diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/AdditionAnimatedNode.java b/ReactAndroid/src/main/java/com/facebook/react/animated/AdditionAnimatedNode.java index 6b72b32e5161..be72e5cdb058 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/AdditionAnimatedNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/AdditionAnimatedNode.java @@ -38,8 +38,9 @@ public void update() { if (animatedNode != null && animatedNode instanceof ValueAnimatedNode) { mValue += ((ValueAnimatedNode) animatedNode).getValue(); } else { - throw new JSApplicationCausedNativeException( - "Illegal node ID set as an input for Animated.Add node"); + //PATCH: COMMENTED + // throw new JSApplicationCausedNativeException( + // "Illegal node ID set as an input for Animated.Add node"); } } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/AnimationDriver.java b/ReactAndroid/src/main/java/com/facebook/react/animated/AnimationDriver.java index cd627d2809a4..c1bf07c5969b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/AnimationDriver.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/AnimationDriver.java @@ -35,7 +35,8 @@ * start animating with the new properties (different destination or spring settings) */ public void resetConfig(ReadableMap config) { - throw new JSApplicationCausedNativeException( - "Animation config for " + getClass().getSimpleName() + " cannot be reset"); + //PATCH: COMMENTED + // throw new JSApplicationCausedNativeException( + // "Animation config for " + getClass().getSimpleName() + " cannot be reset"); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/DiffClampAnimatedNode.java b/ReactAndroid/src/main/java/com/facebook/react/animated/DiffClampAnimatedNode.java index de356762c801..da74e991b55b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/DiffClampAnimatedNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/DiffClampAnimatedNode.java @@ -40,8 +40,10 @@ public void update() { private double getInputNodeValue() { AnimatedNode animatedNode = mNativeAnimatedNodesManager.getNodeById(mInputNodeTag); if (animatedNode == null || !(animatedNode instanceof ValueAnimatedNode)) { - throw new JSApplicationCausedNativeException( - "Illegal node ID set as an input for Animated.DiffClamp node"); + //PATCH: COMMENTED + // throw new JSApplicationCausedNativeException( + // "Illegal node ID set as an input for Animated.DiffClamp node"); + return; } return ((ValueAnimatedNode) animatedNode).getValue(); diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/DivisionAnimatedNode.java b/ReactAndroid/src/main/java/com/facebook/react/animated/DivisionAnimatedNode.java index 505062194510..045806fa7afb 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/DivisionAnimatedNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/DivisionAnimatedNode.java @@ -41,14 +41,18 @@ public void update() { continue; } if (value == 0) { - throw new JSApplicationCausedNativeException( - "Detected a division by zero in Animated.divide node with Animated ID " + mTag); + //PATCH: COMMENTED + // throw new JSApplicationCausedNativeException( + // "Detected a division by zero in Animated.divide node with Animated ID " + mTag); + return; } mValue /= value; - } else { - throw new JSApplicationCausedNativeException( - "Illegal node ID set as an input for Animated.divide node with Animated ID " + mTag); - } + } + //PATCH: COMMENTED + // else { + // throw new JSApplicationCausedNativeException( + // "Illegal node ID set as an input for Animated.divide node with Animated ID " + mTag); + // } } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/EventAnimationDriver.java b/ReactAndroid/src/main/java/com/facebook/react/animated/EventAnimationDriver.java index edc92c238c3b..c4c7e4781986 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/EventAnimationDriver.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/EventAnimationDriver.java @@ -35,7 +35,9 @@ public EventAnimationDriver( @Override public void receiveEvent(int targetTag, String eventName, @Nullable WritableMap event) { if (event == null) { - throw new IllegalArgumentException("Native animated events must have event data."); + //PATCH: COMMENTED + // throw new IllegalArgumentException("Native animated events must have event data."); + return; } // Get the new value for the node by looking into the event map using the provided event path. @@ -51,10 +53,12 @@ public void receiveEvent(int targetTag, String eventName, @Nullable WritableMap } else if (keyType == ReadableType.Array) { currArray = currMap.getArray(key); currMap = null; - } else { - throw new UnexpectedNativeTypeException( - "Unexpected type " + keyType + " for key '" + key + "'"); } + //PATCH: COMMENTED + // else { + // throw new UnexpectedNativeTypeException( + // "Unexpected type " + keyType + " for key '" + key + "'"); + // } } else { int index = Integer.parseInt(mEventPath.get(i)); ReadableType keyType = currArray.getType(index); @@ -64,10 +68,12 @@ public void receiveEvent(int targetTag, String eventName, @Nullable WritableMap } else if (keyType == ReadableType.Array) { currArray = currArray.getArray(index); currMap = null; - } else { - throw new UnexpectedNativeTypeException( - "Unexpected type " + keyType + " for index '" + index + "'"); - } + } + //PATCH: COMMENTED + // else { + // throw new UnexpectedNativeTypeException( + // "Unexpected type " + keyType + " for index '" + index + "'"); + // } } } @@ -83,6 +89,7 @@ public void receiveEvent(int targetTag, String eventName, @Nullable WritableMap @Override public void receiveTouches( String eventName, WritableArray touches, WritableArray changedIndices) { - throw new RuntimeException("receiveTouches is not support by native animated events"); + //PATCH: COMMENTED + // throw new RuntimeException("receiveTouches is not support by native animated events"); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/InterpolationAnimatedNode.java b/ReactAndroid/src/main/java/com/facebook/react/animated/InterpolationAnimatedNode.java index 5a738ae7fbe0..cd2ea0e4cf0b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/InterpolationAnimatedNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/InterpolationAnimatedNode.java @@ -59,8 +59,10 @@ private static double interpolate( case EXTRAPOLATE_TYPE_EXTEND: break; default: - throw new JSApplicationIllegalArgumentException( - "Invalid extrapolation type " + extrapolateLeft + "for left extrapolation"); + //PATCH: COMMENTED + // throw new JSApplicationIllegalArgumentException( + // "Invalid extrapolation type " + extrapolateRight + "for left extrapolation"); + return; } } @@ -74,8 +76,10 @@ private static double interpolate( case EXTRAPOLATE_TYPE_EXTEND: break; default: - throw new JSApplicationIllegalArgumentException( - "Invalid extrapolation type " + extrapolateRight + "for right extrapolation"); + //PATCH: COMMENTED + // throw new JSApplicationIllegalArgumentException( + // "Invalid extrapolation type " + extrapolateRight + "for right extrapolation"); + return; } } @@ -191,10 +195,14 @@ public InterpolationAnimatedNode(ReadableMap config) { @Override public void onAttachedToNode(AnimatedNode parent) { if (mParent != null) { - throw new IllegalStateException("Parent already attached"); + //PATCH: COMMENTED + // throw new IllegalStateException("Parent already attached"); + return; } if (!(parent instanceof ValueAnimatedNode)) { - throw new IllegalArgumentException("Parent is of an invalid type"); + //PATCH: COMMENTED + // throw new IllegalArgumentException("Parent is of an invalid type"); + return; } mParent = (ValueAnimatedNode) parent; } @@ -202,7 +210,9 @@ public void onAttachedToNode(AnimatedNode parent) { @Override public void onDetachedFromNode(AnimatedNode parent) { if (parent != mParent) { - throw new IllegalArgumentException("Invalid parent node provided"); + //PATCH: COMMENTED + // throw new IllegalArgumentException("Invalid parent node provided"); + return; } mParent = null; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/ModulusAnimatedNode.java b/ReactAndroid/src/main/java/com/facebook/react/animated/ModulusAnimatedNode.java index f5ec5b7bb3c9..1c70d7b0a2ac 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/ModulusAnimatedNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/ModulusAnimatedNode.java @@ -30,8 +30,9 @@ public void update() { double value = ((ValueAnimatedNode) animatedNode).getValue(); mValue = (value % mModulus + mModulus) % mModulus; } else { - throw new JSApplicationCausedNativeException( - "Illegal node ID set as an input for Animated.modulus node"); + //PATCH: COMMENTED + // throw new JSApplicationCausedNativeException( + // "Illegal node ID set as an input for Animated.modulus node"); } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/MultiplicationAnimatedNode.java b/ReactAndroid/src/main/java/com/facebook/react/animated/MultiplicationAnimatedNode.java index 1053457a7bd8..3e0d03417b9b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/MultiplicationAnimatedNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/MultiplicationAnimatedNode.java @@ -38,8 +38,9 @@ public void update() { if (animatedNode != null && animatedNode instanceof ValueAnimatedNode) { mValue *= ((ValueAnimatedNode) animatedNode).getValue(); } else { - throw new JSApplicationCausedNativeException( - "Illegal node ID set as an input for Animated.multiply node"); + //PATCH: COMMENTED + // throw new JSApplicationCausedNativeException( + // "Illegal node ID set as an input for Animated.multiply node"); } } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/NativeAnimatedModule.java b/ReactAndroid/src/main/java/com/facebook/react/animated/NativeAnimatedModule.java index 0f52b73c6162..31774ee0d2aa 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/NativeAnimatedModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/NativeAnimatedModule.java @@ -258,7 +258,8 @@ protected void doFrameGuarded(final long frameTimeNanos) { ReactChoreographer.CallbackType.NATIVE_ANIMATED_MODULE, mAnimatedFrameCallback); } catch (Exception ex) { - throw new RuntimeException(ex); + //PATCH: COMMENTED + // throw new RuntimeException(ex); } } }; diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/NativeAnimatedNodesManager.java b/ReactAndroid/src/main/java/com/facebook/react/animated/NativeAnimatedNodesManager.java index bb626bed0b2d..b2f7b1161fd6 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/NativeAnimatedNodesManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/NativeAnimatedNodesManager.java @@ -110,8 +110,9 @@ public boolean hasActiveAnimations() { @UiThread public void createAnimatedNode(int tag, ReadableMap config) { if (mAnimatedNodes.get(tag) != null) { - throw new JSApplicationIllegalArgumentException( - "createAnimatedNode: Animated node [" + tag + "] already exists"); + // throw new JSApplicationIllegalArgumentException( + // "createAnimatedNode: Animated node [" + tag + "] already exists"); + return; } String type = config.getString("type"); final AnimatedNode node; @@ -142,7 +143,8 @@ public void createAnimatedNode(int tag, ReadableMap config) { } else if ("tracking".equals(type)) { node = new TrackingAnimatedNode(config, this); } else { - throw new JSApplicationIllegalArgumentException("Unsupported node type: " + type); + // throw new JSApplicationIllegalArgumentException("Unsupported node type: " + type); + return; } node.mTag = tag; mAnimatedNodes.put(tag, node); @@ -153,8 +155,9 @@ public void createAnimatedNode(int tag, ReadableMap config) { public void updateAnimatedNodeConfig(int tag, ReadableMap config) { AnimatedNode node = mAnimatedNodes.get(tag); if (node == null) { - throw new JSApplicationIllegalArgumentException( - "updateAnimatedNode: Animated node [" + tag + "] does not exist"); + // throw new JSApplicationIllegalArgumentException( + // "updateAnimatedNode: Animated node [" + tag + "] does not exist"); + return; } if (node instanceof AnimatedNodeWithUpdateableConfig) { @@ -174,10 +177,11 @@ public void dropAnimatedNode(int tag) { public void startListeningToAnimatedNodeValue(int tag, AnimatedNodeValueListener listener) { AnimatedNode node = mAnimatedNodes.get(tag); if (node == null || !(node instanceof ValueAnimatedNode)) { - throw new JSApplicationIllegalArgumentException( - "startListeningToAnimatedNodeValue: Animated node [" - + tag - + "] does not exist, or is not a 'value' node"); + // throw new JSApplicationIllegalArgumentException( + // "startListeningToAnimatedNodeValue: Animated node [" + // + tag + // + "] does not exist, or is not a 'value' node"); + return; } ((ValueAnimatedNode) node).setValueListener(listener); } @@ -186,10 +190,11 @@ public void startListeningToAnimatedNodeValue(int tag, AnimatedNodeValueListener public void stopListeningToAnimatedNodeValue(int tag) { AnimatedNode node = mAnimatedNodes.get(tag); if (node == null || !(node instanceof ValueAnimatedNode)) { - throw new JSApplicationIllegalArgumentException( - "startListeningToAnimatedNodeValue: Animated node [" - + tag - + "] does not exist, or is not a 'value' node"); + // throw new JSApplicationIllegalArgumentException( + // "startListeningToAnimatedNodeValue: Animated node [" + // + tag + // + "] does not exist, or is not a 'value' node"); + return; } ((ValueAnimatedNode) node).setValueListener(null); } @@ -198,10 +203,11 @@ public void stopListeningToAnimatedNodeValue(int tag) { public void setAnimatedNodeValue(int tag, double value) { AnimatedNode node = mAnimatedNodes.get(tag); if (node == null || !(node instanceof ValueAnimatedNode)) { - throw new JSApplicationIllegalArgumentException( - "setAnimatedNodeValue: Animated node [" - + tag - + "] does not exist, or is not a 'value' node"); + // throw new JSApplicationIllegalArgumentException( + // "setAnimatedNodeValue: Animated node [" + // + tag + // + "] does not exist, or is not a 'value' node"); + return; } stopAnimationsForNode(node); ((ValueAnimatedNode) node).mValue = value; @@ -212,10 +218,11 @@ public void setAnimatedNodeValue(int tag, double value) { public void setAnimatedNodeOffset(int tag, double offset) { AnimatedNode node = mAnimatedNodes.get(tag); if (node == null || !(node instanceof ValueAnimatedNode)) { - throw new JSApplicationIllegalArgumentException( - "setAnimatedNodeOffset: Animated node [" - + tag - + "] does not exist, or is not a 'value' node"); + // throw new JSApplicationIllegalArgumentException( + // "setAnimatedNodeOffset: Animated node [" + // + tag + // + "] does not exist, or is not a 'value' node"); + return; } ((ValueAnimatedNode) node).mOffset = offset; mUpdatedNodes.put(tag, node); @@ -225,10 +232,11 @@ public void setAnimatedNodeOffset(int tag, double offset) { public void flattenAnimatedNodeOffset(int tag) { AnimatedNode node = mAnimatedNodes.get(tag); if (node == null || !(node instanceof ValueAnimatedNode)) { - throw new JSApplicationIllegalArgumentException( - "flattenAnimatedNodeOffset: Animated node [" - + tag - + "] does not exist, or is not a 'value' node"); + // throw new JSApplicationIllegalArgumentException( + // "flattenAnimatedNodeOffset: Animated node [" + // + tag + // + "] does not exist, or is not a 'value' node"); + return; } ((ValueAnimatedNode) node).flattenOffset(); } @@ -237,10 +245,11 @@ public void flattenAnimatedNodeOffset(int tag) { public void extractAnimatedNodeOffset(int tag) { AnimatedNode node = mAnimatedNodes.get(tag); if (node == null || !(node instanceof ValueAnimatedNode)) { - throw new JSApplicationIllegalArgumentException( - "extractAnimatedNodeOffset: Animated node [" - + tag - + "] does not exist, or is not a 'value' node"); + // throw new JSApplicationIllegalArgumentException( + // "extractAnimatedNodeOffset: Animated node [" + // + tag + // + "] does not exist, or is not a 'value' node"); + return; } ((ValueAnimatedNode) node).extractOffset(); } @@ -250,15 +259,17 @@ public void startAnimatingNode( int animationId, int animatedNodeTag, ReadableMap animationConfig, Callback endCallback) { AnimatedNode node = mAnimatedNodes.get(animatedNodeTag); if (node == null) { - throw new JSApplicationIllegalArgumentException( - "startAnimatingNode: Animated node [" + animatedNodeTag + "] does not exist"); + // throw new JSApplicationIllegalArgumentException( + // "startAnimatingNode: Animated node [" + animatedNodeTag + "] does not exist"); + return; } if (!(node instanceof ValueAnimatedNode)) { - throw new JSApplicationIllegalArgumentException( - "startAnimatingNode: Animated node [" - + animatedNodeTag - + "] should be of type " - + ValueAnimatedNode.class.getName()); + // throw new JSApplicationIllegalArgumentException( + // "startAnimatingNode: Animated node [" + // + animatedNodeTag + // + "] should be of type " + // + ValueAnimatedNode.class.getName()); + return; } final AnimationDriver existingDriver = mActiveAnimations.get(animationId); @@ -278,8 +289,9 @@ public void startAnimatingNode( } else if ("decay".equals(type)) { animation = new DecayAnimation(animationConfig); } else { - throw new JSApplicationIllegalArgumentException( - "startAnimatingNode: Unsupported animation type [" + animatedNodeTag + "]: " + type); + // throw new JSApplicationIllegalArgumentException( + // "startAnimatingNode: Unsupported animation type [" + animatedNodeTag + "]: " + type); + return; } animation.mId = animationId; animation.mEndCallback = endCallback; @@ -357,17 +369,19 @@ public void stopAnimation(int animationId) { public void connectAnimatedNodes(int parentNodeTag, int childNodeTag) { AnimatedNode parentNode = mAnimatedNodes.get(parentNodeTag); if (parentNode == null) { - throw new JSApplicationIllegalArgumentException( - "connectAnimatedNodes: Animated node with tag (parent) [" - + parentNodeTag - + "] does not exist"); + // throw new JSApplicationIllegalArgumentException( + // "connectAnimatedNodes: Animated node with tag (parent) [" + // + parentNodeTag + // + "] does not exist"); + return; } AnimatedNode childNode = mAnimatedNodes.get(childNodeTag); if (childNode == null) { - throw new JSApplicationIllegalArgumentException( - "connectAnimatedNodes: Animated node with tag (child) [" - + childNodeTag - + "] does not exist"); + // throw new JSApplicationIllegalArgumentException( + // "connectAnimatedNodes: Animated node with tag (child) [" + // + childNodeTag + // + "] does not exist"); + return; } parentNode.addChild(childNode); mUpdatedNodes.put(childNodeTag, childNode); @@ -376,17 +390,19 @@ public void connectAnimatedNodes(int parentNodeTag, int childNodeTag) { public void disconnectAnimatedNodes(int parentNodeTag, int childNodeTag) { AnimatedNode parentNode = mAnimatedNodes.get(parentNodeTag); if (parentNode == null) { - throw new JSApplicationIllegalArgumentException( - "disconnectAnimatedNodes: Animated node with tag (parent) [" - + parentNodeTag - + "] does not exist"); + // throw new JSApplicationIllegalArgumentException( + // "disconnectAnimatedNodes: Animated node with tag (parent) [" + // + parentNodeTag + // + "] does not exist"); + return; } AnimatedNode childNode = mAnimatedNodes.get(childNodeTag); if (childNode == null) { - throw new JSApplicationIllegalArgumentException( - "disconnectAnimatedNodes: Animated node with tag (child) [" - + childNodeTag - + "] does not exist"); + // throw new JSApplicationIllegalArgumentException( + // "disconnectAnimatedNodes: Animated node with tag (child) [" + // + childNodeTag + // + "] does not exist"); + return; } parentNode.removeChild(childNode); mUpdatedNodes.put(childNodeTag, childNode); @@ -396,22 +412,25 @@ public void disconnectAnimatedNodes(int parentNodeTag, int childNodeTag) { public void connectAnimatedNodeToView(int animatedNodeTag, int viewTag) { AnimatedNode node = mAnimatedNodes.get(animatedNodeTag); if (node == null) { - throw new JSApplicationIllegalArgumentException( - "connectAnimatedNodeToView: Animated node with tag [" - + animatedNodeTag - + "] does not exist"); + // throw new JSApplicationIllegalArgumentException( + // "connectAnimatedNodeToView: Animated node with tag [" + // + animatedNodeTag + // + "] does not exist"); + return; } if (!(node instanceof PropsAnimatedNode)) { - throw new JSApplicationIllegalArgumentException( - "connectAnimatedNodeToView: Animated node connected to view [" - + viewTag - + "] should be of type " - + PropsAnimatedNode.class.getName()); + // throw new JSApplicationIllegalArgumentException( + // "connectAnimatedNodeToView: Animated node connected to view [" + // + viewTag + // + "] should be of type " + // + PropsAnimatedNode.class.getName()); + return; } if (mReactApplicationContext == null) { - throw new IllegalStateException( - "connectAnimatedNodeToView: Animated node could not be connected, no ReactApplicationContext: " - + viewTag); + // throw new IllegalStateException( + // "connectAnimatedNodeToView: Animated node could not be connected, no ReactApplicationContext: " + // + viewTag); + return; } @Nullable @@ -435,17 +454,19 @@ public void connectAnimatedNodeToView(int animatedNodeTag, int viewTag) { public void disconnectAnimatedNodeFromView(int animatedNodeTag, int viewTag) { AnimatedNode node = mAnimatedNodes.get(animatedNodeTag); if (node == null) { - throw new JSApplicationIllegalArgumentException( - "disconnectAnimatedNodeFromView: Animated node with tag [" - + animatedNodeTag - + "] does not exist"); + // throw new JSApplicationIllegalArgumentException( + // "disconnectAnimatedNodeFromView: Animated node with tag [" + // + animatedNodeTag + // + "] does not exist"); + return; } if (!(node instanceof PropsAnimatedNode)) { - throw new JSApplicationIllegalArgumentException( - "disconnectAnimatedNodeFromView: Animated node connected to view [" - + viewTag - + "] should be of type " - + PropsAnimatedNode.class.getName()); + // throw new JSApplicationIllegalArgumentException( + // "disconnectAnimatedNodeFromView: Animated node connected to view [" + // + viewTag + // + "] should be of type " + // + PropsAnimatedNode.class.getName()); + return; } PropsAnimatedNode propsAnimatedNode = (PropsAnimatedNode) node; propsAnimatedNode.disconnectFromView(viewTag); @@ -455,8 +476,9 @@ public void disconnectAnimatedNodeFromView(int animatedNodeTag, int viewTag) { public void getValue(int tag, Callback callback) { AnimatedNode node = mAnimatedNodes.get(tag); if (node == null || !(node instanceof ValueAnimatedNode)) { - throw new JSApplicationIllegalArgumentException( - "getValue: Animated node with tag [" + tag + "] does not exist or is not a 'value' node"); + // throw new JSApplicationIllegalArgumentException( + // "getValue: Animated node with tag [" + tag + "] does not exist or is not a 'value' node"); + return; } double value = ((ValueAnimatedNode) node).getValue(); if (callback != null) { @@ -490,9 +512,10 @@ public void restoreDefaultValues(int animatedNodeTag) { return; } if (!(node instanceof PropsAnimatedNode)) { - throw new JSApplicationIllegalArgumentException( - "Animated node connected to view [?] should be of type " - + PropsAnimatedNode.class.getName()); + // throw new JSApplicationIllegalArgumentException( + // "Animated node connected to view [?] should be of type " + // + PropsAnimatedNode.class.getName()); + return; } PropsAnimatedNode propsAnimatedNode = (PropsAnimatedNode) node; propsAnimatedNode.restoreDefaultValues(); @@ -504,17 +527,19 @@ public void addAnimatedEventToView( int nodeTag = eventMapping.getInt("animatedValueTag"); AnimatedNode node = mAnimatedNodes.get(nodeTag); if (node == null) { - throw new JSApplicationIllegalArgumentException( - "addAnimatedEventToView: Animated node with tag [" + nodeTag + "] does not exist"); + // throw new JSApplicationIllegalArgumentException( + // "addAnimatedEventToView: Animated node with tag [" + nodeTag + "] does not exist"); + return; } if (!(node instanceof ValueAnimatedNode)) { - throw new JSApplicationIllegalArgumentException( - "addAnimatedEventToView: Animated node on view [" - + viewTag - + "] connected to event handler (" - + eventHandlerName - + ") should be of type " - + ValueAnimatedNode.class.getName()); + // throw new JSApplicationIllegalArgumentException( + // "addAnimatedEventToView: Animated node on view [" + // + viewTag + // + "] connected to event handler (" + // + eventHandlerName + // + ") should be of type " + // + ValueAnimatedNode.class.getName()); + return; } ReadableArray path = eventMapping.getArray("nativeEventPath"); @@ -813,7 +838,7 @@ private void updateNodes(List nodes) { // or fix the root cause ReactSoftExceptionLogger.logSoftException(TAG, new ReactNoCrashSoftException(ex)); } else { - throw ex; + // throw ex; } } else { mWarnedAboutGraphTraversal = false; diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/PropsAnimatedNode.java b/ReactAndroid/src/main/java/com/facebook/react/animated/PropsAnimatedNode.java index aacf6bf1c3f7..c95a207d984d 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/PropsAnimatedNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/PropsAnimatedNode.java @@ -48,8 +48,9 @@ public void connectToView(int viewTag, UIManager uiManager) { if (mConnectedViewTag != -1) { - throw new JSApplicationIllegalArgumentException( - "Animated node " + mTag + " is " + "already attached to a view: " + mConnectedViewTag); + // throw new JSApplicationIllegalArgumentException( + // "Animated node " + mTag + " is " + "already attached to a view: " + mConnectedViewTag); + return; } mConnectedViewTag = viewTag; mUIManager = uiManager; @@ -57,12 +58,13 @@ public void connectToView(int viewTag, UIManager uiManager) { public void disconnectFromView(int viewTag) { if (mConnectedViewTag != viewTag && mConnectedViewTag != -1) { - throw new JSApplicationIllegalArgumentException( - "Attempting to disconnect view that has " - + "not been connected with the given animated node: " - + viewTag - + " but is connected to view " - + mConnectedViewTag); + // throw new JSApplicationIllegalArgumentException( + // "Attempting to disconnect view that has " + // + "not been connected with the given animated node: " + // + viewTag + // + " but is connected to view " + // + mConnectedViewTag); + return; } mConnectedViewTag = -1; @@ -97,7 +99,8 @@ public final void updateView() { for (Map.Entry entry : mPropNodeMapping.entrySet()) { @Nullable AnimatedNode node = mNativeAnimatedNodesManager.getNodeById(entry.getValue()); if (node == null) { - throw new IllegalArgumentException("Mapped property node does not exists"); + // throw new IllegalArgumentException("Mapped property node does not exists"); + return; } else if (node instanceof StyleAnimatedNode) { ((StyleAnimatedNode) node).collectViewUpdates(mPropMap); } else if (node instanceof ValueAnimatedNode) { @@ -110,8 +113,9 @@ public final void updateView() { } else if (node instanceof ColorAnimatedNode) { mPropMap.putInt(entry.getKey(), ((ColorAnimatedNode) node).getColor()); } else { - throw new IllegalArgumentException( - "Unsupported type of node used in property node " + node.getClass()); + // throw new IllegalArgumentException( + // "Unsupported type of node used in property node " + node.getClass()); + return; } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/StyleAnimatedNode.java b/ReactAndroid/src/main/java/com/facebook/react/animated/StyleAnimatedNode.java index 68ef6a4186e9..ffd939068578 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/StyleAnimatedNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/StyleAnimatedNode.java @@ -38,7 +38,8 @@ public void collectViewUpdates(JavaOnlyMap propsMap) { for (Map.Entry entry : mPropMapping.entrySet()) { @Nullable AnimatedNode node = mNativeAnimatedNodesManager.getNodeById(entry.getValue()); if (node == null) { - throw new IllegalArgumentException("Mapped style node does not exists"); + // throw new IllegalArgumentException("Mapped style node does not exists"); + return; } else if (node instanceof TransformAnimatedNode) { ((TransformAnimatedNode) node).collectViewUpdates(propsMap); } else if (node instanceof ValueAnimatedNode) { @@ -46,8 +47,9 @@ public void collectViewUpdates(JavaOnlyMap propsMap) { } else if (node instanceof ColorAnimatedNode) { propsMap.putInt(entry.getKey(), ((ColorAnimatedNode) node).getColor()); } else { - throw new IllegalArgumentException( - "Unsupported type of node used in property node " + node.getClass()); + // throw new IllegalArgumentException( + // "Unsupported type of node used in property node " + node.getClass()); + return; } } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/SubtractionAnimatedNode.java b/ReactAndroid/src/main/java/com/facebook/react/animated/SubtractionAnimatedNode.java index 8b13969f422b..2dbd3e93a3d2 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/SubtractionAnimatedNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/SubtractionAnimatedNode.java @@ -42,8 +42,8 @@ public void update() { mValue -= value; } } else { - throw new JSApplicationCausedNativeException( - "Illegal node ID set as an input for Animated.subtract node"); + // throw new JSApplicationCausedNativeException( + // "Illegal node ID set as an input for Animated.subtract node"); } } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/TransformAnimatedNode.java b/ReactAndroid/src/main/java/com/facebook/react/animated/TransformAnimatedNode.java index 8b3ec593d4ec..72a5bd40fbfd 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/TransformAnimatedNode.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/TransformAnimatedNode.java @@ -66,12 +66,14 @@ public void collectViewUpdates(JavaOnlyMap propsMap) { int nodeTag = ((AnimatedTransformConfig) transformConfig).mNodeTag; AnimatedNode node = mNativeAnimatedNodesManager.getNodeById(nodeTag); if (node == null) { - throw new IllegalArgumentException("Mapped style node does not exists"); + // throw new IllegalArgumentException("Mapped style node does not exists"); + return; } else if (node instanceof ValueAnimatedNode) { value = ((ValueAnimatedNode) node).getValue(); } else { - throw new IllegalArgumentException( - "Unsupported type of node used as a transform child " + "node " + node.getClass()); + // throw new IllegalArgumentException( + // "Unsupported type of node used as a transform child " + "node " + node.getClass()); + return; } } else { value = ((StaticTransformConfig) transformConfig).mValue; diff --git a/packages/assets/.npmignore b/packages/assets/.npmignore deleted file mode 100644 index 9b166b095d3f..000000000000 --- a/packages/assets/.npmignore +++ /dev/null @@ -1,3 +0,0 @@ -**/__mocks__/** -**/__tests__/** -BUCK diff --git a/packages/assets/BUCK b/packages/assets/BUCK deleted file mode 100644 index df68edf8b3a9..000000000000 --- a/packages/assets/BUCK +++ /dev/null @@ -1,30 +0,0 @@ -load("@fbsource//tools/build_defs/third_party:yarn_defs.bzl", "yarn_workspace") -load("@fbsource//xplat/js:JS_DEFS.bzl", "rn_library") - -rn_library( - name = "assets", - labels = [ - "pfh:ReactNative_CommonInfrastructurePlaceholder", - ], - skip_processors = True, - visibility = ["PUBLIC"], -) - -yarn_workspace( - name = "yarn-workspace", - srcs = glob( - [ - "**/*.js", - "**/*.json", - ], - exclude = [ - "**/__fixtures__/**", - "**/__flowtests__/**", - "**/__mocks__/**", - "**/__tests__/**", - "**/node_modules/**", - "**/node_modules/.bin/**", - ], - ), - visibility = ["PUBLIC"], -) diff --git a/packages/assets/__tests__/path-support-test.js b/packages/assets/__tests__/path-support-test.js deleted file mode 100644 index fa96053c3014..000000000000 --- a/packages/assets/__tests__/path-support-test.js +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -import {getAndroidResourceFolderName} from '../path-support'; - -const DRAWABLE_ASSET = { - __packager_asset: true, - fileSystemLocation: 'foo.png', - httpServerLocation: '/assets/', - width: 150, - height: 150, - scales: [1], - hash: '__HASH__', - name: 'foo', - type: 'png', -}; - -const NON_DRAWABLE_ASSET = { - __packager_asset: true, - fileSystemLocation: 'foo.txt', - httpServerLocation: '/assets/', - width: 150, - height: 150, - scales: [1], - hash: '__HASH__', - name: 'foo', - type: 'txt', -}; - -describe('getAndroidResourceFolderName', () => { - test('supports the six primary density buckets', () => { - expect(getAndroidResourceFolderName(DRAWABLE_ASSET, 0.75)).toBe( - 'drawable-ldpi', - ); - expect(getAndroidResourceFolderName(DRAWABLE_ASSET, 1)).toBe( - 'drawable-mdpi', - ); - expect(getAndroidResourceFolderName(DRAWABLE_ASSET, 1.5)).toBe( - 'drawable-hdpi', - ); - expect(getAndroidResourceFolderName(DRAWABLE_ASSET, 2)).toBe( - 'drawable-xhdpi', - ); - expect(getAndroidResourceFolderName(DRAWABLE_ASSET, 3)).toBe( - 'drawable-xxhdpi', - ); - expect(getAndroidResourceFolderName(DRAWABLE_ASSET, 4)).toBe( - 'drawable-xxxhdpi', - ); - }); - - test('supports nonstandard densities', () => { - expect(getAndroidResourceFolderName(DRAWABLE_ASSET, 1.25)).toBe( - 'drawable-200dpi', - ); - expect(getAndroidResourceFolderName(DRAWABLE_ASSET, 1.66)).toBe( - 'drawable-266dpi', - ); - expect(getAndroidResourceFolderName(DRAWABLE_ASSET, 1.33)).toBe( - 'drawable-213dpi', - ); // ~tvdpi - }); - - test('throws if the density cannot be processed', () => { - expect(() => getAndroidResourceFolderName(DRAWABLE_ASSET, -1)).toThrow(); - expect(() => getAndroidResourceFolderName(DRAWABLE_ASSET, 0)).toThrow(); - expect(() => - getAndroidResourceFolderName(DRAWABLE_ASSET, Infinity), - ).toThrow(); - }); - - test('returns "raw" for non-drawables', () => { - expect(getAndroidResourceFolderName(NON_DRAWABLE_ASSET, 0.75)).toBe('raw'); - expect(getAndroidResourceFolderName(NON_DRAWABLE_ASSET, 1)).toBe('raw'); - expect(getAndroidResourceFolderName(NON_DRAWABLE_ASSET, 1.25)).toBe('raw'); - }); -}); diff --git a/packages/assets/package.json b/packages/assets/package.json deleted file mode 100644 index 885e71753388..000000000000 --- a/packages/assets/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "@react-native/assets", - "version": "1.0.0", - "description": "Asset support code for React Native.", - "repository": { - "type": "git", - "url": "git@github.com:facebook/react-native.git", - "directory": "packages/assets" - }, - "license": "MIT" -} diff --git a/packages/assets/path-support.js b/packages/assets/path-support.js deleted file mode 100644 index a6c30d42375a..000000000000 --- a/packages/assets/path-support.js +++ /dev/null @@ -1,92 +0,0 @@ -/** - * 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 - * @flow strict - */ - -'use strict'; - -import type {PackagerAsset} from './registry.js'; - -const androidScaleSuffix = { - '0.75': 'ldpi', - '1': 'mdpi', - '1.5': 'hdpi', - '2': 'xhdpi', - '3': 'xxhdpi', - '4': 'xxxhdpi', -}; - -const ANDROID_BASE_DENSITY = 160; - -/** - * FIXME: using number to represent discrete scale numbers is fragile in essence because of - * floating point numbers imprecision. - */ -function getAndroidAssetSuffix(scale: number): string { - if (scale.toString() in androidScaleSuffix) { - return androidScaleSuffix[scale.toString()]; - } - // NOTE: Android Gradle Plugin does not fully support the nnndpi format. - // See https://issuetracker.google.com/issues/72884435 - if (Number.isFinite(scale) && scale > 0) { - return Math.round(scale * ANDROID_BASE_DENSITY) + 'dpi'; - } - throw new Error('no such scale ' + scale.toString()); -} - -// See https://developer.android.com/guide/topics/resources/drawable-resource.html -const drawableFileTypes = new Set([ - 'gif', - 'jpeg', - 'jpg', - 'ktx', - 'png', - 'svg', - 'webp', - 'xml', -]); - -function getAndroidResourceFolderName( - asset: PackagerAsset, - scale: number, -): string | $TEMPORARY$string<'raw'> { - if (!drawableFileTypes.has(asset.type)) { - return 'raw'; - } - const suffix = getAndroidAssetSuffix(scale); - if (!suffix) { - throw new Error( - "Don't know which android drawable suffix to use for scale: " + - scale + - '\nAsset: ' + - JSON.stringify(asset, null, '\t') + - '\nPossible scales are:' + - JSON.stringify(androidScaleSuffix, null, '\t'), - ); - } - return 'drawable-' + suffix; -} - -function getAndroidResourceIdentifier(asset: PackagerAsset): string { - return (getBasePath(asset) + '/' + asset.name) - .toLowerCase() - .replace(/\//g, '_') // Encode folder structure in file name - .replace(/([^a-z0-9_])/g, '') // Remove illegal chars - .replace(/^assets_/, ''); // Remove "assets_" prefix -} - -function getBasePath(asset: PackagerAsset): string { - const basePath = asset.httpServerLocation; - return basePath.startsWith('/') ? basePath.substr(1) : basePath; -} - -module.exports = { - getAndroidResourceFolderName, - getAndroidResourceIdentifier, - getBasePath, -}; diff --git a/packages/assets/registry.js b/packages/assets/registry.js deleted file mode 100644 index 02470da3c496..000000000000 --- a/packages/assets/registry.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -export type PackagerAsset = { - +__packager_asset: boolean, - +fileSystemLocation: string, - +httpServerLocation: string, - +width: ?number, - +height: ?number, - +scales: Array, - +hash: string, - +name: string, - +type: string, - ... -}; - -const assets: Array = []; - -function registerAsset(asset: PackagerAsset): number { - // `push` returns new array length, so the first asset will - // get id 1 (not 0) to make the value truthy - return assets.push(asset); -} - -function getAssetByID(assetId: number): PackagerAsset { - return assets[assetId - 1]; -} - -module.exports = {registerAsset, getAssetByID}; diff --git a/packages/babel-plugin-codegen/BUCK b/packages/babel-plugin-codegen/BUCK deleted file mode 100644 index 8fd38289431b..000000000000 --- a/packages/babel-plugin-codegen/BUCK +++ /dev/null @@ -1,23 +0,0 @@ -load("@fbsource//tools/build_defs/third_party:yarn_defs.bzl", "yarn_workspace") - -yarn_workspace( - name = "yarn-workspace", - srcs = glob( - ["**/*.js"], - exclude = [ - "**/__fixtures__/**", - "**/__flowtests__/**", - "**/__mocks__/**", - "**/__server_snapshot_tests__/**", - "**/__tests__/**", - "**/node_modules/**", - "**/node_modules/.bin/**", - "**/.*", - "**/.*/**", - "**/.*/.*", - "**/*.xcodeproj/**", - "**/*.xcworkspace/**", - ], - ), - visibility = ["PUBLIC"], -) diff --git a/packages/babel-plugin-codegen/__test_fixtures__/failures.js b/packages/babel-plugin-codegen/__test_fixtures__/failures.js deleted file mode 100644 index 908a83488e07..000000000000 --- a/packages/babel-plugin-codegen/__test_fixtures__/failures.js +++ /dev/null @@ -1,90 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -const COMMANDS_EXPORTED_WITH_DIFFERENT_NAME = ` -// @flow - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {ViewProps} from 'ViewPropTypes'; -import type {NativeComponentType} from 'codegenNativeComponent'; - -type ModuleProps = $ReadOnly<{| - ...ViewProps, -|}>; - -type NativeType = NativeComponentType; - -interface NativeCommands { - +hotspotUpdate: (viewRef: React.ElementRef) => void; -} - -export const Foo = codegenNativeCommands(); - -export default (codegenNativeComponent('Module'): NativeType); -`; - -const OTHER_COMMANDS_EXPORT = ` -// @flow - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {ViewProps} from 'ViewPropTypes'; -import type {NativeComponentType} from 'codegenNativeComponent'; - -type ModuleProps = $ReadOnly<{| - ...ViewProps, -|}>; - -type NativeType = NativeComponentType; - -interface NativeCommands { - +hotspotUpdate: (viewRef: React.ElementRef) => void; -} - -export const Commands = 4; - -export default (codegenNativeComponent('Module'): NativeType); -`; - -const COMMANDS_EXPORTED_WITH_SHORTHAND = ` -// @flow - -const codegenNativeComponent = require('codegenNativeComponent'); -import type {NativeComponentType} from 'codegenNativeComponent'; - -import type {ViewProps} from 'ViewPropTypes'; - -type ModuleProps = $ReadOnly<{| - ...ViewProps, -|}>; - -type NativeType = NativeComponentType; - -interface NativeCommands { - +hotspotUpdate: (viewRef: React.ElementRef) => void; -} - -const Commands = 4; - -export {Commands}; - -export default (codegenNativeComponent('Module'): NativeType); -`; - -module.exports = { - 'CommandsExportedWithDifferentNameNativeComponent.js': - COMMANDS_EXPORTED_WITH_DIFFERENT_NAME, - 'CommandsExportedWithShorthandNativeComponent.js': - COMMANDS_EXPORTED_WITH_SHORTHAND, - 'OtherCommandsExportNativeComponent.js': OTHER_COMMANDS_EXPORT, -}; diff --git a/packages/babel-plugin-codegen/__test_fixtures__/fixtures.js b/packages/babel-plugin-codegen/__test_fixtures__/fixtures.js deleted file mode 100644 index a55b940eabcc..000000000000 --- a/packages/babel-plugin-codegen/__test_fixtures__/fixtures.js +++ /dev/null @@ -1,110 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; -const NOT_A_NATIVE_COMPONENT = ` -const requireNativeComponent = require('requireNativeComponent'); - -export default 'Not a view config' -`; - -const FULL_NATIVE_COMPONENT = ` -// @flow - -const codegenNativeCommands = require('codegenNativeCommands'); -const codegenNativeComponent = require('codegenNativeComponent'); - -import type { - Int32, - BubblingEventHandler, - DirectEventHandler, - WithDefault, -} from 'CodegenFlowtypes'; -import type {NativeComponentType} from 'codegenNativeComponent'; - -import type {ViewProps} from 'ViewPropTypes'; - -type ModuleProps = $ReadOnly<{| - ...ViewProps, - - // Props - boolean_default_true_optional_both?: WithDefault, - - // Events - onDirectEventDefinedInlineNull: DirectEventHandler, - onBubblingEventDefinedInlineNull: BubblingEventHandler, -|}>; - -type NativeType = NativeComponentType; - -interface NativeCommands { - +hotspotUpdate: (viewRef: React.ElementRef, x: Int32, y: Int32) => void; - +scrollTo: (viewRef: React.ElementRef, y: Int32, animated: boolean) => void; -} - -export const Commands = codegenNativeCommands({ - supportedCommands: ['hotspotUpdate', 'scrollTo'], -}); - -export default codegenNativeComponent('Module', { - interfaceOnly: true, - paperComponentName: 'RCTModule', -}); -`; - -const FULL_NATIVE_COMPONENT_WITH_TYPE_EXPORT = ` -// @flow - -const codegenNativeCommands = require('codegenNativeCommands'); -const codegenNativeComponent = require('codegenNativeComponent'); -import type {NativeComponentType} from 'codegenNativeComponent'; - -import type { - Int32, - BubblingEventHandler, - DirectEventHandler, - WithDefault, -} from 'CodegenFlowtypes'; - -import type {ViewProps} from 'ViewPropTypes'; - -type ModuleProps = $ReadOnly<{| - ...ViewProps, - - // Props - boolean_default_true_optional_both?: WithDefault, - - // Events - onDirectEventDefinedInlineNull: DirectEventHandler, - onBubblingEventDefinedInlineNull: BubblingEventHandler, -|}>; - -type NativeType = NativeComponentType; - -interface NativeCommands { - +hotspotUpdate: (viewRef: React.ElementRef, x: Int32, y: Int32) => void; - +scrollTo: (viewRef: React.ElementRef, y: Int32, animated: boolean) => void; -} - -export const Commands = codegenNativeCommands({ - supportedCommands: ['hotspotUpdate', 'scrollTo'], -}); - -export default (codegenNativeComponent('Module', { - interfaceOnly: true, - paperComponentName: 'RCTModule', -}): NativeType); -`; - -module.exports = { - 'NotANativeComponent.js': NOT_A_NATIVE_COMPONENT, - 'FullNativeComponent.js': FULL_NATIVE_COMPONENT, - 'FullTypedNativeComponent.js': FULL_NATIVE_COMPONENT_WITH_TYPE_EXPORT, -}; diff --git a/packages/babel-plugin-codegen/__tests__/__snapshots__/index-test.js.snap b/packages/babel-plugin-codegen/__tests__/__snapshots__/index-test.js.snap deleted file mode 100644 index 5aecf0862f11..000000000000 --- a/packages/babel-plugin-codegen/__tests__/__snapshots__/index-test.js.snap +++ /dev/null @@ -1,165 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`Babel plugin inline view configs can inline config for FullNativeComponent.js 1`] = ` -"// @flow - -const codegenNativeCommands = require('codegenNativeCommands'); -const codegenNativeComponent = require('codegenNativeComponent'); -import type { Int32, BubblingEventHandler, DirectEventHandler, WithDefault } from 'CodegenFlowtypes'; -import type { NativeComponentType } from 'codegenNativeComponent'; -import type { ViewProps } from 'ViewPropTypes'; -type ModuleProps = $ReadOnly<{| - ...ViewProps, - // Props - boolean_default_true_optional_both?: WithDefault, - // Events - onDirectEventDefinedInlineNull: DirectEventHandler, - onBubblingEventDefinedInlineNull: BubblingEventHandler, -|}>; -type NativeType = NativeComponentType; -interface NativeCommands { - +hotspotUpdate: (viewRef: React.ElementRef, x: Int32, y: Int32) => void, - +scrollTo: (viewRef: React.ElementRef, y: Int32, animated: boolean) => void, -} -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); -const { - ConditionallyIgnoredEventHandlers -} = require('react-native/Libraries/NativeComponent/ViewConfigIgnore'); -const { - dispatchCommand -} = require(\\"react-native/Libraries/ReactNative/RendererProxy\\"); -let nativeComponentName = 'RCTModule'; -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'RCTModule', - bubblingEventTypes: { - topBubblingEventDefinedInlineNull: { - phasedRegistrationNames: { - captured: 'onBubblingEventDefinedInlineNullCapture', - bubbled: 'onBubblingEventDefinedInlineNull' - } - } - }, - directEventTypes: { - topDirectEventDefinedInlineNull: { - registrationName: 'onDirectEventDefinedInlineNull' - } - }, - validAttributes: { - boolean_default_true_optional_both: true, - ...ConditionallyIgnoredEventHandlers({ - onDirectEventDefinedInlineNull: true, - onBubblingEventDefinedInlineNull: true - }) - } -}; -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -export const Commands = { - hotspotUpdate(ref, x, y) { - dispatchCommand(ref, \\"hotspotUpdate\\", [x, y]); - }, - scrollTo(ref, y, animated) { - dispatchCommand(ref, \\"scrollTo\\", [y, animated]); - } -};" -`; - -exports[`Babel plugin inline view configs can inline config for FullTypedNativeComponent.js 1`] = ` -"// @flow - -const codegenNativeCommands = require('codegenNativeCommands'); -const codegenNativeComponent = require('codegenNativeComponent'); -import type { NativeComponentType } from 'codegenNativeComponent'; -import type { Int32, BubblingEventHandler, DirectEventHandler, WithDefault } from 'CodegenFlowtypes'; -import type { ViewProps } from 'ViewPropTypes'; -type ModuleProps = $ReadOnly<{| - ...ViewProps, - // Props - boolean_default_true_optional_both?: WithDefault, - // Events - onDirectEventDefinedInlineNull: DirectEventHandler, - onBubblingEventDefinedInlineNull: BubblingEventHandler, -|}>; -type NativeType = NativeComponentType; -interface NativeCommands { - +hotspotUpdate: (viewRef: React.ElementRef, x: Int32, y: Int32) => void, - +scrollTo: (viewRef: React.ElementRef, y: Int32, animated: boolean) => void, -} -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); -const { - ConditionallyIgnoredEventHandlers -} = require('react-native/Libraries/NativeComponent/ViewConfigIgnore'); -const { - dispatchCommand -} = require(\\"react-native/Libraries/ReactNative/RendererProxy\\"); -let nativeComponentName = 'RCTModule'; -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'RCTModule', - bubblingEventTypes: { - topBubblingEventDefinedInlineNull: { - phasedRegistrationNames: { - captured: 'onBubblingEventDefinedInlineNullCapture', - bubbled: 'onBubblingEventDefinedInlineNull' - } - } - }, - directEventTypes: { - topDirectEventDefinedInlineNull: { - registrationName: 'onDirectEventDefinedInlineNull' - } - }, - validAttributes: { - boolean_default_true_optional_both: true, - ...ConditionallyIgnoredEventHandlers({ - onDirectEventDefinedInlineNull: true, - onBubblingEventDefinedInlineNull: true - }) - } -}; -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -export const Commands = { - hotspotUpdate(ref, x, y) { - dispatchCommand(ref, \\"hotspotUpdate\\", [x, y]); - }, - scrollTo(ref, y, animated) { - dispatchCommand(ref, \\"scrollTo\\", [y, animated]); - } -};" -`; - -exports[`Babel plugin inline view configs can inline config for NotANativeComponent.js 1`] = ` -"const requireNativeComponent = require('requireNativeComponent'); -export default 'Not a view config';" -`; - -exports[`Babel plugin inline view configs fails on inline config for CommandsExportedWithDifferentNameNativeComponent.js 1`] = ` -"/CommandsExportedWithDifferentNameNativeComponent.js: Native commands must be exported with the name 'Commands' - 17 | } - 18 | -> 19 | export const Foo = codegenNativeCommands(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - 20 | - 21 | export default (codegenNativeComponent('Module'): NativeType); - 22 |" -`; - -exports[`Babel plugin inline view configs fails on inline config for CommandsExportedWithShorthandNativeComponent.js 1`] = ` -"/CommandsExportedWithShorthandNativeComponent.js: 'Commands' is a reserved export and may only be used to export the result of codegenNativeCommands. - 19 | const Commands = 4; - 20 | -> 21 | export {Commands}; - | ^^^^^^^^^^^^^^^^^^ - 22 | - 23 | export default (codegenNativeComponent('Module'): NativeType); - 24 |" -`; - -exports[`Babel plugin inline view configs fails on inline config for OtherCommandsExportNativeComponent.js 1`] = ` -"/OtherCommandsExportNativeComponent.js: 'Commands' is a reserved export and may only be used to export the result of codegenNativeCommands. - 17 | } - 18 | -> 19 | export const Commands = 4; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ - 20 | - 21 | export default (codegenNativeComponent('Module'): NativeType); - 22 |" -`; diff --git a/packages/babel-plugin-codegen/__tests__/index-test.js b/packages/babel-plugin-codegen/__tests__/index-test.js deleted file mode 100644 index 20195b5ea403..000000000000 --- a/packages/babel-plugin-codegen/__tests__/index-test.js +++ /dev/null @@ -1,50 +0,0 @@ -/** - * 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 - * @oncall react_native - */ - -'use strict'; - -const {transform: babelTransform} = require('@babel/core'); -const fixtures = require('../__test_fixtures__/fixtures.js'); -const failures = require('../__test_fixtures__/failures.js'); - -const transform = (fixture, filename) => - babelTransform(fixture, { - babelrc: false, - browserslistConfigFile: false, - cwd: '/', - filename: filename, - highlightCode: false, - plugins: [require('@babel/plugin-syntax-flow'), require('../index')], - }).code; - -describe('Babel plugin inline view configs', () => { - Object.keys(fixtures) - .sort() - .forEach(fixtureName => { - it(`can inline config for ${fixtureName}`, () => { - expect(transform(fixtures[fixtureName], fixtureName)).toMatchSnapshot(); - }); - }); - - Object.keys(failures) - .sort() - .forEach(fixtureName => { - it(`fails on inline config for ${fixtureName}`, () => { - expect(() => { - try { - transform(failures[fixtureName], fixtureName); - } catch (err) { - err.message = err.message.replace(/^[A-z]:\\/g, '/'); // Ensure platform consistent snapshots. - throw err; - } - }).toThrowErrorMatchingSnapshot(); - }); - }); -}); diff --git a/packages/babel-plugin-codegen/index.js b/packages/babel-plugin-codegen/index.js deleted file mode 100644 index b1a11612ecae..000000000000 --- a/packages/babel-plugin-codegen/index.js +++ /dev/null @@ -1,171 +0,0 @@ -/** - * 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 - */ - -'use strict'; - -let flowParser, typeScriptParser, RNCodegen; - -const {basename} = require('path'); - -try { - flowParser = require('react-native-codegen/src/parsers/flow'); - typeScriptParser = require('react-native-codegen/src/parsers/typescript'); - RNCodegen = require('react-native-codegen/src/generators/RNCodegen'); -} catch (e) { - // Fallback to lib when source doesn't exit (e.g. when installed as a dev dependency) - flowParser = require('react-native-codegen/lib/parsers/flow'); - typeScriptParser = require('react-native-codegen/lib/parsers/typescript'); - RNCodegen = require('react-native-codegen/lib/generators/RNCodegen'); -} - -function parseFile(filename, code) { - if (filename.endsWith('js')) { - return flowParser.parseString(code); - } - - if (filename.endsWith('ts')) { - return typeScriptParser.parseString(code); - } - - throw new Error( - `Unable to parse file '${filename}'. Unsupported filename extension.`, - ); -} - -function generateViewConfig(filename, code) { - const schema = parseFile(filename, code); - - const libraryName = basename(filename).replace( - /NativeComponent\.(js|ts)$/, - '', - ); - return RNCodegen.generateViewConfig({ - schema, - libraryName, - }); -} - -function isCodegenDeclaration(declaration) { - if (!declaration) { - return false; - } - - if ( - declaration.left && - declaration.left.left && - declaration.left.left.name === 'codegenNativeComponent' - ) { - return true; - } else if ( - declaration.callee && - declaration.callee.name && - declaration.callee.name === 'codegenNativeComponent' - ) { - return true; - } else if ( - declaration.type === 'TypeCastExpression' && - declaration.expression && - declaration.expression.callee && - declaration.expression.callee.name && - declaration.expression.callee.name === 'codegenNativeComponent' - ) { - return true; - } - - return false; -} - -module.exports = function ({parse, types: t}) { - return { - pre(state) { - this.code = state.code; - this.filename = state.opts.filename; - this.defaultExport = null; - this.commandsExport = null; - this.codeInserted = false; - }, - visitor: { - ExportNamedDeclaration(path) { - if (this.codeInserted) { - return; - } - - if ( - path.node.declaration && - path.node.declaration.declarations && - path.node.declaration.declarations[0] - ) { - const firstDeclaration = path.node.declaration.declarations[0]; - - if (firstDeclaration.type === 'VariableDeclarator') { - if ( - firstDeclaration.init && - firstDeclaration.init.type === 'CallExpression' && - firstDeclaration.init.callee.type === 'Identifier' && - firstDeclaration.init.callee.name === 'codegenNativeCommands' - ) { - if ( - firstDeclaration.id.type === 'Identifier' && - firstDeclaration.id.name !== 'Commands' - ) { - throw path.buildCodeFrameError( - "Native commands must be exported with the name 'Commands'", - ); - } - this.commandsExport = path; - return; - } else { - if (firstDeclaration.id.name === 'Commands') { - throw path.buildCodeFrameError( - "'Commands' is a reserved export and may only be used to export the result of codegenNativeCommands.", - ); - } - } - } - } else if (path.node.specifiers && path.node.specifiers.length > 0) { - path.node.specifiers.forEach(specifier => { - if ( - specifier.type === 'ExportSpecifier' && - specifier.local.type === 'Identifier' && - specifier.local.name === 'Commands' - ) { - throw path.buildCodeFrameError( - "'Commands' is a reserved export and may only be used to export the result of codegenNativeCommands.", - ); - } - }); - } - }, - ExportDefaultDeclaration(path, state) { - if (isCodegenDeclaration(path.node.declaration)) { - this.defaultExport = path; - } - }, - - Program: { - exit(path) { - if (this.defaultExport) { - const viewConfig = generateViewConfig(this.filename, this.code); - this.defaultExport.replaceWithMultiple( - parse(viewConfig, { - babelrc: false, - browserslistConfigFile: false, - configFile: false, - }).program.body, - ); - if (this.commandsExport != null) { - this.commandsExport.remove(); - } - this.codeInserted = true; - } - }, - }, - }, - }; -}; diff --git a/packages/babel-plugin-codegen/package.json b/packages/babel-plugin-codegen/package.json deleted file mode 100644 index 9e40a4c26cf2..000000000000 --- a/packages/babel-plugin-codegen/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "version": "0.71.2", - "name": "@react-native/babel-plugin-codegen", - "description": "Babel plugin to generate native module and view manager code for React Native.", - "repository": { - "type": "git", - "url": "git@github.com:facebook/react-native.git", - "directory": "packages/babel-plugin-codegen" - }, - "files": [ - "index.js" - ], - "dependencies": { - "react-native-codegen": "*" - }, - "devDependencies": { - "@babel/core": "^7.14.0" - }, - "license": "MIT" -} diff --git a/packages/eslint-config-react-native-community/BUCK b/packages/eslint-config-react-native-community/BUCK deleted file mode 100644 index 8fd38289431b..000000000000 --- a/packages/eslint-config-react-native-community/BUCK +++ /dev/null @@ -1,23 +0,0 @@ -load("@fbsource//tools/build_defs/third_party:yarn_defs.bzl", "yarn_workspace") - -yarn_workspace( - name = "yarn-workspace", - srcs = glob( - ["**/*.js"], - exclude = [ - "**/__fixtures__/**", - "**/__flowtests__/**", - "**/__mocks__/**", - "**/__server_snapshot_tests__/**", - "**/__tests__/**", - "**/node_modules/**", - "**/node_modules/.bin/**", - "**/.*", - "**/.*/**", - "**/.*/.*", - "**/*.xcodeproj/**", - "**/*.xcworkspace/**", - ], - ), - visibility = ["PUBLIC"], -) diff --git a/packages/eslint-config-react-native-community/README.md b/packages/eslint-config-react-native-community/README.md deleted file mode 100644 index 367ab70030de..000000000000 --- a/packages/eslint-config-react-native-community/README.md +++ /dev/null @@ -1,25 +0,0 @@ -# eslint-config-react-native-community - -[![Version][version-badge]][package] - -## Installation - -``` -yarn add --dev eslint prettier @react-native-community/eslint-config -``` - -*Note: We're using `yarn` to install deps. Feel free to change commands to use `npm` 3+ and `npx` if you like* - -## Usage - -Add to your eslint config (`.eslintrc`, or `eslintConfig` field in `package.json`): - -```json -{ - "extends": "@react-native-community" -} -``` - -[version-badge]: https://img.shields.io/npm/v/@react-native-community/eslint-config.svg?style=flat-square -[package]: https://www.npmjs.com/package/@react-native-community/eslint-config - diff --git a/packages/eslint-config-react-native-community/index.js b/packages/eslint-config-react-native-community/index.js deleted file mode 100644 index bb5e2e32c94b..000000000000 --- a/packages/eslint-config-react-native-community/index.js +++ /dev/null @@ -1,333 +0,0 @@ -/** - * 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 - */ - -module.exports = { - env: { - es6: true, - }, - - parserOptions: { - sourceType: 'module', - }, - - extends: ['plugin:prettier/recommended'], - - plugins: [ - 'eslint-comments', - 'react', - 'react-hooks', - 'react-native', - '@react-native-community', - 'jest', - ], - - settings: { - react: { - version: 'detect', - }, - }, - - overrides: [ - { - files: ['*.js'], - parser: '@babel/eslint-parser', - plugins: ['ft-flow'], - rules: { - // Flow Plugin - // The following rules are made available via `eslint-plugin-ft-flow` - - 'ft-flow/define-flow-type': 1, - 'ft-flow/use-flow-type': 1, - }, - }, - { - files: ['*.ts', '*.tsx'], - parser: '@typescript-eslint/parser', - plugins: ['@typescript-eslint/eslint-plugin'], - rules: { - '@typescript-eslint/no-unused-vars': [ - 'error', - { - argsIgnorePattern: '^_', - destructuredArrayIgnorePattern: '^_', - }, - ], - 'no-unused-vars': 'off', - 'no-shadow': 'off', - '@typescript-eslint/no-shadow': 1, - 'no-undef': 'off', - 'func-call-spacing': 'off', - '@typescript-eslint/func-call-spacing': 1, - }, - }, - { - files: [ - '*.{spec,test}.{js,ts,tsx}', - '**/__{mocks,tests}__/**/*.{js,ts,tsx}', - ], - env: { - jest: true, - 'jest/globals': true, - }, - rules: { - 'react-native/no-inline-styles': 0, - quotes: [1, 'single', {avoidEscape: true, allowTemplateLiterals: true}], - }, - }, - ], - - // Map from global var to bool specifying if it can be redefined - globals: { - __DEV__: true, - __dirname: false, - __fbBatchedBridgeConfig: false, - AbortController: false, - Blob: true, - alert: false, - cancelAnimationFrame: false, - cancelIdleCallback: false, - clearImmediate: true, - clearInterval: false, - clearTimeout: false, - console: false, - document: false, - ErrorUtils: false, - escape: false, - Event: false, - EventTarget: false, - exports: false, - fetch: false, - File: true, - FileReader: false, - FormData: false, - global: false, - Headers: false, - Intl: false, - Map: true, - module: false, - navigator: false, - process: false, - Promise: true, - requestAnimationFrame: true, - requestIdleCallback: true, - require: false, - Set: true, - setImmediate: true, - setInterval: false, - setTimeout: false, - queueMicrotask: true, - URL: false, - URLSearchParams: false, - WebSocket: true, - window: false, - XMLHttpRequest: false, - }, - - rules: { - // General - 'comma-dangle': [1, 'always-multiline'], // allow or disallow trailing commas - 'no-cond-assign': 1, // disallow assignment in conditional expressions - 'no-console': 0, // disallow use of console (off by default in the node environment) - 'no-const-assign': 2, // disallow assignment to const-declared variables - 'no-constant-condition': 0, // disallow use of constant expressions in conditions - 'no-control-regex': 1, // disallow control characters in regular expressions - 'no-debugger': 1, // disallow use of debugger - 'no-dupe-class-members': 2, // Disallow duplicate name in class members - 'no-dupe-keys': 2, // disallow duplicate keys when creating object literals - 'no-empty': 0, // disallow empty statements - 'no-ex-assign': 1, // disallow assigning to the exception in a catch block - 'no-extra-boolean-cast': 1, // disallow double-negation boolean casts in a boolean context - 'no-extra-parens': 0, // disallow unnecessary parentheses (off by default) - 'no-extra-semi': 1, // disallow unnecessary semicolons - 'no-func-assign': 1, // disallow overwriting functions written as function declarations - 'no-inner-declarations': 0, // disallow function or variable declarations in nested blocks - 'no-invalid-regexp': 1, // disallow invalid regular expression strings in the RegExp constructor - 'no-negated-in-lhs': 1, // disallow negation of the left operand of an in expression - 'no-obj-calls': 1, // disallow the use of object properties of the global object (Math and JSON) as functions - 'no-regex-spaces': 1, // disallow multiple spaces in a regular expression literal - 'no-reserved-keys': 0, // disallow reserved words being used as object literal keys (off by default) - 'no-sparse-arrays': 1, // disallow sparse arrays - 'no-unreachable': 2, // disallow unreachable statements after a return, throw, continue, or break statement - 'use-isnan': 1, // disallow comparisons with the value NaN - 'valid-jsdoc': 0, // Ensure JSDoc comments are valid (off by default) - 'valid-typeof': 1, // Ensure that the results of typeof are compared against a valid string - - // Best Practices - // These are rules designed to prevent you from making mistakes. They either prescribe a better way of doing something or help you avoid footguns. - - 'block-scoped-var': 0, // treat var statements as if they were block scoped (off by default) - complexity: 0, // specify the maximum cyclomatic complexity allowed in a program (off by default) - 'consistent-return': 0, // require return statements to either always or never specify values - curly: 1, // specify curly brace conventions for all control statements - 'default-case': 0, // require default case in switch statements (off by default) - 'dot-notation': 1, // encourages use of dot notation whenever possible - eqeqeq: [1, 'allow-null'], // require the use of === and !== - 'guard-for-in': 0, // make sure for-in loops have an if statement (off by default) - 'no-alert': 1, // disallow the use of alert, confirm, and prompt - 'no-caller': 1, // disallow use of arguments.caller or arguments.callee - 'no-div-regex': 1, // disallow division operators explicitly at beginning of regular expression (off by default) - 'no-else-return': 0, // disallow else after a return in an if (off by default) - 'no-eq-null': 0, // disallow comparisons to null without a type-checking operator (off by default) - 'no-eval': 2, // disallow use of eval() - 'no-extend-native': 1, // disallow adding to native types - 'no-extra-bind': 1, // disallow unnecessary function binding - 'no-fallthrough': 1, // disallow fallthrough of case statements - 'no-floating-decimal': 1, // disallow the use of leading or trailing decimal points in numeric literals (off by default) - 'no-implied-eval': 1, // disallow use of eval()-like methods - 'no-labels': 1, // disallow use of labeled statements - 'no-iterator': 1, // disallow usage of __iterator__ property - 'no-lone-blocks': 1, // disallow unnecessary nested blocks - 'no-loop-func': 0, // disallow creation of functions within loops - 'no-multi-str': 0, // disallow use of multiline strings - 'no-native-reassign': 0, // disallow reassignments of native objects - 'no-new': 1, // disallow use of new operator when not part of the assignment or comparison - 'no-new-func': 2, // disallow use of new operator for Function object - 'no-new-wrappers': 1, // disallows creating new instances of String,Number, and Boolean - 'no-octal': 1, // disallow use of octal literals - 'no-octal-escape': 1, // disallow use of octal escape sequences in string literals, such as var foo = "Copyright \251"; - 'no-proto': 1, // disallow usage of __proto__ property - 'no-redeclare': 0, // disallow declaring the same variable more then once - 'no-return-assign': 1, // disallow use of assignment in return statement - 'no-script-url': 1, // disallow use of javascript: urls. - 'no-self-compare': 1, // disallow comparisons where both sides are exactly the same (off by default) - 'no-sequences': 1, // disallow use of comma operator - 'no-unused-expressions': 0, // disallow usage of expressions in statement position - 'no-useless-escape': 1, // disallow escapes that don't have any effect in literals - 'no-void': 1, // disallow use of void operator (off by default) - 'no-warning-comments': 0, // disallow usage of configurable warning terms in comments": 1, // e.g. TODO or FIXME (off by default) - 'no-with': 1, // disallow use of the with statement - radix: 1, // require use of the second argument for parseInt() (off by default) - 'semi-spacing': 1, // require a space after a semi-colon - 'vars-on-top': 0, // requires to declare all vars on top of their containing scope (off by default) - 'wrap-iife': 0, // require immediate function invocation to be wrapped in parentheses (off by default) - yoda: 1, // require or disallow Yoda conditions - - // Variables - // These rules have to do with variable declarations. - - 'no-catch-shadow': 1, // disallow the catch clause parameter name being the same as a variable in the outer scope (off by default in the node environment) - 'no-delete-var': 1, // disallow deletion of variables - 'no-label-var': 1, // disallow labels that share a name with a variable - 'no-shadow': 1, // disallow declaration of variables already declared in the outer scope - 'no-shadow-restricted-names': 1, // disallow shadowing of names such as arguments - 'no-undef': 2, // disallow use of undeclared variables unless mentioned in a /*global */ block - 'no-undefined': 0, // disallow use of undefined variable (off by default) - 'no-undef-init': 1, // disallow use of undefined when initializing variables - 'no-unused-vars': [ - 1, - {vars: 'all', args: 'none', ignoreRestSiblings: true}, - ], // disallow declaration of variables that are not used in the code - 'no-use-before-define': 0, // disallow use of variables before they are defined - - // Node.js - // These rules are specific to JavaScript running on Node.js. - - 'handle-callback-err': 1, // enforces error handling in callbacks (off by default) (on by default in the node environment) - 'no-mixed-requires': 1, // disallow mixing regular variable and require declarations (off by default) (on by default in the node environment) - 'no-new-require': 1, // disallow use of new operator with the require function (off by default) (on by default in the node environment) - 'no-path-concat': 1, // disallow string concatenation with __dirname and __filename (off by default) (on by default in the node environment) - 'no-process-exit': 0, // disallow process.exit() (on by default in the node environment) - 'no-restricted-modules': 1, // restrict usage of specified node modules (off by default) - 'no-sync': 0, // disallow use of synchronous methods (off by default) - - // ESLint Comments Plugin - // The following rules are made available via `eslint-plugin-eslint-comments` - 'eslint-comments/no-aggregating-enable': 1, // disallows eslint-enable comments for multiple eslint-disable comments - 'eslint-comments/no-unlimited-disable': 1, // disallows eslint-disable comments without rule names - 'eslint-comments/no-unused-disable': 1, // disallow disables that don't cover any errors - 'eslint-comments/no-unused-enable': 1, // // disallow enables that don't enable anything or enable rules that weren't disabled - - // Stylistic Issues - // These rules are purely matters of style and are quite subjective. - - 'key-spacing': 0, - 'keyword-spacing': 1, // enforce spacing before and after keywords - 'jsx-quotes': [1, 'prefer-double'], // enforces the usage of double quotes for all JSX attribute values which doesn’t contain a double quote - 'comma-spacing': 0, - 'no-multi-spaces': 0, - 'brace-style': 0, // enforce one true brace style (off by default) - camelcase: 0, // require camel case names - 'consistent-this': 1, // enforces consistent naming when capturing the current execution context (off by default) - 'eol-last': 1, // enforce newline at the end of file, with no multiple empty lines - 'func-names': 0, // require function expressions to have a name (off by default) - 'func-style': 0, // enforces use of function declarations or expressions (off by default) - 'new-cap': 0, // require a capital letter for constructors - 'new-parens': 1, // disallow the omission of parentheses when invoking a constructor with no arguments - 'no-nested-ternary': 0, // disallow nested ternary expressions (off by default) - 'no-array-constructor': 1, // disallow use of the Array constructor - 'no-empty-character-class': 1, // disallow the use of empty character classes in regular expressions - 'no-lonely-if': 0, // disallow if as the only statement in an else block (off by default) - 'no-new-object': 1, // disallow use of the Object constructor - 'func-call-spacing': 1, // disallow space between function identifier and application - 'no-ternary': 0, // disallow the use of ternary operators (off by default) - 'no-trailing-spaces': 1, // disallow trailing whitespace at the end of lines - 'no-underscore-dangle': 0, // disallow dangling underscores in identifiers - 'no-mixed-spaces-and-tabs': 1, // disallow mixed spaces and tabs for indentation - quotes: [1, 'single', 'avoid-escape'], // specify whether double or single quotes should be used - 'quote-props': 0, // require quotes around object literal property names (off by default) - semi: 1, // require or disallow use of semicolons instead of ASI - 'sort-vars': 0, // sort variables within the same declaration block (off by default) - 'space-in-brackets': 0, // require or disallow spaces inside brackets (off by default) - 'space-in-parens': 0, // require or disallow spaces inside parentheses (off by default) - 'space-infix-ops': 1, // require spaces around operators - 'space-unary-ops': [1, {words: true, nonwords: false}], // require or disallow spaces before/after unary operators (words on by default, nonwords off by default) - 'max-nested-callbacks': 0, // specify the maximum depth callbacks can be nested (off by default) - 'one-var': 0, // allow just one var statement per function (off by default) - 'wrap-regex': 0, // require regex literals to be wrapped in parentheses (off by default) - - // Legacy - // The following rules are included for compatibility with JSHint and JSLint. While the names of the rules may not match up with the JSHint/JSLint counterpart, the functionality is the same. - - 'max-depth': 0, // specify the maximum depth that blocks can be nested (off by default) - 'max-len': 0, // specify the maximum length of a line in your program (off by default) - 'max-params': 0, // limits the number of parameters that can be used in the function declaration. (off by default) - 'max-statements': 0, // specify the maximum number of statement allowed in a function (off by default) - 'no-bitwise': 1, // disallow use of bitwise operators (off by default) - 'no-plusplus': 0, // disallow use of unary operators, ++ and -- (off by default) - - // React Plugin - // The following rules are made available via `eslint-plugin-react`. - - 'react/display-name': 0, - 'react/jsx-boolean-value': 0, - 'react/jsx-no-comment-textnodes': 2, - 'react/jsx-no-duplicate-props': 2, - 'react/jsx-no-undef': 2, - 'react/jsx-sort-props': 0, - 'react/jsx-uses-react': 1, - 'react/jsx-uses-vars': 1, - 'react/no-did-mount-set-state': 1, - 'react/no-did-update-set-state': 1, - 'react/no-multi-comp': 0, - 'react/no-string-refs': 1, - 'react/no-unknown-property': 0, - 'react/no-unstable-nested-components': 1, - 'react/prop-types': 0, - 'react/react-in-jsx-scope': 1, - 'react/self-closing-comp': 1, - 'react/wrap-multilines': 0, - - // React-Hooks Plugin - // The following rules are made available via `eslint-plugin-react-hooks` - 'react-hooks/rules-of-hooks': 2, - 'react-hooks/exhaustive-deps': 2, - - // React-Native Plugin - // The following rules are made available via `eslint-plugin-react-native` - - 'react-native/no-inline-styles': 1, - - // Jest Plugin - // The following rules are made available via `eslint-plugin-jest`. - 'jest/no-disabled-tests': 1, - 'jest/no-focused-tests': 1, - 'jest/no-identical-title': 1, - 'jest/valid-expect': 1, - }, -}; diff --git a/packages/eslint-config-react-native-community/package.json b/packages/eslint-config-react-native-community/package.json deleted file mode 100644 index 53f6ca2e9b7c..000000000000 --- a/packages/eslint-config-react-native-community/package.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "@react-native-community/eslint-config", - "version": "3.2.0", - "description": "ESLint config for React Native", - "main": "index.js", - "license": "MIT", - "repository": { - "type": "git", - "url": "git@github.com:facebook/react-native.git", - "directory": "packages/eslint-config-react-native-community" - }, - "homepage": "https://github.com/facebook/react-native/tree/HEAD/packages/eslint-config-react-native-community#readme", - "dependencies": { - "@babel/core": "^7.14.0", - "@babel/eslint-parser": "^7.18.2", - "@react-native-community/eslint-plugin": "^1.3.0", - "@typescript-eslint/eslint-plugin": "^5.30.5", - "@typescript-eslint/parser": "^5.30.5", - "eslint-config-prettier": "^8.5.0", - "eslint-plugin-eslint-comments": "^3.2.0", - "eslint-plugin-ft-flow": "^2.0.1", - "eslint-plugin-jest": "^26.5.3", - "eslint-plugin-prettier": "^4.2.1", - "eslint-plugin-react": "^7.30.1", - "eslint-plugin-react-hooks": "^4.6.0", - "eslint-plugin-react-native": "^4.0.0" - }, - "peerDependencies": { - "eslint": ">=8", - "prettier": ">=2" - }, - "devDependencies": { - "eslint": "^8.19.0", - "prettier": "^2.4.1" - } -} diff --git a/packages/eslint-plugin-react-native-community/BUCK b/packages/eslint-plugin-react-native-community/BUCK deleted file mode 100644 index 8fd38289431b..000000000000 --- a/packages/eslint-plugin-react-native-community/BUCK +++ /dev/null @@ -1,23 +0,0 @@ -load("@fbsource//tools/build_defs/third_party:yarn_defs.bzl", "yarn_workspace") - -yarn_workspace( - name = "yarn-workspace", - srcs = glob( - ["**/*.js"], - exclude = [ - "**/__fixtures__/**", - "**/__flowtests__/**", - "**/__mocks__/**", - "**/__server_snapshot_tests__/**", - "**/__tests__/**", - "**/node_modules/**", - "**/node_modules/.bin/**", - "**/.*", - "**/.*/**", - "**/.*/.*", - "**/*.xcodeproj/**", - "**/*.xcworkspace/**", - ], - ), - visibility = ["PUBLIC"], -) diff --git a/packages/eslint-plugin-react-native-community/README.md b/packages/eslint-plugin-react-native-community/README.md deleted file mode 100644 index 4512dff9efc2..000000000000 --- a/packages/eslint-plugin-react-native-community/README.md +++ /dev/null @@ -1,27 +0,0 @@ -# eslint-plugin-react-native-community - -This plugin is intended to be used in [`@react-native-community/eslint-config`](https://github.com/facebook/react-native/tree/HEAD/packages/eslint-config-react-native-community). You probably want to install that package instead. - -## Installation - -``` -yarn add --dev eslint @react-native-community/eslint-plugin -``` - -*Note: We're using `yarn` to install deps. Feel free to change commands to use `npm` 3+ and `npx` if you like* - -## Usage - -Add to your eslint config (`.eslintrc`, or `eslintConfig` field in `package.json`): - -```json -{ - "plugins": ["@react-native-community"] -} -``` - -## Rules - -### `platform-colors` - -Enforces that calls to `PlatformColor` and `DynamicColorIOS` are statically analyzable to enable performance optimizations. diff --git a/packages/eslint-plugin-react-native-community/__tests__/eslint-tester.js b/packages/eslint-plugin-react-native-community/__tests__/eslint-tester.js deleted file mode 100644 index 7ad39befe0be..000000000000 --- a/packages/eslint-plugin-react-native-community/__tests__/eslint-tester.js +++ /dev/null @@ -1,23 +0,0 @@ -/** - * 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 - */ - -'use strict'; - -const ESLintTester = require('eslint').RuleTester; - -ESLintTester.setDefaultConfig({ - parser: require.resolve('@babel/eslint-parser'), - parserOptions: { - requireConfigFile: false, - ecmaVersion: 6, - sourceType: 'module', - }, -}); - -module.exports = ESLintTester; diff --git a/packages/eslint-plugin-react-native-community/__tests__/platform-colors-test.js b/packages/eslint-plugin-react-native-community/__tests__/platform-colors-test.js deleted file mode 100644 index 76e799f3cb5b..000000000000 --- a/packages/eslint-plugin-react-native-community/__tests__/platform-colors-test.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * 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 - * @oncall react_native - */ - -'use strict'; - -const ESLintTester = require('./eslint-tester.js'); - -const rule = require('../platform-colors.js'); - -const eslintTester = new ESLintTester(); - -eslintTester.run('../platform-colors', rule, { - valid: [ - "const color = PlatformColor('labelColor');", - "const color = PlatformColor('controlAccentColor', 'controlColor');", - "const color = DynamicColorIOS({light: 'black', dark: 'white'});", - "const color = DynamicColorIOS({light: PlatformColor('black'), dark: PlatformColor('white')});", - "const color = DynamicColorIOS({light: PlatformColor('black'), dark: PlatformColor('white'), highContrastLight: PlatformColor('black'), highContrastDark: PlatformColor('white')});", - ], - invalid: [ - { - code: 'const color = PlatformColor();', - errors: [{message: rule.meta.messages.platformColorArgsLength}], - }, - { - code: "const labelColor = 'labelColor'; const color = PlatformColor(labelColor);", - errors: [{message: rule.meta.messages.platformColorArgTypes}], - }, - { - code: "const tuple = {light: 'black', dark: 'white'}; const color = DynamicColorIOS(tuple);", - errors: [{message: rule.meta.messages.dynamicColorIOSArg}], - }, - { - code: "const black = 'black'; const color = DynamicColorIOS({light: black, dark: 'white'});", - errors: [{message: rule.meta.messages.dynamicColorIOSValue}], - }, - { - code: "const white = 'white'; const color = DynamicColorIOS({light: 'black', dark: white});", - errors: [{message: rule.meta.messages.dynamicColorIOSValue}], - }, - ], -}); diff --git a/packages/eslint-plugin-react-native-community/index.js b/packages/eslint-plugin-react-native-community/index.js deleted file mode 100644 index 5c3756184557..000000000000 --- a/packages/eslint-plugin-react-native-community/index.js +++ /dev/null @@ -1,12 +0,0 @@ -/** - * 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 - */ - -exports.rules = { - 'platform-colors': require('./platform-colors'), -}; diff --git a/packages/eslint-plugin-react-native-community/package.json b/packages/eslint-plugin-react-native-community/package.json deleted file mode 100644 index f50afbdad52d..000000000000 --- a/packages/eslint-plugin-react-native-community/package.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "@react-native-community/eslint-plugin", - "version": "1.3.0", - "description": "ESLint rules for @react-native-community/eslint-config", - "main": "index.js", - "repository": { - "type": "git", - "url": "git@github.com:facebook/react-native.git", - "directory": "packages/eslint-plugin-react-native-community" - }, - "license": "MIT" -} diff --git a/packages/eslint-plugin-react-native-community/platform-colors.js b/packages/eslint-plugin-react-native-community/platform-colors.js deleted file mode 100644 index cfbabd1a923c..000000000000 --- a/packages/eslint-plugin-react-native-community/platform-colors.js +++ /dev/null @@ -1,79 +0,0 @@ -/** - * 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 - */ - -module.exports = { - meta: { - type: 'problem', - docs: { - description: - 'Ensure that PlatformColor() and DynamicColorIOS() are passed literals of the expected shape.', - }, - messages: { - platformColorArgsLength: - 'PlatformColor() must have at least one argument that is a literal.', - platformColorArgTypes: - 'PlatformColor() every argument must be a literal.', - dynamicColorIOSArg: - 'DynamicColorIOS() must take a single argument of type Object', - dynamicColorIOSValue: - 'DynamicColorIOS() value must be either a literal or a PlatformColor() call.', - }, - schema: [], - }, - - create: function (context) { - return { - CallExpression: function (node) { - if (node.callee.name === 'PlatformColor') { - const args = node.arguments; - if (args.length === 0) { - context.report({ - node, - messageId: 'platformColorArgsLength', - }); - return; - } - if (!args.every(arg => arg.type === 'Literal')) { - context.report({ - node, - messageId: 'platformColorArgTypes', - }); - return; - } - } else if (node.callee.name === 'DynamicColorIOS') { - const args = node.arguments; - if (!(args.length === 1 && args[0].type === 'ObjectExpression')) { - context.report({ - node, - messageId: 'dynamicColorIOSArg', - }); - return; - } - const properties = args[0].properties; - properties.forEach(property => { - if ( - !( - property.type === 'Property' && - (property.value.type === 'Literal' || - (property.value.type === 'CallExpression' && - property.value.callee.name === 'PlatformColor')) - ) - ) { - context.report({ - node, - messageId: 'dynamicColorIOSValue', - }); - return; - } - }); - } - }, - }; - }, -}; diff --git a/packages/eslint-plugin-specs/BUCK b/packages/eslint-plugin-specs/BUCK deleted file mode 100644 index 8fd38289431b..000000000000 --- a/packages/eslint-plugin-specs/BUCK +++ /dev/null @@ -1,23 +0,0 @@ -load("@fbsource//tools/build_defs/third_party:yarn_defs.bzl", "yarn_workspace") - -yarn_workspace( - name = "yarn-workspace", - srcs = glob( - ["**/*.js"], - exclude = [ - "**/__fixtures__/**", - "**/__flowtests__/**", - "**/__mocks__/**", - "**/__server_snapshot_tests__/**", - "**/__tests__/**", - "**/node_modules/**", - "**/node_modules/.bin/**", - "**/.*", - "**/.*/**", - "**/.*/.*", - "**/*.xcodeproj/**", - "**/*.xcworkspace/**", - ], - ), - visibility = ["PUBLIC"], -) diff --git a/packages/eslint-plugin-specs/__tests__/eslint-tester.js b/packages/eslint-plugin-specs/__tests__/eslint-tester.js deleted file mode 100644 index c6937e8cd049..000000000000 --- a/packages/eslint-plugin-specs/__tests__/eslint-tester.js +++ /dev/null @@ -1,26 +0,0 @@ -/** - * 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 - */ - -'use strict'; - -const ESLintTester = require('eslint').RuleTester; - -ESLintTester.setDefaultConfig({ - parser: require.resolve('@babel/eslint-parser'), - parserOptions: { - requireConfigFile: false, - ecmaVersion: 6, - sourceType: 'module', - babelOptions: { - presets: [require.resolve('@babel/preset-flow')], - }, - }, -}); - -module.exports = ESLintTester; diff --git a/packages/eslint-plugin-specs/__tests__/react-native-modules-test.js b/packages/eslint-plugin-specs/__tests__/react-native-modules-test.js deleted file mode 100644 index ae3b5c62ac66..000000000000 --- a/packages/eslint-plugin-specs/__tests__/react-native-modules-test.js +++ /dev/null @@ -1,58 +0,0 @@ -/** - * 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 - * @oncall react_native - */ - -'use strict'; - -const ESLintTester = require('./eslint-tester.js'); - -const rule = require('../react-native-modules'); - -const NATIVE_MODULES_DIR = __dirname; - -const eslintTester = new ESLintTester(); - -const VALID_SPECS = [ - { - code: ` -import {TurboModuleRegistry, type TurboModule} from 'react-native'; -import type {UnsafeObject} from 'react-native/Libraries/Types/CodegenTypes'; - -export interface Spec extends TurboModule { - func1(a: string): UnsafeObject, -} -export default TurboModuleRegistry.get('XYZ'); - `, - filename: `${NATIVE_MODULES_DIR}/NativeXYZ.js`, - }, -]; - -const INVALID_SPECS = [ - // Untyped NativeModule require - { - code: ` -import {TurboModuleRegistry, type TurboModule} from 'react-native'; -export interface Spec extends TurboModule { - func1(a: string): {||}, -} -export default TurboModuleRegistry.get('XYZ'); - `, - filename: `${NATIVE_MODULES_DIR}/XYZ.js`, - errors: [ - { - message: rule.errors.misnamedHasteModule('XYZ'), - }, - ], - }, -]; - -eslintTester.run('../react-native-modules', rule, { - valid: VALID_SPECS, - invalid: INVALID_SPECS, -}); diff --git a/packages/eslint-plugin-specs/index.js b/packages/eslint-plugin-specs/index.js deleted file mode 100644 index eb77fdd6a9a2..000000000000 --- a/packages/eslint-plugin-specs/index.js +++ /dev/null @@ -1,19 +0,0 @@ -/** - * 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 - * @oncall react_native - */ - -'use strict'; - -const reactNativeModules = require('./react-native-modules'); - -module.exports = { - rules: { - 'react-native-modules': reactNativeModules, - }, -}; diff --git a/packages/eslint-plugin-specs/package.json b/packages/eslint-plugin-specs/package.json deleted file mode 100644 index 2956a52d482a..000000000000 --- a/packages/eslint-plugin-specs/package.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "@react-native/eslint-plugin-specs", - "version": "0.71.1", - "description": "ESLint rules to validate NativeModule and Component Specs", - "main": "index.js", - "repository": { - "type": "git", - "url": "git@github.com:facebook/react-native.git", - "directory": "packages/eslint-plugin-specs" - }, - "scripts": { - "prepack": "node prepack.js", - "postpack": "node postpack.js" - }, - "dependencies": { - "@babel/core": "^7.14.0", - "@babel/eslint-parser": "^7.18.2", - "@babel/plugin-transform-flow-strip-types": "^7.0.0", - "@babel/preset-flow": "^7.17.12", - "flow-parser": "^0.185.0", - "make-dir": "^2.1.0", - "pirates": "^4.0.1", - "react-native-codegen": "*", - "source-map-support": "0.5.0" - }, - "license": "MIT" -} diff --git a/packages/eslint-plugin-specs/postpack.js b/packages/eslint-plugin-specs/postpack.js deleted file mode 100644 index 99807d8b086d..000000000000 --- a/packages/eslint-plugin-specs/postpack.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 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 - */ - -const fs = require('fs'); - -/** - * script to prepare package for publish. - * - * Due to differences to how we consume internal packages, update a flag - */ - -fs.readFile('./react-native-modules.js', 'utf8', function (readError, source) { - if (readError != null) { - return console.error( - 'Failed to read react-native-modules.js for publish', - readError, - ); - } - - const result = source.replace( - 'const PACKAGE_USAGE = true;', - 'const PACKAGE_USAGE = false;', - ); - - fs.writeFile( - './react-native-modules.js', - result, - 'utf8', - function (writeError) { - if (writeError != null) { - return console.error( - 'Failed to update react-native-modules.js for publish', - writeError, - ); - } - }, - ); -}); diff --git a/packages/eslint-plugin-specs/prepack.js b/packages/eslint-plugin-specs/prepack.js deleted file mode 100644 index 3a3c44514976..000000000000 --- a/packages/eslint-plugin-specs/prepack.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 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 - */ - -const fs = require('fs'); - -/** - * script to prepare package for publish. - * - * Due to differences to how we consume internal packages, update a flag - */ - -fs.readFile('./react-native-modules.js', 'utf8', function (readError, source) { - if (readError != null) { - return console.error( - 'Failed to read react-native-modules.js for publish', - readError, - ); - } - - const result = source.replace( - 'const PACKAGE_USAGE = false;', - 'const PACKAGE_USAGE = true;', - ); - - fs.writeFile( - './react-native-modules.js', - result, - 'utf8', - function (writeError) { - if (writeError != null) { - return console.error( - 'Failed to update react-native-modules.js for publish', - writeError, - ); - } - }, - ); -}); diff --git a/packages/eslint-plugin-specs/react-native-modules.js b/packages/eslint-plugin-specs/react-native-modules.js deleted file mode 100644 index f303ab539eba..000000000000 --- a/packages/eslint-plugin-specs/react-native-modules.js +++ /dev/null @@ -1,171 +0,0 @@ -/** - * 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 - * @oncall react_native - */ - -'use strict'; - -const path = require('path'); -const withBabelRegister = require('./with-babel-register'); - -// We use the prepack hook before publishing package to set this value to true -const PACKAGE_USAGE = false; -const ERRORS = { - misnamedHasteModule(hasteModuleName) { - return `Module ${hasteModuleName}: All files using TurboModuleRegistry must start with Native.`; - }, -}; - -let RNModuleParser; -let RNParserUtils; - -function requireModuleParser() { - if (RNModuleParser == null || RNParserUtils == null) { - // If using this externally, we leverage react-native-codegen as published form - if (!PACKAGE_USAGE) { - const config = { - only: [/react-native-codegen\/src\//], - plugins: [require('@babel/plugin-transform-flow-strip-types').default], - }; - - withBabelRegister(config, () => { - RNModuleParser = require('react-native-codegen/src/parsers/flow/modules'); - RNParserUtils = require('react-native-codegen/src/parsers/utils'); - }); - } else { - const config = { - only: [/react-native-codegen\/lib\//], - plugins: [require('@babel/plugin-transform-flow-strip-types').default], - }; - - withBabelRegister(config, () => { - RNModuleParser = require('react-native-codegen/lib/parsers/flow/modules'); - RNParserUtils = require('react-native-codegen/lib/parsers/utils'); - }); - } - } - - return { - buildModuleSchema: RNModuleParser.buildModuleSchema, - createParserErrorCapturer: RNParserUtils.createParserErrorCapturer, - }; -} - -const VALID_SPEC_NAMES = /^Native\S+$/; - -function isModuleRequire(node) { - if (node.type !== 'CallExpression') { - return false; - } - - const callExpression = node; - - if (callExpression.callee.type !== 'MemberExpression') { - return false; - } - - const memberExpression = callExpression.callee; - if ( - !( - memberExpression.object.type === 'Identifier' && - memberExpression.object.name === 'TurboModuleRegistry' - ) - ) { - return false; - } - - if ( - !( - memberExpression.property.type === 'Identifier' && - (memberExpression.property.name === 'get' || - memberExpression.property.name === 'getEnforcing') - ) - ) { - return false; - } - return true; -} - -function isGeneratedFile(context) { - return ( - context - .getSourceCode() - .getText() - .indexOf('@' + 'generated SignedSource<<') !== -1 - ); -} - -/** - * A lint rule to guide best practices in writing type safe React NativeModules. - */ -function rule(context) { - const filename = context.getFilename(); - const hasteModuleName = path.basename(filename).replace(/\.js$/, ''); - - if (isGeneratedFile(context)) { - return {}; - } - - let isModule = false; - - return { - 'Program:exit': function (node) { - if (!isModule) { - return; - } - - // Report invalid file names - if (!VALID_SPEC_NAMES.test(hasteModuleName)) { - context.report({ - node, - message: ERRORS.misnamedHasteModule(hasteModuleName), - }); - } - - const {buildModuleSchema, createParserErrorCapturer} = - requireModuleParser(); - const flowParser = require('flow-parser'); - - const [parsingErrors, tryParse] = createParserErrorCapturer(); - - const sourceCode = context.getSourceCode().getText(); - const ast = flowParser.parse(sourceCode, {enums: true}); - - tryParse(() => { - buildModuleSchema(hasteModuleName, ast, tryParse); - }); - - parsingErrors.forEach(error => { - error.nodes.forEach(flowNode => { - context.report({ - loc: flowNode.loc, - message: error.message, - }); - }); - }); - }, - CallExpression(node) { - if (!isModuleRequire(node)) { - return; - } - - isModule = true; - }, - InterfaceExtends(node) { - if (node.id.name !== 'TurboModule') { - return; - } - - isModule = true; - }, - }; -} - -rule.errors = ERRORS; - -module.exports = rule; diff --git a/packages/eslint-plugin-specs/with-babel-register/disk-cache.js b/packages/eslint-plugin-specs/with-babel-register/disk-cache.js deleted file mode 100644 index 9a797909cec8..000000000000 --- a/packages/eslint-plugin-specs/with-babel-register/disk-cache.js +++ /dev/null @@ -1,131 +0,0 @@ -/** - * 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 - * @oncall react_native - */ - -const path = require('path'); -const fs = require('fs'); -const os = require('os'); -const {sync: makeDirSync} = require('make-dir'); - -const packageJson = JSON.parse( - fs.readFileSync(require.resolve('../package.json'), 'utf8'), -); - -/** - * This file is a fork of - * https://github.com/babel/babel/blob/2782a549e99d2ef1816332d23d7dfd5190f58a0f/packages/babel-register/src/cache.js#L1 - */ - -const FILENAME = path.join( - os.tmpdir(), - `.eslint-plugin-specs.${packageJson.version}.disk-cache.json`, -); - -let data = {}; - -let cacheDisabled = process.env.NODE_ENV === 'test'; - -function isCacheDisabled() { - return cacheDisabled; -} - -/** - * Write stringified cache to disk. - */ -function save() { - if (isCacheDisabled()) { - return; - } - - let serialised = '{}'; - - try { - serialised = JSON.stringify(data, null, ' '); - } catch (err) { - if (err.message === 'Invalid string length') { - err.message = "Cache too large so it's been cleared."; - console.error(err.stack); - } else { - throw err; - } - } - - try { - makeDirSync(path.dirname(FILENAME)); - fs.writeFileSync(FILENAME, serialised); - } catch (e) { - switch (e.code) { - // workaround https://github.com/nodejs/node/issues/31481 - // todo: remove the ENOENT error check when we drop node.js 13 support - case 'ENOENT': - case 'EACCES': - case 'EPERM': - console.warn( - `Could not write cache to file: ${FILENAME} due to a permission issue. Cache is disabled.`, - ); - cacheDisabled = true; - break; - case 'EROFS': - console.warn( - `Could not write cache to file: ${FILENAME} because it resides in a readonly filesystem. Cache is disabled.`, - ); - cacheDisabled = true; - break; - default: - throw e; - } - } -} - -/** - * Load cache from disk and parse. - */ - -function load() { - if (isCacheDisabled()) { - data = {}; - return; - } - - process.on('exit', save); - process.nextTick(save); - - let cacheContent; - - try { - cacheContent = fs.readFileSync(FILENAME); - } catch (e) { - switch (e.code) { - // check EACCES only as fs.readFileSync will never throw EPERM on Windows - // https://github.com/libuv/libuv/blob/076df64dbbda4320f93375913a728efc40e12d37/src/win/fs.c#L735 - case 'EACCES': - console.warn( - `Babel could not read cache file: ${FILENAME} due to a permission issue. Cache is disabled.`, - ); - cacheDisabled = true; - /* fall through */ - default: - return; - } - } - - try { - data = JSON.parse(cacheContent); - } catch {} -} - -/** - * Retrieve data from cache. - */ - -function get() { - return data; -} - -module.exports = {load, get}; diff --git a/packages/eslint-plugin-specs/with-babel-register/index.js b/packages/eslint-plugin-specs/with-babel-register/index.js deleted file mode 100644 index e4fe1450367b..000000000000 --- a/packages/eslint-plugin-specs/with-babel-register/index.js +++ /dev/null @@ -1,110 +0,0 @@ -/** - * 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 - * @oncall react_native - */ - -const babel = require('@babel/core'); -const {OptionManager, DEFAULT_EXTENSIONS} = require('@babel/core'); -const sourceMapSupport = require('source-map-support'); -const {addHook} = require('pirates'); -const path = require('path'); -const fs = require('fs'); -const diskCache = require('./disk-cache'); - -function compile(sourceMapManager, cache, options, code, filename) { - const opts = new OptionManager().init({ - sourceRoot: path.dirname(filename) + path.sep, - ...options, - filename, - }); - - // Bail out ASAP if the file has been ignored. - if (opts === null) { - return code; - } - - let output = cache[filename]; - - if (!output || output.mtime !== mtime(filename)) { - output = babel.transformSync(code, { - ...opts, - sourceMaps: opts.sourceMaps === undefined ? 'both' : opts.sourceMaps, - ast: false, - }); - - cache[filename] = output; - output.mtime = mtime(filename); - } - - if (!sourceMapManager.isInstalled) { - sourceMapManager.install(); - } - - if (output.map) { - sourceMapManager.maps[filename] = output.map; - } - - return output.code; -} - -function mtime(filename) { - return +fs.statSync(filename).mtime; -} - -function withBabelRegister(options, fn) { - let revertHook; - /** - * TODO: Do source maps break when we use a require hook - * to before we initialize the ESLint plugin? - */ - const sourceMapManager = { - isInstalled: false, - maps: {}, - install() { - if (sourceMapManager.isInstalled) { - return; - } - sourceMapManager.isInstalled = true; - sourceMapSupport.install({ - handleUncaughtExceptions: true, - environment: 'node', - retrieveSourceMap(filename) { - const map = sourceMapManager.maps && sourceMapManager.maps[filename]; - if (map) { - return { - url: null, - map: map, - }; - } else { - return null; - } - }, - }); - }, - }; - - diskCache.load(); - const cache = diskCache.get(); - - try { - revertHook = addHook( - (code, filename) => { - return compile(sourceMapManager, cache, options, code, filename); - }, - { - exts: DEFAULT_EXTENSIONS, - ignoreNodeModules: false, - }, - ); - return fn(); - } finally { - revertHook(); - } -} - -module.exports = withBabelRegister; diff --git a/packages/hermes-inspector-msggen/.babelrc b/packages/hermes-inspector-msggen/.babelrc deleted file mode 100644 index 8ad6d5109ddf..000000000000 --- a/packages/hermes-inspector-msggen/.babelrc +++ /dev/null @@ -1,8 +0,0 @@ -{ - "presets": [ "@babel/preset-flow", ["@babel/preset-env", { - "targets": { - "node": "current" - } - }] - ], -} diff --git a/packages/hermes-inspector-msggen/.gitignore b/packages/hermes-inspector-msggen/.gitignore deleted file mode 100644 index 050ba480f8f8..000000000000 --- a/packages/hermes-inspector-msggen/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -.DS_Store -bin/ -node_modules/ diff --git a/packages/hermes-inspector-msggen/__tests__/CommandTest.js b/packages/hermes-inspector-msggen/__tests__/CommandTest.js deleted file mode 100644 index b409e81cced7..000000000000 --- a/packages/hermes-inspector-msggen/__tests__/CommandTest.js +++ /dev/null @@ -1,62 +0,0 @@ -/** - * 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. - */ - -import {Command} from '../src/Command.js'; - -test('parses simple command', () => { - let obj = { - 'name': 'setBreakpointsActive', - 'parameters': [ - { 'name': 'active', 'type': 'boolean', 'description': 'New value for breakpoints active state.' }, - ], - 'description': 'Activates / deactivates all breakpoints on the page.', - }; - let command = Command.create('Debugger', obj, false); - - expect(command.domain).toBe('Debugger'); - expect(command.name).toBe('setBreakpointsActive'); - expect(command.description).toBe('Activates / deactivates all breakpoints on the page.'); - expect(command.parameters.map(p => p.name)).toEqual(['active']); - expect(command.returns.length).toBe(0); - - expect(command.getDebuggerName()).toBe('Debugger.setBreakpointsActive'); - expect(command.getCppNamespace()).toBe('debugger'); - expect(command.getRequestCppType()).toBe('SetBreakpointsActiveRequest'); - expect(command.getResponseCppType()).toBeUndefined(); - expect(command.getForwardDecls()).toEqual(['struct SetBreakpointsActiveRequest;']); -}); - -test('parses command with return', () => { - let obj = { - 'name': 'setBreakpoint', - 'parameters': [ - { 'name': 'location', '$ref': 'Location', 'description': 'Location to set breakpoint in.' }, - { 'name': 'condition', 'type': 'string', 'optional': true, 'description': 'Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true.' }, - ], - 'returns': [ - { 'name': 'breakpointId', '$ref': 'BreakpointId', 'description': 'Id of the created breakpoint for further reference.' }, - { 'name': 'actualLocation', '$ref': 'Location', 'description': 'Location this breakpoint resolved into.' }, - ], - 'description': 'Sets JavaScript breakpoint at a given location.', - }; - let command = Command.create('Debugger', obj, false); - - expect(command.domain).toBe('Debugger'); - expect(command.name).toBe('setBreakpoint'); - expect(command.description).toBe('Sets JavaScript breakpoint at a given location.'); - expect(command.parameters.map(p => p.name)).toEqual(['location', 'condition']); - expect(command.returns.map(p => p.name)).toEqual(['breakpointId', 'actualLocation']); - - expect(command.getDebuggerName()).toBe('Debugger.setBreakpoint'); - expect(command.getCppNamespace()).toBe('debugger'); - expect(command.getRequestCppType()).toBe('SetBreakpointRequest'); - expect(command.getResponseCppType()).toBe('SetBreakpointResponse'); - expect(command.getForwardDecls()).toEqual([ - 'struct SetBreakpointRequest;', - 'struct SetBreakpointResponse;', - ]); -}); diff --git a/packages/hermes-inspector-msggen/__tests__/EventTest.js b/packages/hermes-inspector-msggen/__tests__/EventTest.js deleted file mode 100644 index 8ebb1ecb6e91..000000000000 --- a/packages/hermes-inspector-msggen/__tests__/EventTest.js +++ /dev/null @@ -1,47 +0,0 @@ -/** - * 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. - */ - -import {Event} from '../src/Event.js'; - -test('parses simple event', () => { - let obj = { - 'name': 'resumed', - 'description': 'Fired when the virtual machine resumed execution.', - }; - let event = Event.create('Debugger', obj, false); - - expect(event.domain).toBe('Debugger'); - expect(event.name).toBe('resumed'); - expect(event.description).toBe('Fired when the virtual machine resumed execution.'); - - expect(event.getDebuggerName()).toBe('Debugger.resumed'); - expect(event.getCppNamespace()).toBe('debugger'); - expect(event.getCppType()).toBe('ResumedNotification'); - expect(event.getForwardDecls()).toEqual(['struct ResumedNotification;']); -}); - -test('parses event with params', () => { - let obj = { - 'name': 'breakpointResolved', - 'parameters': [ - { 'name': 'breakpointId', '$ref': 'BreakpointId', 'description': 'Breakpoint unique identifier.' }, - { 'name': 'location', '$ref': 'Location', 'description': 'Actual breakpoint location.' }, - ], - 'description': 'Fired when breakpoint is resolved to an actual script and location.', - }; - let event = Event.create('Debugger', obj, false); - - expect(event.domain).toBe('Debugger'); - expect(event.name).toBe('breakpointResolved'); - expect(event.description).toBe('Fired when breakpoint is resolved to an actual script and location.'); - expect(event.parameters.map(p => p.name)).toEqual(['breakpointId', 'location']); - - expect(event.getDebuggerName()).toBe('Debugger.breakpointResolved'); - expect(event.getCppNamespace()).toBe('debugger'); - expect(event.getCppType()).toBe('BreakpointResolvedNotification'); - expect(event.getForwardDecls()).toEqual(['struct BreakpointResolvedNotification;']); -}); diff --git a/packages/hermes-inspector-msggen/__tests__/GraphTest.js b/packages/hermes-inspector-msggen/__tests__/GraphTest.js deleted file mode 100644 index b890c050ea89..000000000000 --- a/packages/hermes-inspector-msggen/__tests__/GraphTest.js +++ /dev/null @@ -1,78 +0,0 @@ -/** - * 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. - */ - -import {Graph} from '../src/Graph.js'; - -// graph looks like this before test: https://pxl.cl/9k8t -let graph = null; - -beforeEach(() => { - graph = new Graph(); - graph.addEdge('A1', 'B1'); - graph.addEdge('A2', 'B1'); - graph.addEdge('A2', 'B2'); - graph.addEdge('A3', 'B2'); - graph.addEdge('A3', 'C3'); - graph.addEdge('B1', 'C1'); - graph.addEdge('B1', 'C2'); - graph.addEdge('B1', 'C3'); - graph.addEdge('B2', 'C2'); -}); - -// checks id1 occurs after id2 in arr -function expectOccursAfter(arr, id1, id2) { - let idx1 = arr.indexOf(id1); - let idx2 = arr.indexOf(id2); - - expect(idx1).not.toBe(-1); - expect(idx2).not.toBe(-1); - expect(idx1).toBeGreaterThan(idx2); -} - -test('detects cycle', () => { - graph.addEdge('C2', 'A1'); - expect(() => graph.traverse(['A2'])).toThrow(/^Not a DAG/); -}); - -test('checks for presence of root', () => { - expect(() => graph.traverse(['A1', 'NX'])).toThrow(/^No node/); -}); - -test('traverses partial graph', () => { - let ids = graph.traverse(['B1', 'A3']); - - // Check that expected nodes are there - let sortedIds = ids.slice().sort(); - expect(sortedIds).toEqual(['A3', 'B1', 'B2', 'C1', 'C2', 'C3']); - - // Check that the result is topologically sorted - expectOccursAfter(ids, 'A3', 'B2'); - expectOccursAfter(ids, 'A3', 'C3'); - expectOccursAfter(ids, 'B1', 'C1'); - expectOccursAfter(ids, 'B1', 'C2'); - expectOccursAfter(ids, 'B1', 'C3'); - expectOccursAfter(ids, 'B2', 'C2'); -}); - -test('traverses complete graph', () => { - let ids = graph.traverse(['A1', 'A2', 'A3']); - - // Check that expected nodes are there - let sortedIds = ids.slice().sort(); - expect(sortedIds).toEqual(['A1', 'A2', 'A3', 'B1', 'B2', 'C1', 'C2', 'C3']); - - // Check that the result is topologically sorted - expectOccursAfter(ids, 'A1', 'B1'); - expectOccursAfter(ids, 'A2', 'B1'); - expectOccursAfter(ids, 'A2', 'B2'); - expectOccursAfter(ids, 'A3', 'B2'); - expectOccursAfter(ids, 'A3', 'C3'); - expectOccursAfter(ids, 'B1', 'C1'); - expectOccursAfter(ids, 'B1', 'C2'); - expectOccursAfter(ids, 'B1', 'C3'); - expectOccursAfter(ids, 'B2', 'C2'); -}); diff --git a/packages/hermes-inspector-msggen/__tests__/HeaderWriterTest.js b/packages/hermes-inspector-msggen/__tests__/HeaderWriterTest.js deleted file mode 100644 index 1c9da38f7b99..000000000000 --- a/packages/hermes-inspector-msggen/__tests__/HeaderWriterTest.js +++ /dev/null @@ -1,128 +0,0 @@ -/** - * 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. - */ - -import {expectCodeIsEqual, FakeWritable} from '../src/TestHelpers'; -import { - emitNotificationDecl, - emitRequestDecl, - emitResponseDecl, - emitTypeDecl, -} from '../src/HeaderWriter'; -import { Event } from '../src/Event'; -import { Command } from '../src/Command'; -import { Type } from '../src/Type'; - -let stream = null; - -beforeEach(() => { - stream = new FakeWritable(); -}); - -test('emits type decl', () => { - let obj = { - 'id': 'Location', - 'type': 'object', - 'properties': [ - { 'name': 'scriptId', '$ref': 'Runtime.ScriptId', 'description': 'Script identifier as reported in the Debugger.scriptParsed.' }, - { 'name': 'lineNumber', 'type': 'integer', 'description': 'Line number in the script (0-based).' }, - { 'name': 'columnNumber', 'type': 'integer', 'optional': true, 'description': 'Column number in the script (0-based).' }, - ], - 'description': 'Location in the source code.', - }; - let type = Type.create('Debugger', obj); - - emitTypeDecl(stream, type); - - expectCodeIsEqual(stream.get(), ` - struct debugger::Location : public Serializable { - Location() = default; - explicit Location(const folly::dynamic &obj); - folly::dynamic toDynamic() const override; - - runtime::ScriptId scriptId{}; - int lineNumber{}; - folly::Optional columnNumber; - }; - `); -}); - -test('emits request decl', () => { - let obj = { - 'name': 'getScriptSource', - 'parameters': [ - { 'name': 'scriptId', '$ref': 'Runtime.ScriptId', 'description': 'Id of the script to get source for.' }, - ], - 'returns': [ - { 'name': 'scriptSource', 'type': 'string', 'description': 'Script source.' }, - ], - 'description': 'Returns source for the script with given id.', - }; - let command = Command.create('Debugger', obj); - - emitRequestDecl(stream, command); - - expectCodeIsEqual(stream.get(), ` - struct debugger::GetScriptSourceRequest : public Request { - GetScriptSourceRequest(); - explicit GetScriptSourceRequest(const folly::dynamic &obj); - - folly::dynamic toDynamic() const override; - void accept(RequestHandler &handler) const override; - - runtime::ScriptId scriptId{}; - }; - `); -}); - -test('emits response decl', () => { - let obj = { - 'name': 'getScriptSource', - 'parameters': [ - { 'name': 'scriptId', '$ref': 'Runtime.ScriptId', 'description': 'Id of the script to get source for.' }, - ], - 'returns': [ - { 'name': 'scriptSource', 'type': 'string', 'description': 'Script source.' }, - ], - 'description': 'Returns source for the script with given id.', - }; - let command = Command.create('Debugger', obj); - - emitResponseDecl(stream, command); - - expectCodeIsEqual(stream.get(), ` - struct debugger::GetScriptSourceResponse : public Response { - GetScriptSourceResponse() = default; - explicit GetScriptSourceResponse(const folly::dynamic &obj); - folly::dynamic toDynamic() const override; - - std::string scriptSource; - }; - `); -}); - -test('emits notification decl', () => { - let obj = { - 'name': 'messageAdded', - 'parameters': [ - { 'name': 'message', '$ref': 'ConsoleMessage', 'description': 'Console message that has been added.' }, - ], - 'description': 'Issued when new console message is added.', - }; - let event = Event.create('Console', obj); - - emitNotificationDecl(stream, event); - - expectCodeIsEqual(stream.get(), ` - struct console::MessageAddedNotification : public Notification { - MessageAddedNotification(); - explicit MessageAddedNotification(const folly::dynamic &obj); - folly::dynamic toDynamic() const override; - - console::ConsoleMessage message{}; - }; - `); -}); diff --git a/packages/hermes-inspector-msggen/__tests__/ImplementationWriterTest.js b/packages/hermes-inspector-msggen/__tests__/ImplementationWriterTest.js deleted file mode 100644 index 6ad01e08231a..000000000000 --- a/packages/hermes-inspector-msggen/__tests__/ImplementationWriterTest.js +++ /dev/null @@ -1,171 +0,0 @@ -/** - * 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. - */ - -import {expectCodeIsEqual, FakeWritable} from '../src/TestHelpers'; -import { - emitNotificationDef, - emitRequestDef, - emitResponseDef, - emitTypeDef, -} from '../src/ImplementationWriter'; -import { Event } from '../src/Event'; -import { Command } from '../src/Command'; -import { Type } from '../src/Type'; - -let stream = null; - -beforeEach(() => { - stream = new FakeWritable(); -}); - -test('emits type def', () => { - let obj = { - 'id': 'Location', - 'type': 'object', - 'properties': [ - { 'name': 'scriptId', '$ref': 'Runtime.ScriptId', 'description': 'Script identifier as reported in the Debugger.scriptParsed.' }, - { 'name': 'lineNumber', 'type': 'integer', 'description': 'Line number in the script (0-based).' }, - { 'name': 'columnNumber', 'type': 'integer', 'optional': true, 'description': 'Column number in the script (0-based).' }, - ], - 'description': 'Location in the source code.', - }; - let type = Type.create('Debugger', obj); - - emitTypeDef(stream, type); - - expectCodeIsEqual(stream.get(), ` - debugger::Location::Location(const dynamic &obj) { - assign(scriptId, obj, "scriptId"); - assign(lineNumber, obj, "lineNumber"); - assign(columnNumber, obj, "columnNumber"); - } - - dynamic debugger::Location::toDynamic() const { - dynamic obj = dynamic::object; - put(obj, "scriptId", scriptId); - put(obj, "lineNumber", lineNumber); - put(obj, "columnNumber", columnNumber); - return obj; - } - `); -}); - -test('emits request def', () => { - let obj = { - 'name': 'getScriptSource', - 'parameters': [ - { 'name': 'scriptId', '$ref': 'Runtime.ScriptId', 'description': 'Id of the script to get source for.' }, - ], - 'returns': [ - { 'name': 'scriptSource', 'type': 'string', 'description': 'Script source.' }, - ], - 'description': 'Returns source for the script with given id.', - }; - let command = Command.create('Debugger', obj); - - emitRequestDef(stream, command); - - expectCodeIsEqual(stream.get(), ` - debugger::GetScriptSourceRequest::GetScriptSourceRequest() - : Request("Debugger.getScriptSource") {} - - debugger::GetScriptSourceRequest::GetScriptSourceRequest(const dynamic &obj) - : Request("Debugger.getScriptSource") { - assign(id, obj, "id"); - assign(method, obj, "method"); - - dynamic params = obj.at("params"); - assign(scriptId, params, "scriptId"); - } - - dynamic debugger::GetScriptSourceRequest::toDynamic() const { - dynamic params = dynamic::object; - put(params, "scriptId", scriptId); - - dynamic obj = dynamic::object; - put(obj, "id", id); - put(obj, "method", method); - put(obj, "params", std::move(params)); - return obj; - } - - void debugger::GetScriptSourceRequest::accept(RequestHandler &handler) const { - handler.handle(*this); - } - `); -}); - -test('emits response def', () => { - let obj = { - 'name': 'getScriptSource', - 'parameters': [ - { 'name': 'scriptId', '$ref': 'Runtime.ScriptId', 'description': 'Id of the script to get source for.' }, - ], - 'returns': [ - { 'name': 'scriptSource', 'type': 'string', 'description': 'Script source.' }, - ], - 'description': 'Returns source for the script with given id.', - }; - let command = Command.create('Debugger', obj); - - emitResponseDef(stream, command); - - expectCodeIsEqual(stream.get(), ` - debugger::GetScriptSourceResponse::GetScriptSourceResponse(const dynamic &obj) { - assign(id, obj, "id"); - - dynamic res = obj.at("result"); - assign(scriptSource, res, "scriptSource"); - } - - dynamic debugger::GetScriptSourceResponse::toDynamic() const { - dynamic res = dynamic::object; - put(res, "scriptSource", scriptSource); - - dynamic obj = dynamic::object; - put(obj, "id", id); - put(obj, "result", std::move(res)); - return obj; - } - `); -}); - -test('emits notification def', () => { - let obj = { - 'name': 'messageAdded', - 'parameters': [ - { 'name': 'message', '$ref': 'ConsoleMessage', 'description': 'Console message that has been added.' }, - ], - 'description': 'Issued when new console message is added.', - }; - let event = Event.create('Console', obj); - - emitNotificationDef(stream, event); - - expectCodeIsEqual(stream.get(), ` - console::MessageAddedNotification::MessageAddedNotification() - : Notification("Console.messageAdded") {} - - console::MessageAddedNotification::MessageAddedNotification(const dynamic &obj) - : Notification("Console.messageAdded") { - assign(method, obj, "method"); - - dynamic params = obj.at("params"); - assign(message, params, "message"); - } - - dynamic console::MessageAddedNotification::toDynamic() const { - dynamic params = dynamic::object; - put(params, "message", message); - - dynamic obj = dynamic::object; - put(obj, "method", method); - put(obj, "params", std::move(params)); - return obj; - } - `); -}); diff --git a/packages/hermes-inspector-msggen/__tests__/PropertyTest.js b/packages/hermes-inspector-msggen/__tests__/PropertyTest.js deleted file mode 100644 index f1f1c8a5be7e..000000000000 --- a/packages/hermes-inspector-msggen/__tests__/PropertyTest.js +++ /dev/null @@ -1,131 +0,0 @@ -/** - * 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. - */ - -import {Property} from '../src/Property.js'; - -test('parses required primitive prop', () => { - let obj = { - 'name': 'lineNumber', - 'type': 'integer', - 'description': 'Line number in the script (0-based).', - }; - let prop = Property.create('Debugger', obj); - - expect(prop.domain).toBe('Debugger'); - expect(prop.name).toBe('lineNumber'); - expect(prop.type).toBe('integer'); - expect(prop.optional).toBeUndefined(); - expect(prop.description).toBe('Line number in the script (0-based).'); - - expect(prop.getFullCppType()).toBe('int'); - expect(prop.getCppIdentifier()).toBe('lineNumber'); - expect(prop.getInitializer()).toBe('{}'); -}); - -test('parses optional primitive prop', () => { - let obj = { - 'name': 'samplingInterval', - 'type': 'number', - 'optional': true, - 'description': 'Average sample interval in bytes.', - }; - let prop = Property.create('HeapProfiler', obj); - - expect(prop.domain).toBe('HeapProfiler'); - expect(prop.name).toBe('samplingInterval'); - expect(prop.type).toBe('number'); - expect(prop.optional).toBe(true); - expect(prop.description).toBe('Average sample interval in bytes.'); - - expect(prop.getFullCppType()).toBe('folly::Optional'); - expect(prop.getCppIdentifier()).toBe('samplingInterval'); - expect(prop.getInitializer()).toBe(''); -}); - -test('parses optional ref prop', () => { - let obj = { - 'name': 'exceptionDetails', - 'optional': true, - '$ref': 'Runtime.ExceptionDetails', - 'description': 'Exception details if any.', - }; - let prop = Property.create('Debugger', obj); - - expect(prop.domain).toBe('Debugger'); - expect(prop.name).toBe('exceptionDetails'); - expect(prop.optional).toBe(true); - expect(prop.$ref).toBe('Runtime.ExceptionDetails'); - expect(prop.description).toBe('Exception details if any.'); - - expect(prop.getFullCppType()).toBe('folly::Optional'); - expect(prop.getCppIdentifier()).toBe('exceptionDetails'); - expect(prop.getInitializer()).toBe(''); -}); - -test('parses recursive ref prop', () => { - let obj = { - 'name': 'parent', - '$ref': 'StackTrace', - 'optional': true, - 'recursive': true, - 'description': 'Asynchronous JavaScript stack trace...', - }; - let prop = Property.create('Runtime', obj); - - expect(prop.domain).toBe('Runtime'); - expect(prop.name).toBe('parent'); - expect(prop.optional).toBe(true); - expect(prop.recursive).toBe(true); - expect(prop.$ref).toBe('StackTrace'); - expect(prop.description).toBe('Asynchronous JavaScript stack trace...'); - - expect(prop.getFullCppType()).toBe('std::unique_ptr'); - expect(prop.getCppIdentifier()).toBe('parent'); - expect(prop.getInitializer()).toBe(''); -}); - -test('parses optional array items prop', () => { - let obj = { - 'name': 'hitBreakpoints', - 'type': 'array', - 'optional': true, - 'items': { 'type': 'string' }, - 'description': 'Hit breakpoints IDs', - }; - let prop = Property.create('Debugger', obj); - - expect(prop.domain).toBe('Debugger'); - expect(prop.name).toBe('hitBreakpoints'); - expect(prop.type).toBe('array'); - expect(prop.optional).toBe(true); - expect(prop.items).toEqual({ 'type': 'string' }); - expect(prop.description).toBe('Hit breakpoints IDs'); - - expect(prop.getFullCppType()).toBe('folly::Optional>'); - expect(prop.getCppIdentifier()).toBe('hitBreakpoints'); - expect(prop.getInitializer()).toBe(''); -}); - -test('parses array ref prop', () => { - let obj = { - 'name': 'domains', - 'type': 'array', - 'items': { '$ref': 'Domain' }, - 'description': 'List of supported domains.', - }; - let prop = Property.create('Schema', obj); - - expect(prop.domain).toBe('Schema'); - expect(prop.name).toBe('domains'); - expect(prop.type).toBe('array'); - expect(prop.items).toEqual({ $ref: 'Domain' }); - expect(prop.description).toBe('List of supported domains.'); - - expect(prop.getFullCppType()).toBe('std::vector'); - expect(prop.getCppIdentifier()).toBe('domains'); - expect(prop.getInitializer()).toBe(''); -}); diff --git a/packages/hermes-inspector-msggen/__tests__/TypeTest.js b/packages/hermes-inspector-msggen/__tests__/TypeTest.js deleted file mode 100644 index 14fc860e1e2d..000000000000 --- a/packages/hermes-inspector-msggen/__tests__/TypeTest.js +++ /dev/null @@ -1,50 +0,0 @@ -/** - * 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. - */ - -import {Type} from '../src/Type.js'; - -test('parses primitive type', () => { - let obj = { - 'id': 'Timestamp', - 'type': 'number', - 'description': 'Number of milliseconds since epoch.', - }; - let type = Type.create('Runtime', obj, false); - - expect(type.domain).toBe('Runtime'); - expect(type.id).toBe('Timestamp'); - expect(type.type).toBe('number'); - expect(type.description).toBe('Number of milliseconds since epoch.'); - - expect(type.getCppNamespace()).toBe('runtime'); - expect(type.getCppType()).toBe('Timestamp'); - expect(type.getForwardDecls()).toEqual(['using Timestamp = double;']); -}); - -test('parses object type', () => { - let obj = { - 'id': 'Location', - 'type': 'object', - 'properties': [ - { 'name': 'scriptId', '$ref': 'Runtime.ScriptId', 'description': 'Script identifier as reported in the Debugger.scriptParsed.' }, - { 'name': 'lineNumber', 'type': 'integer', 'description': 'Line number in the script (0-based).' }, - { 'name': 'columnNumber', 'type': 'integer', 'optional': true, 'description': 'Column number in the script (0-based).' }, - ], - 'description': 'Location in the source code.', - }; - let type = Type.create('Debugger', obj, false); - - expect(type.domain).toBe('Debugger'); - expect(type.id).toBe('Location'); - expect(type.type).toBe('object'); - expect(type.properties.map(p => p.name)).toEqual(['scriptId', 'lineNumber', 'columnNumber']); - expect(type.description).toBe('Location in the source code.'); - - expect(type.getCppNamespace()).toBe('debugger'); - expect(type.getCppType()).toBe('Location'); - expect(type.getForwardDecls()).toEqual(['struct Location;']); -}); diff --git a/packages/hermes-inspector-msggen/package.json b/packages/hermes-inspector-msggen/package.json deleted file mode 100644 index add61d46ca79..000000000000 --- a/packages/hermes-inspector-msggen/package.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@react-native/hermes-inspector-msggen", - "private": true, - "version": "0.71.1", - "license": "MIT", - "bin": { - "msggen": "./bin/index.js" - }, - "scripts": { - "flow": "flow", - "build": "babel src --out-dir bin --source-maps", - "watch": "babel src --out-dir bin --source-maps --watch", - "test": "jest" - }, - "dependencies": { - "devtools-protocol": "0.0.959523", - "yargs": "^17.5.1" - }, - "devDependencies": { - "@babel/cli": "^7.14.0", - "@babel/core": "^7.14.0", - "@babel/preset-env": "^7.14.0", - "@babel/preset-flow": "^7.14.0", - "jest": "^29.2.1" - }, - "jest": { - "transform": { - ".*": "/node_modules/babel-jest" - } - } -} diff --git a/packages/hermes-inspector-msggen/src/Command.js b/packages/hermes-inspector-msggen/src/Command.js deleted file mode 100644 index b7b60d4aeac1..000000000000 --- a/packages/hermes-inspector-msggen/src/Command.js +++ /dev/null @@ -1,79 +0,0 @@ -/** - * 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 - */ - -import {Property} from './Property'; -import {toCppNamespace, toCppType} from './Converters'; - -export class Command { - domain: string; - name: string; - description: ?string; - experimental: ?boolean; - parameters: Array; - returns: Array; - - static create( - domain: string, - obj: any, - ignoreExperimental: boolean, - ): ?Command { - return ignoreExperimental && obj.experimental - ? null - : new Command(domain, obj, ignoreExperimental); - } - - constructor(domain: string, obj: any, ignoreExperimental: boolean) { - this.domain = domain; - this.name = obj.name; - this.description = obj.description; - this.experimental = obj.experimental; - this.parameters = Property.createArray( - domain, - obj.parameters || [], - ignoreExperimental, - ); - this.returns = Property.createArray( - domain, - obj.returns || [], - ignoreExperimental, - ); - } - - getDebuggerName(): string { - return `${this.domain}.${this.name}`; - } - - getCppNamespace(): string { - return toCppNamespace(this.domain); - } - - getRequestCppType(): string { - return toCppType(this.name + 'Request'); - } - - getResponseCppType(): ?string { - if (this.returns && this.returns.length > 0) { - return toCppType(this.name + 'Response'); - } - } - - getForwardDecls(): Array { - const decls = [`struct ${this.getRequestCppType()};`]; - const respCppType = this.getResponseCppType(); - if (respCppType) { - decls.push(`struct ${respCppType};`); - } - return decls; - } - - getForwardDeclSortKey(): string { - return this.getRequestCppType(); - } -} diff --git a/packages/hermes-inspector-msggen/src/Converters.js b/packages/hermes-inspector-msggen/src/Converters.js deleted file mode 100644 index 8061ef1a41aa..000000000000 --- a/packages/hermes-inspector-msggen/src/Converters.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -export function toCppNamespace(domain: string): string { - return domain.substr(0, 1).toLowerCase() + domain.substr(1); -} - -export function toCppType(type: string): string { - return type.substr(0, 1).toUpperCase() + type.substr(1); -} - -export type JsTypeString = - | 'any' - | 'boolean' - | 'integer' - | 'number' - | 'object' - | 'string'; - -const jsTypeMappings = { - any: 'folly::dynamic', - array: 'folly::dynamic', - boolean: 'bool', - integer: 'int', - number: 'double', - object: 'folly::dynamic', - string: 'std::string', -}; - -export function jsTypeToCppType(jsTypeStr: JsTypeString): string { - return jsTypeMappings[jsTypeStr]; -} diff --git a/packages/hermes-inspector-msggen/src/Event.js b/packages/hermes-inspector-msggen/src/Event.js deleted file mode 100644 index 9edfe7f8f2be..000000000000 --- a/packages/hermes-inspector-msggen/src/Event.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * 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 - */ - -import {Property} from './Property'; -import {toCppNamespace, toCppType} from './Converters'; - -export class Event { - domain: string; - name: string; - description: ?string; - experimental: ?boolean; - parameters: Array; - - static create(domain: string, obj: any, ignoreExperimental: boolean): ?Event { - return ignoreExperimental && obj.experimental - ? null - : new Event(domain, obj, ignoreExperimental); - } - - constructor(domain: string, obj: any, ignoreExperimental: boolean) { - this.domain = domain; - this.name = obj.name; - this.description = obj.description; - this.parameters = Property.createArray( - domain, - obj.parameters || [], - ignoreExperimental, - ); - } - - getDebuggerName(): string { - return `${this.domain}.${this.name}`; - } - - getCppNamespace(): string { - return toCppNamespace(this.domain); - } - - getCppType(): string { - return toCppType(this.name + 'Notification'); - } - - getForwardDecls(): Array { - return [`struct ${this.getCppType()};`]; - } - - getForwardDeclSortKey(): string { - return this.getCppType(); - } -} diff --git a/packages/hermes-inspector-msggen/src/GeneratedHeader.js b/packages/hermes-inspector-msggen/src/GeneratedHeader.js deleted file mode 100644 index 9533b2425e28..000000000000 --- a/packages/hermes-inspector-msggen/src/GeneratedHeader.js +++ /dev/null @@ -1,16 +0,0 @@ -/** - * 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 - */ - -'use strict'; - -// placeholder token that will be replaced by signedsource script -export const GeneratedHeader: string = - '// Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved.\n' + - '// @generated <>'; diff --git a/packages/hermes-inspector-msggen/src/Graph.js b/packages/hermes-inspector-msggen/src/Graph.js deleted file mode 100644 index 359e4673924c..000000000000 --- a/packages/hermes-inspector-msggen/src/Graph.js +++ /dev/null @@ -1,90 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -import invariant from 'assert'; - -type NodeId = string; - -class Node { - id: NodeId; - children: Set; - state: 'none' | 'visiting' | 'visited'; - - constructor(id: NodeId) { - this.id = id; - this.children = new Set(); - this.state = 'none'; - } -} - -export class Graph { - nodes: Map; - - constructor() { - this.nodes = new Map(); - } - - addNode(nodeId: NodeId): Node { - let node = this.nodes.get(nodeId); - if (!node) { - node = new Node(nodeId); - this.nodes.set(nodeId, node); - } - return node; - } - - addEdge(srcId: NodeId, dstId: NodeId) { - const src = this.addNode(srcId); - const dst = this.addNode(dstId); - src.children.add(dst); - } - - // traverse returns all nodes in the graph reachable from the given rootIds. - // the returned nodes are topologically sorted, with the deepest nodes - // returned first. - traverse(rootIds: Array): Array { - // clear marks - for (const node of this.nodes.values()) { - node.state = 'none'; - } - - // make a fake root node that points to all the provided rootIds - const root = new Node('root'); - for (const id of rootIds) { - const node = this.nodes.get(id); - invariant(node != null, `No node ${id} in graph`); - root.children.add(node); - } - - const output: Array = []; - postorder(root, output); - - // remove fake root node - output.splice(-1); - - return output; - } -} - -function postorder(node: Node, output: Array) { - if (node.state === 'visited') { - return; - } - - invariant(node.state !== 'visiting', `Not a DAG: cycle involving ${node.id}`); - - node.state = 'visiting'; - for (const child of node.children) { - postorder(child, output); - } - - node.state = 'visited'; - output.push(node.id); -} diff --git a/packages/hermes-inspector-msggen/src/HeaderWriter.js b/packages/hermes-inspector-msggen/src/HeaderWriter.js deleted file mode 100644 index 5784f9f2f261..000000000000 --- a/packages/hermes-inspector-msggen/src/HeaderWriter.js +++ /dev/null @@ -1,323 +0,0 @@ -/** - * 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 - */ - -import {Writable} from 'stream'; - -import {GeneratedHeader} from './GeneratedHeader'; -import {Property} from './Property'; -import {PropsType, Type} from './Type'; -import {Command} from './Command'; -import {Event} from './Event'; -import {toCppNamespace} from './Converters'; - -export class HeaderWriter { - stream: Writable; - types: Array; - commands: Array; - events: Array; - - constructor( - stream: Writable, - types: Array, - commands: Array, - events: Array, - ) { - this.stream = stream; - this.types = types; - this.commands = commands; - this.events = events; - } - - write() { - this.writePrologue(); - this.writeForwardDecls(); - this.writeRequestHandlerDecls(); - this.writeTypeDecls(); - this.writeRequestDecls(); - this.writeResponseDecls(); - this.writeNotificationDecls(); - this.writeEpilogue(); - } - - writePrologue() { - this.stream.write(`${GeneratedHeader} - - #pragma once - - #include - - #include - - #include - - namespace facebook { - namespace hermes { - namespace inspector { - namespace chrome { - namespace message { - - `); - } - - writeForwardDecls() { - this.stream.write('struct UnknownRequest;\n\n'); - - const namespaceMap: Map> = new Map(); - const addToMap = function (type: Type | Command | Event) { - const domain = type.domain; - let types = namespaceMap.get(domain); - if (!types) { - types = []; - namespaceMap.set(domain, types); - } - types.push(type); - }; - - this.types.forEach(addToMap); - this.commands.forEach(addToMap); - this.events.forEach(addToMap); - - for (const [domain, types] of namespaceMap) { - types.sort((a, b) => { - const nameA = a.getForwardDeclSortKey(); - const nameB = b.getForwardDeclSortKey(); - return nameA < nameB ? -1 : nameA > nameB ? 1 : 0; - }); - - const ns = toCppNamespace(domain); - this.stream.write(`namespace ${ns} {\n`); - - for (const type of types) { - for (const decl of type.getForwardDecls()) { - this.stream.write(`${decl}\n`); - } - } - - this.stream.write(`} // namespace ${ns}\n\n`); - } - } - - writeRequestHandlerDecls() { - this.stream.write( - '\n/// RequestHandler handles requests via the visitor pattern.\n', - ); - emitRequestHandlerDecl(this.stream, this.commands); - - this.stream.write( - '\n/// NoopRequestHandler can be subclassed to only handle some requests.\n', - ); - emitNoopRequestHandlerDecl(this.stream, this.commands); - } - - writeTypeDecls() { - this.stream.write('\n/// Types\n'); - - for (const type of this.types) { - if (type instanceof PropsType) { - emitTypeDecl(this.stream, type); - } - } - } - - writeRequestDecls() { - this.stream.write('\n/// Requests\n'); - - emitUnknownRequestDecl(this.stream); - - for (const command of this.commands) { - emitRequestDecl(this.stream, command); - } - } - - writeResponseDecls() { - this.stream.write('\n/// Responses\n'); - - emitErrorResponseDecl(this.stream); - emitOkResponseDecl(this.stream); - - for (const command of this.commands) { - emitResponseDecl(this.stream, command); - } - } - - writeNotificationDecls() { - this.stream.write('\n/// Notifications\n'); - - for (const event of this.events) { - emitNotificationDecl(this.stream, event); - } - } - - writeEpilogue() { - this.stream.write(` - } // namespace message - } // namespace chrome - } // namespace inspector - } // namespace hermes - } // namespace facebook - `); - } -} - -function emitRequestHandlerDecl(stream: Writable, commands: Array) { - stream.write(`struct RequestHandler { - virtual ~RequestHandler() = default; - - virtual void handle(const UnknownRequest &req) = 0; - `); - - for (const command of commands) { - const cppNs = command.getCppNamespace(); - const cppType = command.getRequestCppType(); - - stream.write(`virtual void handle(const ${cppNs}::${cppType} &req) = 0;`); - } - - stream.write('};\n'); -} - -function emitNoopRequestHandlerDecl( - stream: Writable, - commands: Array, -) { - stream.write(`struct NoopRequestHandler : public RequestHandler { - void handle(const UnknownRequest &req) override {} - `); - - for (const command of commands) { - const cppNs = command.getCppNamespace(); - const cppType = command.getRequestCppType(); - - stream.write(`void handle(const ${cppNs}::${cppType} &req) override {}`); - } - - stream.write('};\n'); -} - -function emitProps(stream: Writable, props: ?Array) { - if (!props || props.length === 0) { - return; - } - - stream.write('\n'); - - for (const prop of props) { - const fullCppType = prop.getFullCppType(); - const cppId = prop.getCppIdentifier(); - const init = prop.getInitializer(); - - stream.write(` ${fullCppType} ${cppId}${init};\n`); - } -} - -export function emitTypeDecl(stream: Writable, type: PropsType) { - const cppNs = type.getCppNamespace(); - const cppType = type.getCppType(); - - stream.write(`struct ${cppNs}::${cppType} : public Serializable { - ${cppType}() = default; - explicit ${cppType}(const folly::dynamic &obj); - folly::dynamic toDynamic() const override; - `); - - if (type instanceof PropsType) { - emitProps(stream, type.properties); - } - - stream.write('};\n\n'); -} - -function emitUnknownRequestDecl(stream: Writable) { - stream.write(`struct UnknownRequest : public Request { - UnknownRequest(); - explicit UnknownRequest(const folly::dynamic &obj); - - folly::dynamic toDynamic() const override; - void accept(RequestHandler &handler) const override; - - folly::Optional params; - }; - - `); -} - -export function emitRequestDecl(stream: Writable, command: Command) { - const cppNs = command.getCppNamespace(); - const cppType = command.getRequestCppType(); - - stream.write(`struct ${cppNs}::${cppType} : public Request { - ${cppType}(); - explicit ${cppType}(const folly::dynamic &obj); - - folly::dynamic toDynamic() const override; - void accept(RequestHandler &handler) const override; - `); - - emitProps(stream, command.parameters); - - stream.write('};\n\n'); -} - -function emitErrorResponseDecl(stream: Writable) { - stream.write(`struct ErrorResponse : public Response { - ErrorResponse() = default; - explicit ErrorResponse(const folly::dynamic &obj); - folly::dynamic toDynamic() const override; - - int code; - std::string message; - folly::Optional data; - }; - - `); -} - -function emitOkResponseDecl(stream: Writable) { - stream.write(`struct OkResponse : public Response { - OkResponse() = default; - explicit OkResponse(const folly::dynamic &obj); - folly::dynamic toDynamic() const override; - }; - - `); -} - -export function emitResponseDecl(stream: Writable, command: Command) { - const cppNs = command.getCppNamespace(); - const cppType = command.getResponseCppType(); - if (!cppType) { - return; - } - - stream.write(`struct ${cppNs}::${cppType} : public Response { - ${cppType}() = default; - explicit ${cppType}(const folly::dynamic &obj); - folly::dynamic toDynamic() const override; - `); - - emitProps(stream, command.returns); - - stream.write('};\n\n'); -} - -export function emitNotificationDecl(stream: Writable, event: Event) { - const cppNs = event.getCppNamespace(); - const cppType = event.getCppType(); - - stream.write(`struct ${cppNs}::${cppType} : public Notification { - ${cppType}(); - explicit ${cppType}(const folly::dynamic &obj); - folly::dynamic toDynamic() const override; - `); - - emitProps(stream, event.parameters); - - stream.write('};\n\n'); -} diff --git a/packages/hermes-inspector-msggen/src/ImplementationWriter.js b/packages/hermes-inspector-msggen/src/ImplementationWriter.js deleted file mode 100644 index e2ff75628271..000000000000 --- a/packages/hermes-inspector-msggen/src/ImplementationWriter.js +++ /dev/null @@ -1,421 +0,0 @@ -/** - * 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 - */ - -import {Writable} from 'stream'; - -import {GeneratedHeader} from './GeneratedHeader'; -import {PropsType, Type} from './Type'; -import {Command} from './Command'; -import {Event} from './Event'; - -export class ImplementationWriter { - stream: Writable; - types: Array; - commands: Array; - events: Array; - - constructor( - stream: Writable, - types: Array, - commands: Array, - events: Array, - ) { - this.stream = stream; - this.types = types; - this.commands = commands; - this.events = events; - } - - write() { - this.writePrologue(); - this.writeRequestParser(); - this.writeTypeDefs(); - this.writeRequestDefs(); - this.writeResponseDefs(); - this.writeNotificationDefs(); - this.writeEpilogue(); - } - - writePrologue() { - this.stream.write(`${GeneratedHeader} - - #include "MessageTypes.h" - - #include "MessageTypesInlines.h" - - namespace facebook { - namespace hermes { - namespace inspector { - namespace chrome { - namespace message { - - `); - } - - writeRequestParser() { - emitRequestParser(this.stream, this.commands); - } - - writeTypeDefs() { - this.stream.write('\n/// Types\n'); - - for (const type of this.types) { - if (type instanceof PropsType) { - emitTypeDef(this.stream, type); - } - } - } - - writeRequestDefs() { - this.stream.write('\n/// Requests\n'); - - emitUnknownRequestDef(this.stream); - - for (const command of this.commands) { - emitRequestDef(this.stream, command); - } - } - - writeResponseDefs() { - this.stream.write('\n/// Responses\n'); - - emitErrorResponseDef(this.stream); - emitOkResponseDef(this.stream); - - for (const command of this.commands) { - emitResponseDef(this.stream, command); - } - } - - writeNotificationDefs() { - this.stream.write('\n/// Notifications\n'); - - for (const event of this.events) { - emitNotificationDef(this.stream, event); - } - } - - writeEpilogue() { - this.stream.write(` - } // namespace message - } // namespace chrome - } // namespace inspector - } // namespace hermes - } // namespace facebook - `); - } -} - -function emitRequestParser(stream: Writable, commands: Array) { - stream.write(` - using RequestBuilder = std::unique_ptr (*)(const dynamic &); - - namespace { - - template - std::unique_ptr makeUnique(const dynamic &obj) { - return std::make_unique(obj); - } - - } // namespace - - std::unique_ptr Request::fromJsonThrowOnError(const std::string &str) { - static std::unordered_map builders = { - `); - - for (const command of commands) { - const cppNs = command.getCppNamespace(); - const cppType = command.getRequestCppType(); - const dbgName = command.getDebuggerName(); - - stream.write(`{"${dbgName}", makeUnique<${cppNs}::${cppType}>},\n`); - } - - stream.write(`}; - - dynamic obj = folly::parseJson(str); - std::string method = obj.at("method").asString(); - - auto it = builders.find(method); - if (it == builders.end()) { - return std::make_unique(obj); - } - - auto builder = it->second; - return builder(obj); - } - - folly::Try> Request::fromJson(const std::string &str) { - return folly::makeTryWith( - [&str] { return Request::fromJsonThrowOnError(str); }); - }\n\n`); - - stream.write('\n'); -} - -export function emitTypeDef(stream: Writable, type: PropsType) { - const cppNs = type.getCppNamespace(); - const cppType = type.getCppType(); - const props = type.properties || []; - - // From-dynamic constructor - stream.write(`${cppNs}::${cppType}::${cppType}(const dynamic &obj) {\n`); - - for (const prop of props) { - const id = prop.getCppIdentifier(); - const name = prop.name; - stream.write(`assign(${id}, obj, "${name}");\n`); - } - - stream.write('}\n\n'); - - // toDynamic - stream.write(`dynamic ${cppNs}::${cppType}::toDynamic() const { - dynamic obj = dynamic::object;\n\n`); - - for (const prop of props) { - const id = prop.getCppIdentifier(); - const name = prop.name; - stream.write(`put(obj, "${name}", ${id});\n`); - } - - stream.write('return obj;\n}\n\n'); -} - -function emitErrorResponseDef(stream: Writable) { - stream.write(`ErrorResponse::ErrorResponse(const dynamic &obj) { - assign(id, obj, "id"); - - dynamic error = obj.at("error"); - assign(code, error, "code"); - assign(message, error, "message"); - assign(data, error, "data"); - } - - dynamic ErrorResponse::toDynamic() const { - dynamic error = dynamic::object; - put(error, "code", code); - put(error, "message", message); - put(error, "data", data); - - dynamic obj = dynamic::object; - put(obj, "id", id); - put(obj, "error", std::move(error)); - return obj; - }\n\n`); -} - -function emitOkResponseDef(stream: Writable) { - stream.write(`OkResponse::OkResponse(const dynamic &obj) { - assign(id, obj, "id"); - } - - dynamic OkResponse::toDynamic() const { - dynamic result = dynamic::object; - - dynamic obj = dynamic::object; - put(obj, "id", id); - put(obj, "result", std::move(result)); - return obj; - }\n\n`); -} - -function emitUnknownRequestDef(stream: Writable) { - stream.write(`UnknownRequest::UnknownRequest() {} - -UnknownRequest::UnknownRequest(const dynamic &obj) { - assign(id, obj, "id"); - assign(method, obj, "method"); - assign(params, obj, "params"); -} - -dynamic UnknownRequest::toDynamic() const { - dynamic obj = dynamic::object; - put(obj, "id", id); - put(obj, "method", method); - put(obj, "params", params); - return obj; -} - -void UnknownRequest::accept(RequestHandler &handler) const { - handler.handle(*this); -}\n\n`); -} - -export function emitRequestDef(stream: Writable, command: Command) { - const cppNs = command.getCppNamespace(); - const cppType = command.getRequestCppType(); - const dbgName = command.getDebuggerName(); - const props = command.parameters || []; - - // Default constructor - stream.write(`${cppNs}::${cppType}::${cppType}() - : Request("${dbgName}") {}\n\n`); - - // From-dynamic constructor - stream.write(`${cppNs}::${cppType}::${cppType}(const dynamic &obj) - : Request("${dbgName}") { - assign(id, obj, "id"); - assign(method, obj, "method");\n\n`); - - if (props.length > 0) { - const optionalParams = props.every(p => p.optional); - if (optionalParams) { - stream.write(` - auto it = obj.find("params"); - if (it != obj.items().end()) { - dynamic params = it->second; - `); - } else { - stream.write('dynamic params = obj.at("params");\n'); - } - - for (const prop of props) { - const id = prop.getCppIdentifier(); - const name = prop.name; - stream.write(`assign(${id}, params, "${name}");\n`); - } - - if (optionalParams) { - stream.write('}'); - } - } - - stream.write('}\n\n'); - - // toDynamic - stream.write(`dynamic ${cppNs}::${cppType}::toDynamic() const {\n`); - - if (props.length > 0) { - stream.write('dynamic params = dynamic::object;\n'); - - for (const prop of props) { - const id = prop.getCppIdentifier(); - const name = prop.name; - stream.write(`put(params, "${name}", ${id});\n`); - } - } - - stream.write(` - dynamic obj = dynamic::object; - put(obj, "id", id); - put(obj, "method", method); - `); - - if (props.length > 0) { - stream.write('put(obj, "params", std::move(params));\n'); - } - - stream.write(`return obj; - }\n\n`); - - // visitor - stream.write(`void ${cppNs}::${cppType}::accept(RequestHandler &handler) const { - handler.handle(*this); - }\n\n`); -} - -export function emitResponseDef(stream: Writable, command: Command) { - const cppNs = command.getCppNamespace(); - const cppType = command.getResponseCppType(); - if (!cppType) { - return; - } - - // From-dynamic constructor - stream.write(`${cppNs}::${cppType}::${cppType}(const dynamic &obj) { - assign(id, obj, "id");\n\n`); - - const props = command.returns || []; - if (props.length > 0) { - stream.write('dynamic res = obj.at("result");\n'); - - for (const prop of props) { - const id = prop.getCppIdentifier(); - const name = prop.name; - stream.write(`assign(${id}, res, "${name}");\n`); - } - } - - stream.write('}\n\n'); - - // toDynamic - stream.write(`dynamic ${cppNs}::${cppType}::toDynamic() const {\n`); - - if (props.length > 0) { - stream.write('dynamic res = dynamic::object;\n'); - - for (const prop of props) { - const id = prop.getCppIdentifier(); - const name = prop.name; - stream.write(`put(res, "${name}", ${id});\n`); - } - } - - stream.write(` - dynamic obj = dynamic::object; - put(obj, "id", id); - put(obj, "result", std::move(res)); - return obj; - }\n\n`); -} - -export function emitNotificationDef(stream: Writable, event: Event) { - const cppNs = event.getCppNamespace(); - const cppType = event.getCppType(); - const dbgName = event.getDebuggerName(); - const props = event.parameters || []; - - // Default constructor - stream.write(`${cppNs}::${cppType}::${cppType}() - : Notification("${dbgName}") {}\n\n`); - - // From-dynamic constructor - stream.write(`${cppNs}::${cppType}::${cppType}(const dynamic &obj) - : Notification("${dbgName}") { - assign(method, obj, "method");\n\n`); - - if (props.length > 0) { - stream.write('dynamic params = obj.at("params");\n'); - - for (const prop of props) { - const id = prop.getCppIdentifier(); - const name = prop.name; - stream.write(`assign(${id}, params, "${name}");\n`); - } - } - - stream.write('}\n\n'); - - // toDynamic - stream.write(`dynamic ${cppNs}::${cppType}::toDynamic() const {\n`); - - if (props.length > 0) { - stream.write('dynamic params = dynamic::object;\n'); - - for (const prop of props) { - const id = prop.getCppIdentifier(); - const name = prop.name; - stream.write(`put(params, "${name}", ${id});\n`); - } - } - - stream.write(` - dynamic obj = dynamic::object; - put(obj, "method", method); - `); - - if (props.length > 0) { - stream.write('put(obj, "params", std::move(params));\n'); - } - - stream.write(`return obj; - }\n\n`); -} diff --git a/packages/hermes-inspector-msggen/src/Property.js b/packages/hermes-inspector-msggen/src/Property.js deleted file mode 100644 index 2ee60145ff67..000000000000 --- a/packages/hermes-inspector-msggen/src/Property.js +++ /dev/null @@ -1,219 +0,0 @@ -/** - * 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 - */ - -import { - jsTypeToCppType, - toCppNamespace, - toCppType, - type JsTypeString, -} from './Converters'; - -export class Property { - domain: string; - name: string; - description: ?string; - exported: ?boolean; - experimental: ?boolean; - optional: ?boolean; - - static create(domain: string, obj: any): Property { - if (obj.$ref) { - return new RefProperty(domain, obj); - } else if (obj.type === 'array') { - return new ArrayProperty(domain, obj); - } - return new PrimitiveProperty(domain, obj); - } - - static createArray( - domain: string, - elements: Array, - ignoreExperimental: boolean, - ): Array { - let props = elements.map(elem => Property.create(domain, elem)); - if (ignoreExperimental) { - props = props.filter(prop => !prop.experimental); - } - return props; - } - - constructor(domain: string, obj: any) { - this.domain = domain; - this.name = obj.name; - this.description = obj.description; - this.exported = obj.exported; - this.experimental = obj.experimental; - this.optional = obj.optional; - } - - getRefDebuggerName(): ?string { - throw new Error('subclass must implement'); - } - - getFullCppType(): string { - throw new Error('subclass must implement'); - } - - getCppIdentifier(): string { - // need to munge identifier if it matches a C++ keyword like "this" - if (this.name === 'this') { - return 'thisObj'; - } - return this.name; - } - - getInitializer(): string { - throw new Error('subclass must implement'); - } -} - -function maybeWrapOptional( - type: string, - optional: ?boolean, - recursive: ?boolean, -) { - if (optional) { - return recursive ? `std::unique_ptr<${type}>` : `folly::Optional<${type}>`; - } - return type; -} - -function toDomainAndId( - curDomain: string, - absOrRelRef: string, -): [string, string] { - let [domain, id] = ['', '']; - - // absOrRelRef can be: - // 1) absolute ref with a "." referencing a type from another namespace, like - // "Runtime.ExceptionDetails" - // 2) relative ref without a "." referencing a type in current domain, like - // "Domain" - const i = absOrRelRef.indexOf('.'); - if (i === -1) { - domain = curDomain; - id = absOrRelRef; - } else { - domain = absOrRelRef.substr(0, i); - id = absOrRelRef.substr(i + 1); - } - - return [domain, id]; -} - -function toFullCppType(curDomain: string, absOrRelRef: string) { - const [domain, id] = toDomainAndId(curDomain, absOrRelRef); - return `${toCppNamespace(domain)}::${toCppType(id)}`; -} - -class PrimitiveProperty extends Property { - type: JsTypeString; - - constructor(domain: string, obj: any) { - super(domain, obj); - this.type = obj.type; - } - - getRefDebuggerName(): ?string { - return undefined; - } - - getFullCppType(): string { - return maybeWrapOptional(jsTypeToCppType(this.type), this.optional); - } - - getInitializer(): string { - // folly::Optional doesn't need to be explicitly zero-init - if (this.optional) { - return ''; - } - - // we want to explicitly zero-init bool, int, and double - const type = this.type; - if (type === 'boolean' || type === 'integer' || type === 'number') { - return '{}'; - } - - // everything else (folly::dynamic and std::string) has sensible default - // constructor, no need to explicitly zero-init - return ''; - } -} - -class RefProperty extends Property { - $ref: string; - recursive: ?boolean; - - constructor(domain: string, obj: any) { - super(domain, obj); - this.$ref = obj.$ref; - this.recursive = obj.recursive; - } - - getRefDebuggerName(): ?string { - const [domain, id] = toDomainAndId(this.domain, this.$ref); - return `${domain}.${id}`; - } - - getFullCppType(): string { - const fullCppType = toFullCppType(this.domain, this.$ref); - return maybeWrapOptional(`${fullCppType}`, this.optional, this.recursive); - } - - getInitializer(): string { - // must zero-init non-optional ref props since the ref could just be an - // alias to a C++ primitive type like int which we always want to zero-init - return this.optional ? '' : '{}'; - } -} - -class ArrayProperty extends Property { - type: 'array'; - items: - | {|type: JsTypeString, recursive: false|} - | {|$ref: string, recursive: ?boolean|}; - - constructor(domain: string, obj: any) { - super(domain, obj); - this.type = obj.type; - this.items = obj.items; - } - - getRefDebuggerName(): ?string { - if (this.items && this.items.$ref && !this.items.recursive) { - const [domain, id] = toDomainAndId(this.domain, this.items.$ref); - return `${domain}.${id}`; - } - } - - getFullCppType(): string { - let elemType: string = 'folly::dynamic'; - let recursive: ?(false | boolean) = false; - - if (this.items) { - if (this.items.type) { - elemType = jsTypeToCppType(this.items.type); - } else if (this.items.$ref) { - elemType = toFullCppType(this.domain, this.items.$ref); - recursive = this.items.recursive; - } - } - - return maybeWrapOptional( - `std::vector<${elemType}>`, - this.optional, - recursive, - ); - } - - getInitializer(): string { - return ''; - } -} diff --git a/packages/hermes-inspector-msggen/src/TestHelpers.js b/packages/hermes-inspector-msggen/src/TestHelpers.js deleted file mode 100644 index c53ab4c94678..000000000000 --- a/packages/hermes-inspector-msggen/src/TestHelpers.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 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. - */ - -/*global expect*/ - -// munges string so that it's nice to look at in a test diff -function strip(str) { - // Trim leading and trailing WS - str = str.replace(/^\s+/, ''); - str = str.replace(/\s+$/, ''); - - // Collapse all repeating newlines (possibly with spaces in between) into a - // single newline - str = str.replace(/\n(\s*)/g, '\n'); - - // Collapse all non-newline whitespace into a single space - return str.replace(/[^\S\n]+/g, ' '); -} - -export function expectCodeIsEqual(actual, expected) { - expect(strip(actual)).toBe(strip(expected)); -} - -export class FakeWritable { - constructor() { - this.result = ''; - } - - write(str) { - this.result += str; - } - - get() { - return this.result; - } -} diff --git a/packages/hermes-inspector-msggen/src/Type.js b/packages/hermes-inspector-msggen/src/Type.js deleted file mode 100644 index 18f9ac11cf5e..000000000000 --- a/packages/hermes-inspector-msggen/src/Type.js +++ /dev/null @@ -1,98 +0,0 @@ -/** - * 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 - */ - -import {Property} from './Property'; -import {jsTypeToCppType, toCppNamespace, toCppType} from './Converters'; - -export class Type { - domain: string; - id: string; - description: ?string; - exported: ?boolean; - experimental: ?boolean; - - static create(domain: string, obj: any, ignoreExperimental: boolean): ?Type { - let type = null; - - if (obj.type === 'object' && obj.properties) { - type = new PropsType(domain, obj, ignoreExperimental); - } else if (obj.type) { - type = new PrimitiveType(domain, obj, ignoreExperimental); - } else { - throw new TypeError('Type requires `type` property.'); - } - - if (ignoreExperimental && type.experimental) { - type = null; - } - - return type; - } - - constructor(domain: string, obj: any) { - this.domain = domain; - this.id = obj.id; - this.description = obj.description; - this.exported = obj.exported; - this.experimental = obj.experimental; - } - - getDebuggerName(): string { - return `${this.domain}.${this.id}`; - } - - getCppNamespace(): string { - return toCppNamespace(this.domain); - } - - getCppType(): string { - return toCppType(this.id); - } - - getForwardDecls(): Array { - throw new Error('subclass must implement'); - } - - getForwardDeclSortKey(): string { - return this.getCppType(); - } -} - -export class PrimitiveType extends Type { - type: 'integer' | 'number' | 'object' | 'string'; - - constructor(domain: string, obj: any, ignoreExperimental: boolean) { - super(domain, obj); - this.type = obj.type; - } - - getForwardDecls(): Array { - return [`using ${this.getCppType()} = ${jsTypeToCppType(this.type)};`]; - } -} - -export class PropsType extends Type { - type: 'object'; - properties: Array; - - constructor(domain: string, obj: any, ignoreExperimental: boolean) { - super(domain, obj); - this.type = obj.type; - this.properties = Property.createArray( - domain, - obj.properties || [], - ignoreExperimental, - ); - } - - getForwardDecls(): Array { - return [`struct ${this.getCppType()};`]; - } -} diff --git a/packages/hermes-inspector-msggen/src/custom.json b/packages/hermes-inspector-msggen/src/custom.json deleted file mode 100644 index c9650a9c293a..000000000000 --- a/packages/hermes-inspector-msggen/src/custom.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "domains": [ - { - "domain": "Hermes", - "description": "Hermes specific messages", - "commands": [ - { - "name": "setPauseOnLoad", - "description": "Pause VM when new scripts are loaded (reason='load')", - "parameters": [ - { - "name": "state", - "description": "Pause on script load mode", - "type": "string", - "enum": [ - "none", - "smart", - "all" - ] - } - ] - } - ] - } - ] -} diff --git a/packages/hermes-inspector-msggen/src/index.js b/packages/hermes-inspector-msggen/src/index.js deleted file mode 100644 index 5826643c753d..000000000000 --- a/packages/hermes-inspector-msggen/src/index.js +++ /dev/null @@ -1,251 +0,0 @@ -/** - * 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 - */ - -import fs from 'fs'; - -import yargs from 'yargs'; - -import {Command} from './Command'; -import {Event} from './Event'; -import {Graph} from './Graph'; -import {Property} from './Property'; -import {PropsType, Type} from './Type'; - -import {HeaderWriter} from './HeaderWriter'; -import {ImplementationWriter} from './ImplementationWriter'; - -// $FlowFixMe[cannot-resolve-module] : this isn't a module, just a JSON file. -const standard = require('devtools-protocol/json/js_protocol.json'); - -const custom = require('../src/custom.json'); - -type Descriptor = {| - types: Array, - commands: Array, - events: Array, -|}; - -function mergeDomains(original: any, extra: any) { - return {...original, domains: original.domains.concat(extra.domains)}; -} - -const proto = mergeDomains(standard, custom); - -function parseDomains( - domainObjs: Array, - ignoreExperimental: boolean, - includeExperimental: Set, -): Descriptor { - const desc = { - types: ([]: Array), - commands: ([]: Array), - events: ([]: Array), - }; - - for (const obj of domainObjs) { - const domain = obj.domain; - - for (const typeObj of obj.types || []) { - const type = Type.create(domain, typeObj, ignoreExperimental); - if (type) { - desc.types.push(type); - } - } - - for (const commandObj of obj.commands || []) { - const command = Command.create( - domain, - commandObj, - !includeExperimental.has(`${domain}.${commandObj.name}`) && - ignoreExperimental, - ); - if (command) { - desc.commands.push(command); - } - } - - for (const eventObj of obj.events || []) { - const event = Event.create(domain, eventObj, ignoreExperimental); - if (event) { - desc.events.push(event); - } - } - } - - return desc; -} - -function buildGraph(desc: Descriptor): Graph { - const graph = new Graph(); - - const types = desc.types; - const commands = desc.commands; - const events = desc.events; - - const maybeAddPropEdges = function (nodeId: string, props: ?Array) { - if (props) { - for (const prop of props) { - const refId = prop.getRefDebuggerName(); - (prop: Object).recursive = refId && refId === nodeId; - if (refId && refId !== nodeId) { - // Don't add edges for recursive properties. - graph.addEdge(nodeId, refId); - } - } - } - }; - - for (const type of types) { - graph.addNode(type.getDebuggerName()); - - if (type instanceof PropsType) { - maybeAddPropEdges(type.getDebuggerName(), type.properties); - } - } - - for (const command of commands) { - graph.addNode(command.getDebuggerName()); - - maybeAddPropEdges(command.getDebuggerName(), command.parameters); - maybeAddPropEdges(command.getDebuggerName(), command.returns); - } - - for (const event of events) { - graph.addNode(event.getDebuggerName()); - - maybeAddPropEdges(event.getDebuggerName(), event.parameters); - } - - return graph; -} - -function parseRoots(desc: Descriptor, rootsPath: ?string): Array { - const roots = []; - - if (rootsPath) { - const buf = fs.readFileSync(rootsPath); - for (let line of buf.toString().split('\n')) { - line = line.trim(); - - // ignore comments and blank lines - if (!line.match(/\s*#/) && line.length > 0) { - roots.push(line); - } - } - } else { - for (const type of desc.types) { - roots.push(type.getDebuggerName()); - } - for (const command of desc.commands) { - roots.push(command.getDebuggerName()); - } - for (const event of desc.events) { - roots.push(event.getDebuggerName()); - } - } - - return roots; -} - -// only include types, commands, events that can be reached from the given -// root messages -function filterReachableFromRoots( - desc: Descriptor, - graph: Graph, - roots: Array, -): Descriptor { - const topoSortedIds = graph.traverse(roots); - - // Types can include other types by value, so they need to be topologically - // sorted in the header. - const typeMap: Map = new Map(); - for (const type of desc.types) { - typeMap.set(type.getDebuggerName(), type); - } - - const types = []; - for (const id of topoSortedIds) { - const type = typeMap.get(id); - if (type) { - types.push(type); - } - } - - // Commands and events don't depend on each other, so just emit them in the - // order we got them from the JSON file. - const ids = new Set(topoSortedIds); - const commands = desc.commands.filter(cmd => ids.has(cmd.getDebuggerName())); - const events = desc.events.filter(event => ids.has(event.getDebuggerName())); - - // Sort commands and events so the code is easier to read. Types have to be - // topologically sorted as explained above. - const comparator = (a: Command | Event, b: Command | Event) => { - const id1 = a.getDebuggerName(); - const id2 = b.getDebuggerName(); - return id1 < id2 ? -1 : id1 > id2 ? 1 : 0; - }; - commands.sort(comparator); - events.sort(comparator); - - return {types, commands, events}; -} - -async function main(): Promise { - const args = await yargs - .usage('Usage: msggen ') - .alias('h', 'help') - .help('h') - .boolean('e') - .alias('e', 'ignore-experimental') - .describe('e', 'ignore experimental commands, props, and types') - .alias('i', 'include-experimental') - .describe('i', 'experimental commands to include') - .alias('r', 'roots') - .describe('r', 'path to a file listing root types, events, and commands') - .nargs('r', 1) - .demandCommand(2, 2).argv; - - const ignoreExperimental = !!args.e; - const includeExperimental = new Set( - typeof args.i === 'string' ? args.i.split(',') : [], - ); - const [headerPath, implPath] = args._; - - const headerStream = fs.createWriteStream(headerPath); - const implStream = fs.createWriteStream(implPath); - - const desc = parseDomains( - proto.domains, - ignoreExperimental, - includeExperimental, - ); - const graph = buildGraph(desc); - const roots = parseRoots(desc, String(args.roots)); - - const reachable = filterReachableFromRoots(desc, graph, roots); - - const hw = new HeaderWriter( - headerStream, - reachable.types, - reachable.commands, - reachable.events, - ); - hw.write(); - - const iw = new ImplementationWriter( - implStream, - reachable.types, - reachable.commands, - reachable.events, - ); - iw.write(); -} - -main(); diff --git a/packages/normalize-color/.npmignore b/packages/normalize-color/.npmignore deleted file mode 100644 index 9b166b095d3f..000000000000 --- a/packages/normalize-color/.npmignore +++ /dev/null @@ -1,3 +0,0 @@ -**/__mocks__/** -**/__tests__/** -BUCK diff --git a/packages/normalize-color/BUCK b/packages/normalize-color/BUCK deleted file mode 100644 index faaff9e880b0..000000000000 --- a/packages/normalize-color/BUCK +++ /dev/null @@ -1,30 +0,0 @@ -load("@fbsource//tools/build_defs/third_party:yarn_defs.bzl", "yarn_workspace") -load("@fbsource//xplat/js:JS_DEFS.bzl", "rn_library") - -rn_library( - name = "normalize-color", - labels = [ - "pfh:ReactNative_CommonInfrastructurePlaceholder", - ], - skip_processors = True, - visibility = ["PUBLIC"], -) - -yarn_workspace( - name = "yarn-workspace", - srcs = glob( - [ - "**/*.js", - "**/*.json", - ], - exclude = [ - "**/__fixtures__/**", - "**/__flowtests__/**", - "**/__mocks__/**", - "**/__tests__/**", - "**/node_modules/**", - "**/node_modules/.bin/**", - ], - ), - visibility = ["PUBLIC"], -) diff --git a/packages/normalize-color/__tests__/normalizeColor-test.js b/packages/normalize-color/__tests__/normalizeColor-test.js deleted file mode 100644 index 56d47df5e159..000000000000 --- a/packages/normalize-color/__tests__/normalizeColor-test.js +++ /dev/null @@ -1,156 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - * @oncall react_native - */ - -'use strict'; - -import normalizeColor from '..'; - -it('accepts only spec compliant colors', () => { - expect(normalizeColor('#abc')).not.toBe(null); - expect(normalizeColor('#abcd')).not.toBe(null); - expect(normalizeColor('#abcdef')).not.toBe(null); - expect(normalizeColor('#abcdef01')).not.toBe(null); - expect(normalizeColor('rgb(1,2,3)')).not.toBe(null); - expect(normalizeColor('rgb(1 2 3)')).not.toBe(null); - expect(normalizeColor('rgb(1, 2, 3)')).not.toBe(null); - expect(normalizeColor('rgb( 1 , 2 , 3 )')).not.toBe(null); - expect(normalizeColor('rgb(-1, -2, -3)')).not.toBe(null); - expect(normalizeColor('rgba(0, 0, 0, 1)')).not.toBe(null); - expect(normalizeColor(0x01234567 + 0.5)).toBe(null); - expect(normalizeColor(-1)).toBe(null); - expect(normalizeColor(0xffffffff + 1)).toBe(null); -}); - -it('temporarilys accept floating point values for rgb', () => { - expect(normalizeColor('rgb(1.1, 2.1, 3.1)')).toBe(0x010203ff); - expect(normalizeColor('rgba(1.1, 2.1, 3.1, 1.0)')).toBe(0x010203ff); -}); - -it('refuses non-spec compliant colors', () => { - expect(normalizeColor('#00gg00')).toBe(null); - expect(normalizeColor('rgb(1, 2, 3,)')).toBe(null); - expect(normalizeColor('rgb(1, 2, 3')).toBe(null); - - // Used to be accepted by normalizeColor - expect(normalizeColor('abc')).toBe(null); - expect(normalizeColor(' #abc ')).toBe(null); - expect(normalizeColor('##abc')).toBe(null); - expect(normalizeColor('rgb 255 0 0')).toBe(null); - expect(normalizeColor('RGBA(0, 1, 2)')).toBe(null); - expect(normalizeColor('rgb (0, 1, 2)')).toBe(null); - expect(normalizeColor('rgba(0 0 0 0.0)')).toBe(null); - expect(normalizeColor('hsv(0, 1, 2)')).toBe(null); - // $FlowExpectedError - Intentionally malformed argument. - expect(normalizeColor({r: 10, g: 10, b: 10})).toBe(null); - expect(normalizeColor('hsl(1%, 2, 3)')).toBe(null); - expect(normalizeColor('rgb(1%, 2%, 3%)')).toBe(null); -}); - -it('handles hex6 properly', () => { - expect(normalizeColor('#000000')).toBe(0x000000ff); - expect(normalizeColor('#ffffff')).toBe(0xffffffff); - expect(normalizeColor('#ff00ff')).toBe(0xff00ffff); - expect(normalizeColor('#abcdef')).toBe(0xabcdefff); - expect(normalizeColor('#012345')).toBe(0x012345ff); -}); - -it('handles hex3 properly', () => { - expect(normalizeColor('#000')).toBe(0x000000ff); - expect(normalizeColor('#fff')).toBe(0xffffffff); - expect(normalizeColor('#f0f')).toBe(0xff00ffff); -}); - -it('handles hex8 properly', () => { - expect(normalizeColor('#00000000')).toBe(0x00000000); - expect(normalizeColor('#ffffffff')).toBe(0xffffffff); - expect(normalizeColor('#ffff00ff')).toBe(0xffff00ff); - expect(normalizeColor('#abcdef01')).toBe(0xabcdef01); - expect(normalizeColor('#01234567')).toBe(0x01234567); -}); - -it('handles rgb properly', () => { - expect(normalizeColor('rgb(0, 0, 0)')).toBe(0x000000ff); - expect(normalizeColor('rgb(-1, -2, -3)')).toBe(0x000000ff); - expect(normalizeColor('rgb(0, 0, 255)')).toBe(0x0000ffff); - expect(normalizeColor('rgb(100, 15, 69)')).toBe(0x640f45ff); - expect(normalizeColor('rgb(255, 255, 255)')).toBe(0xffffffff); - expect(normalizeColor('rgb(256, 256, 256)')).toBe(0xffffffff); - expect(normalizeColor('rgb(0 0 0)')).toBe(0x000000ff); - expect(normalizeColor('rgb(0 0 255)')).toBe(0x0000ffff); -}); - -it('handles rgba properly', () => { - expect(normalizeColor('rgba(0, 0, 0, 0.0)')).toBe(0x00000000); - expect(normalizeColor('rgba(0, 0, 0, 0)')).toBe(0x00000000); - expect(normalizeColor('rgba(0, 0, 0, -0.5)')).toBe(0x00000000); - expect(normalizeColor('rgba(0, 0, 0, 1.0)')).toBe(0x000000ff); - expect(normalizeColor('rgba(0, 0, 0, 1)')).toBe(0x000000ff); - expect(normalizeColor('rgba(0, 0, 0, 1.5)')).toBe(0x000000ff); - expect(normalizeColor('rgba(100, 15, 69, 0.5)')).toBe(0x640f4580); - expect(normalizeColor('rgba(0 0 0 / 0.0)')).toBe(0x00000000); - expect(normalizeColor('rgba(0 0 0 / 1)')).toBe(0x000000ff); - expect(normalizeColor('rgba(100 15 69 / 0.5)')).toBe(0x640f4580); -}); - -it('handles hsl properly', () => { - expect(normalizeColor('hsl(0, 0%, 0%)')).toBe(0x000000ff); - expect(normalizeColor('hsl(360, 100%, 100%)')).toBe(0xffffffff); - expect(normalizeColor('hsl(180, 50%, 50%)')).toBe(0x40bfbfff); - expect(normalizeColor('hsl(540, 50%, 50%)')).toBe(0x40bfbfff); - expect(normalizeColor('hsl(70, 25%, 75%)')).toBe(0xcacfafff); - expect(normalizeColor('hsl(70, 100%, 75%)')).toBe(0xeaff80ff); - expect(normalizeColor('hsl(70, 110%, 75%)')).toBe(0xeaff80ff); - expect(normalizeColor('hsl(70, 0%, 75%)')).toBe(0xbfbfbfff); - expect(normalizeColor('hsl(70, -10%, 75%)')).toBe(0xbfbfbfff); - expect(normalizeColor('hsl(0 0% 0%)')).toBe(0x000000ff); - expect(normalizeColor('hsl(360 100% 100%)')).toBe(0xffffffff); - expect(normalizeColor('hsl(180 50% 50%)')).toBe(0x40bfbfff); -}); - -it('handles hsla properly', () => { - expect(normalizeColor('hsla(0, 0%, 0%, 0)')).toBe(0x00000000); - expect(normalizeColor('hsla(360, 100%, 100%, 1)')).toBe(0xffffffff); - expect(normalizeColor('hsla(360, 100%, 100%, 0)')).toBe(0xffffff00); - expect(normalizeColor('hsla(180, 50%, 50%, 0.2)')).toBe(0x40bfbf33); - expect(normalizeColor('hsla(0 0% 0% / 0)')).toBe(0x00000000); - expect(normalizeColor('hsla(360 100% 100% / 1)')).toBe(0xffffffff); - expect(normalizeColor('hsla(360 100% 100% / 0)')).toBe(0xffffff00); - expect(normalizeColor('hsla(180 50% 50% / 0.2)')).toBe(0x40bfbf33); -}); - -it('handles hwb properly', () => { - expect(normalizeColor('hwb(0, 0%, 100%)')).toBe(0x000000ff); - expect(normalizeColor('hwb(0, 100%, 0%)')).toBe(0xffffffff); - expect(normalizeColor('hwb(0, 0%, 0%)')).toBe(0xff0000ff); - expect(normalizeColor('hwb(70, 50%, 0%)')).toBe(0xeaff80ff); - expect(normalizeColor('hwb(0, 50%, 50%)')).toBe(0x808080ff); - expect(normalizeColor('hwb(360, 100%, 100%)')).toBe(0x808080ff); - expect(normalizeColor('hwb(0 0% 0%)')).toBe(0xff0000ff); - expect(normalizeColor('hwb(70 50% 0%)')).toBe(0xeaff80ff); -}); - -it('handles named colors properly', () => { - expect(normalizeColor('red')).toBe(0xff0000ff); - expect(normalizeColor('transparent')).toBe(0x00000000); - expect(normalizeColor('peachpuff')).toBe(0xffdab9ff); -}); - -it('handles number colors properly', () => { - expect(normalizeColor(0x00000000)).toBe(0x00000000); - expect(normalizeColor(0xff0000ff)).toBe(0xff0000ff); - expect(normalizeColor(0xffffffff)).toBe(0xffffffff); - expect(normalizeColor(0x01234567)).toBe(0x01234567); -}); - -it('returns the same color when it is already normalized', () => { - const normalizedColor = normalizeColor('red') || 0; - expect(normalizeColor(normalizedColor)).toBe(normalizedColor); -}); diff --git a/packages/normalize-color/index.js b/packages/normalize-color/index.js deleted file mode 100644 index 611baaffc138..000000000000 --- a/packages/normalize-color/index.js +++ /dev/null @@ -1,461 +0,0 @@ -/** - * 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 - */ - -/* eslint no-bitwise: 0 */ - -'use strict'; - -function normalizeColor(color) { - if (typeof color === 'number') { - if (color >>> 0 === color && color >= 0 && color <= 0xffffffff) { - return color; - } - return null; - } - - if (typeof color !== 'string') { - return null; - } - - const matchers = getMatchers(); - let match; - - // Ordered based on occurrences on Facebook codebase - if ((match = matchers.hex6.exec(color))) { - return parseInt(match[1] + 'ff', 16) >>> 0; - } - - const colorFromKeyword = normalizeKeyword(color); - if (colorFromKeyword != null) { - return colorFromKeyword; - } - - if ((match = matchers.rgb.exec(color))) { - return ( - ((parse255(match[1]) << 24) | // r - (parse255(match[2]) << 16) | // g - (parse255(match[3]) << 8) | // b - 0x000000ff) >>> // a - 0 - ); - } - - if ((match = matchers.rgba.exec(color))) { - // rgba(R G B / A) notation - if (match[6] !== undefined) { - return ( - ((parse255(match[6]) << 24) | // r - (parse255(match[7]) << 16) | // g - (parse255(match[8]) << 8) | // b - parse1(match[9])) >>> // a - 0 - ); - } - - // rgba(R, G, B, A) notation - return ( - ((parse255(match[2]) << 24) | // r - (parse255(match[3]) << 16) | // g - (parse255(match[4]) << 8) | // b - parse1(match[5])) >>> // a - 0 - ); - } - - if ((match = matchers.hex3.exec(color))) { - return ( - parseInt( - match[1] + - match[1] + // r - match[2] + - match[2] + // g - match[3] + - match[3] + // b - 'ff', // a - 16, - ) >>> 0 - ); - } - - // https://drafts.csswg.org/css-color-4/#hex-notation - if ((match = matchers.hex8.exec(color))) { - return parseInt(match[1], 16) >>> 0; - } - - if ((match = matchers.hex4.exec(color))) { - return ( - parseInt( - match[1] + - match[1] + // r - match[2] + - match[2] + // g - match[3] + - match[3] + // b - match[4] + - match[4], // a - 16, - ) >>> 0 - ); - } - - if ((match = matchers.hsl.exec(color))) { - return ( - (hslToRgb( - parse360(match[1]), // h - parsePercentage(match[2]), // s - parsePercentage(match[3]), // l - ) | - 0x000000ff) >>> // a - 0 - ); - } - - if ((match = matchers.hsla.exec(color))) { - // hsla(H S L / A) notation - if (match[6] !== undefined) { - return ( - (hslToRgb( - parse360(match[6]), // h - parsePercentage(match[7]), // s - parsePercentage(match[8]), // l - ) | - parse1(match[9])) >>> // a - 0 - ); - } - - // hsla(H, S, L, A) notation - return ( - (hslToRgb( - parse360(match[2]), // h - parsePercentage(match[3]), // s - parsePercentage(match[4]), // l - ) | - parse1(match[5])) >>> // a - 0 - ); - } - - if ((match = matchers.hwb.exec(color))) { - return ( - (hwbToRgb( - parse360(match[1]), // h - parsePercentage(match[2]), // w - parsePercentage(match[3]), // b - ) | - 0x000000ff) >>> // a - 0 - ); - } - - return null; -} - -function hue2rgb(p, q, t) { - if (t < 0) { - t += 1; - } - if (t > 1) { - t -= 1; - } - if (t < 1 / 6) { - return p + (q - p) * 6 * t; - } - if (t < 1 / 2) { - return q; - } - if (t < 2 / 3) { - return p + (q - p) * (2 / 3 - t) * 6; - } - return p; -} - -function hslToRgb(h, s, l) { - const q = l < 0.5 ? l * (1 + s) : l + s - l * s; - const p = 2 * l - q; - const r = hue2rgb(p, q, h + 1 / 3); - const g = hue2rgb(p, q, h); - const b = hue2rgb(p, q, h - 1 / 3); - - return ( - (Math.round(r * 255) << 24) | - (Math.round(g * 255) << 16) | - (Math.round(b * 255) << 8) - ); -} - -function hwbToRgb(h, w, b) { - if (w + b >= 1) { - const gray = Math.round((w * 255) / (w + b)); - - return (gray << 24) | (gray << 16) | (gray << 8); - } - - const red = hue2rgb(0, 1, h + 1 / 3) * (1 - w - b) + w; - const green = hue2rgb(0, 1, h) * (1 - w - b) + w; - const blue = hue2rgb(0, 1, h - 1 / 3) * (1 - w - b) + w; - - return ( - (Math.round(red * 255) << 24) | - (Math.round(green * 255) << 16) | - (Math.round(blue * 255) << 8) - ); -} - -const NUMBER = '[-+]?\\d*\\.?\\d+'; -const PERCENTAGE = NUMBER + '%'; - -function call(...args) { - return '\\(\\s*(' + args.join(')\\s*,?\\s*(') + ')\\s*\\)'; -} - -function callWithSlashSeparator(...args) { - return ( - '\\(\\s*(' + - args.slice(0, args.length - 1).join(')\\s*,?\\s*(') + - ')\\s*/\\s*(' + - args[args.length - 1] + - ')\\s*\\)' - ); -} - -function commaSeparatedCall(...args) { - return '\\(\\s*(' + args.join(')\\s*,\\s*(') + ')\\s*\\)'; -} - -let cachedMatchers; - -function getMatchers() { - if (cachedMatchers === undefined) { - cachedMatchers = { - rgb: new RegExp('rgb' + call(NUMBER, NUMBER, NUMBER)), - rgba: new RegExp( - 'rgba(' + - commaSeparatedCall(NUMBER, NUMBER, NUMBER, NUMBER) + - '|' + - callWithSlashSeparator(NUMBER, NUMBER, NUMBER, NUMBER) + - ')', - ), - hsl: new RegExp('hsl' + call(NUMBER, PERCENTAGE, PERCENTAGE)), - hsla: new RegExp( - 'hsla(' + - commaSeparatedCall(NUMBER, PERCENTAGE, PERCENTAGE, NUMBER) + - '|' + - callWithSlashSeparator(NUMBER, PERCENTAGE, PERCENTAGE, NUMBER) + - ')', - ), - hwb: new RegExp('hwb' + call(NUMBER, PERCENTAGE, PERCENTAGE)), - hex3: /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, - hex4: /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, - hex6: /^#([0-9a-fA-F]{6})$/, - hex8: /^#([0-9a-fA-F]{8})$/, - }; - } - return cachedMatchers; -} - -function parse255(str) { - const int = parseInt(str, 10); - if (int < 0) { - return 0; - } - if (int > 255) { - return 255; - } - return int; -} - -function parse360(str) { - const int = parseFloat(str); - return (((int % 360) + 360) % 360) / 360; -} - -function parse1(str) { - const num = parseFloat(str); - if (num < 0) { - return 0; - } - if (num > 1) { - return 255; - } - return Math.round(num * 255); -} - -function parsePercentage(str) { - // parseFloat conveniently ignores the final % - const int = parseFloat(str); - if (int < 0) { - return 0; - } - if (int > 100) { - return 1; - } - return int / 100; -} - -function normalizeKeyword(name) { - // prettier-ignore - switch (name) { - case 'transparent': return 0x00000000; - // http://www.w3.org/TR/css3-color/#svg-color - case 'aliceblue': return 0xf0f8ffff; - case 'antiquewhite': return 0xfaebd7ff; - case 'aqua': return 0x00ffffff; - case 'aquamarine': return 0x7fffd4ff; - case 'azure': return 0xf0ffffff; - case 'beige': return 0xf5f5dcff; - case 'bisque': return 0xffe4c4ff; - case 'black': return 0x000000ff; - case 'blanchedalmond': return 0xffebcdff; - case 'blue': return 0x0000ffff; - case 'blueviolet': return 0x8a2be2ff; - case 'brown': return 0xa52a2aff; - case 'burlywood': return 0xdeb887ff; - case 'burntsienna': return 0xea7e5dff; - case 'cadetblue': return 0x5f9ea0ff; - case 'chartreuse': return 0x7fff00ff; - case 'chocolate': return 0xd2691eff; - case 'coral': return 0xff7f50ff; - case 'cornflowerblue': return 0x6495edff; - case 'cornsilk': return 0xfff8dcff; - case 'crimson': return 0xdc143cff; - case 'cyan': return 0x00ffffff; - case 'darkblue': return 0x00008bff; - case 'darkcyan': return 0x008b8bff; - case 'darkgoldenrod': return 0xb8860bff; - case 'darkgray': return 0xa9a9a9ff; - case 'darkgreen': return 0x006400ff; - case 'darkgrey': return 0xa9a9a9ff; - case 'darkkhaki': return 0xbdb76bff; - case 'darkmagenta': return 0x8b008bff; - case 'darkolivegreen': return 0x556b2fff; - case 'darkorange': return 0xff8c00ff; - case 'darkorchid': return 0x9932ccff; - case 'darkred': return 0x8b0000ff; - case 'darksalmon': return 0xe9967aff; - case 'darkseagreen': return 0x8fbc8fff; - case 'darkslateblue': return 0x483d8bff; - case 'darkslategray': return 0x2f4f4fff; - case 'darkslategrey': return 0x2f4f4fff; - case 'darkturquoise': return 0x00ced1ff; - case 'darkviolet': return 0x9400d3ff; - case 'deeppink': return 0xff1493ff; - case 'deepskyblue': return 0x00bfffff; - case 'dimgray': return 0x696969ff; - case 'dimgrey': return 0x696969ff; - case 'dodgerblue': return 0x1e90ffff; - case 'firebrick': return 0xb22222ff; - case 'floralwhite': return 0xfffaf0ff; - case 'forestgreen': return 0x228b22ff; - case 'fuchsia': return 0xff00ffff; - case 'gainsboro': return 0xdcdcdcff; - case 'ghostwhite': return 0xf8f8ffff; - case 'gold': return 0xffd700ff; - case 'goldenrod': return 0xdaa520ff; - case 'gray': return 0x808080ff; - case 'green': return 0x008000ff; - case 'greenyellow': return 0xadff2fff; - case 'grey': return 0x808080ff; - case 'honeydew': return 0xf0fff0ff; - case 'hotpink': return 0xff69b4ff; - case 'indianred': return 0xcd5c5cff; - case 'indigo': return 0x4b0082ff; - case 'ivory': return 0xfffff0ff; - case 'khaki': return 0xf0e68cff; - case 'lavender': return 0xe6e6faff; - case 'lavenderblush': return 0xfff0f5ff; - case 'lawngreen': return 0x7cfc00ff; - case 'lemonchiffon': return 0xfffacdff; - case 'lightblue': return 0xadd8e6ff; - case 'lightcoral': return 0xf08080ff; - case 'lightcyan': return 0xe0ffffff; - case 'lightgoldenrodyellow': return 0xfafad2ff; - case 'lightgray': return 0xd3d3d3ff; - case 'lightgreen': return 0x90ee90ff; - case 'lightgrey': return 0xd3d3d3ff; - case 'lightpink': return 0xffb6c1ff; - case 'lightsalmon': return 0xffa07aff; - case 'lightseagreen': return 0x20b2aaff; - case 'lightskyblue': return 0x87cefaff; - case 'lightslategray': return 0x778899ff; - case 'lightslategrey': return 0x778899ff; - case 'lightsteelblue': return 0xb0c4deff; - case 'lightyellow': return 0xffffe0ff; - case 'lime': return 0x00ff00ff; - case 'limegreen': return 0x32cd32ff; - case 'linen': return 0xfaf0e6ff; - case 'magenta': return 0xff00ffff; - case 'maroon': return 0x800000ff; - case 'mediumaquamarine': return 0x66cdaaff; - case 'mediumblue': return 0x0000cdff; - case 'mediumorchid': return 0xba55d3ff; - case 'mediumpurple': return 0x9370dbff; - case 'mediumseagreen': return 0x3cb371ff; - case 'mediumslateblue': return 0x7b68eeff; - case 'mediumspringgreen': return 0x00fa9aff; - case 'mediumturquoise': return 0x48d1ccff; - case 'mediumvioletred': return 0xc71585ff; - case 'midnightblue': return 0x191970ff; - case 'mintcream': return 0xf5fffaff; - case 'mistyrose': return 0xffe4e1ff; - case 'moccasin': return 0xffe4b5ff; - case 'navajowhite': return 0xffdeadff; - case 'navy': return 0x000080ff; - case 'oldlace': return 0xfdf5e6ff; - case 'olive': return 0x808000ff; - case 'olivedrab': return 0x6b8e23ff; - case 'orange': return 0xffa500ff; - case 'orangered': return 0xff4500ff; - case 'orchid': return 0xda70d6ff; - case 'palegoldenrod': return 0xeee8aaff; - case 'palegreen': return 0x98fb98ff; - case 'paleturquoise': return 0xafeeeeff; - case 'palevioletred': return 0xdb7093ff; - case 'papayawhip': return 0xffefd5ff; - case 'peachpuff': return 0xffdab9ff; - case 'peru': return 0xcd853fff; - case 'pink': return 0xffc0cbff; - case 'plum': return 0xdda0ddff; - case 'powderblue': return 0xb0e0e6ff; - case 'purple': return 0x800080ff; - case 'rebeccapurple': return 0x663399ff; - case 'red': return 0xff0000ff; - case 'rosybrown': return 0xbc8f8fff; - case 'royalblue': return 0x4169e1ff; - case 'saddlebrown': return 0x8b4513ff; - case 'salmon': return 0xfa8072ff; - case 'sandybrown': return 0xf4a460ff; - case 'seagreen': return 0x2e8b57ff; - case 'seashell': return 0xfff5eeff; - case 'sienna': return 0xa0522dff; - case 'silver': return 0xc0c0c0ff; - case 'skyblue': return 0x87ceebff; - case 'slateblue': return 0x6a5acdff; - case 'slategray': return 0x708090ff; - case 'slategrey': return 0x708090ff; - case 'snow': return 0xfffafaff; - case 'springgreen': return 0x00ff7fff; - case 'steelblue': return 0x4682b4ff; - case 'tan': return 0xd2b48cff; - case 'teal': return 0x008080ff; - case 'thistle': return 0xd8bfd8ff; - case 'tomato': return 0xff6347ff; - case 'turquoise': return 0x40e0d0ff; - case 'violet': return 0xee82eeff; - case 'wheat': return 0xf5deb3ff; - case 'white': return 0xffffffff; - case 'whitesmoke': return 0xf5f5f5ff; - case 'yellow': return 0xffff00ff; - case 'yellowgreen': return 0x9acd32ff; - } - return null; -} - -module.exports = normalizeColor; diff --git a/packages/normalize-color/index.js.flow b/packages/normalize-color/index.js.flow deleted file mode 100644 index 4d24656d835e..000000000000 --- a/packages/normalize-color/index.js.flow +++ /dev/null @@ -1,10 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - */ - -declare module.exports: (color: ?(string | number)) => null | number; diff --git a/packages/normalize-color/package.json b/packages/normalize-color/package.json deleted file mode 100644 index 27fe68afd5cb..000000000000 --- a/packages/normalize-color/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "@react-native/normalize-color", - "version": "2.1.0", - "description": "Color normalization for React Native.", - "repository": { - "type": "git", - "url": "git@github.com:facebook/react-native.git", - "directory": "packages/normalize-color" - }, - "license": "MIT" -} diff --git a/packages/polyfills/.npmignore b/packages/polyfills/.npmignore deleted file mode 100644 index 9b166b095d3f..000000000000 --- a/packages/polyfills/.npmignore +++ /dev/null @@ -1,3 +0,0 @@ -**/__mocks__/** -**/__tests__/** -BUCK diff --git a/packages/polyfills/BUCK b/packages/polyfills/BUCK deleted file mode 100644 index 88ffc9513eee..000000000000 --- a/packages/polyfills/BUCK +++ /dev/null @@ -1,34 +0,0 @@ -load("@fbsource//tools/build_defs/third_party:yarn_defs.bzl", "yarn_workspace") -load("@fbsource//xplat/js:JS_DEFS.bzl", "relative_path_to_js_root", "rn_library") - -yarn_workspace( - name = "yarn-workspace", - srcs = glob( - [ - "**/*.js", - "**/*.json", - ], - exclude = [ - "**/__fixtures__/**", - "**/__flowtests__/**", - "**/__mocks__/**", - "**/__tests__/**", - "**/node_modules/**", - "**/node_modules/.bin/**", - ], - ), - visibility = ["PUBLIC"], -) - -rn_library( - name = "polyfills", - base_path = relative_path_to_js_root() + "node_modules/@react-native/polyfills/", - is_polyfill = True, - labels = [ - "pfh:ReactNative_CommonInfrastructurePlaceholder", - ], - node_modules_check_enabled = False, - skip_processors = True, # Don't anticipate routes or fbicon here - visibility = ["PUBLIC"], - deps = [], -) diff --git a/packages/polyfills/Object.es8.js b/packages/polyfills/Object.es8.js deleted file mode 100644 index 4925f6e2dee0..000000000000 --- a/packages/polyfills/Object.es8.js +++ /dev/null @@ -1,58 +0,0 @@ -/** - * 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 - * @polyfill - * @nolint - */ - -(function () { - 'use strict'; - - const hasOwnProperty = Object.prototype.hasOwnProperty; - - /** - * Returns an array of the given object's own enumerable entries. - * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries - */ - if (typeof Object.entries !== 'function') { - Object.entries = function (object) { - // `null` and `undefined` values are not allowed. - if (object == null) { - throw new TypeError('Object.entries called on non-object'); - } - - const entries = []; - for (const key in object) { - if (hasOwnProperty.call(object, key)) { - entries.push([key, object[key]]); - } - } - return entries; - }; - } - - /** - * Returns an array of the given object's own enumerable entries. - * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values - */ - if (typeof Object.values !== 'function') { - Object.values = function (object) { - // `null` and `undefined` values are not allowed. - if (object == null) { - throw new TypeError('Object.values called on non-object'); - } - - const values = []; - for (const key in object) { - if (hasOwnProperty.call(object, key)) { - values.push(object[key]); - } - } - return values; - }; - } -})(); diff --git a/packages/polyfills/__tests__/Object.es8-test.js b/packages/polyfills/__tests__/Object.es8-test.js deleted file mode 100644 index c53512f17561..000000000000 --- a/packages/polyfills/__tests__/Object.es8-test.js +++ /dev/null @@ -1,140 +0,0 @@ -/** - * 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 - * @oncall jsinfra - */ - -'use strict'; - -describe('Object (ES8)', () => { - beforeEach(() => { - delete Object.entries; - delete Object.values; - jest.resetModules(); - require('../Object.es8'); - }); - - describe('Object.entries', () => { - it('should have a length of 1', () => { - expect(Object.entries.length).toBe(1); - }); - - it('should check for type', () => { - expect(Object.entries.bind(null, null)).toThrow( - TypeError('Object.entries called on non-object'), - ); - expect(Object.entries.bind(null, undefined)).toThrow( - TypeError('Object.entries called on non-object'), - ); - expect(Object.entries.bind(null, [])).not.toThrow(); - expect(Object.entries.bind(null, () => {})).not.toThrow(); - expect(Object.entries.bind(null, {})).not.toThrow(); - expect(Object.entries.bind(null, 'abc')).not.toThrow(); - }); - - it('should return enumerable entries', () => { - const foo = Object.defineProperties( - {}, - { - x: {value: 10, enumerable: true}, - y: {value: 20}, - }, - ); - - expect(Object.entries(foo)).toEqual([['x', 10]]); - - const bar = {x: 10, y: 20}; - expect(Object.entries(bar)).toEqual([ - ['x', 10], - ['y', 20], - ]); - }); - - it('should work with proto-less objects', () => { - const foo = Object.create(null, { - x: {value: 10, enumerable: true}, - y: {value: 20}, - }); - - expect(Object.entries(foo)).toEqual([['x', 10]]); - }); - - it('should return only own entries', () => { - const foo = Object.create( - {z: 30}, - { - x: {value: 10, enumerable: true}, - y: {value: 20}, - }, - ); - - expect(Object.entries(foo)).toEqual([['x', 10]]); - }); - - it('should convert to object primitive string', () => { - expect(Object.entries('ab')).toEqual([ - ['0', 'a'], - ['1', 'b'], - ]); - }); - }); - - describe('Object.values', () => { - it('should have a length of 1', () => { - expect(Object.values.length).toBe(1); - }); - - it('should check for type', () => { - expect(Object.values.bind(null, null)).toThrow( - TypeError('Object.values called on non-object'), - ); - expect(Object.values.bind(null, [])).not.toThrow(); - expect(Object.values.bind(null, () => {})).not.toThrow(); - expect(Object.values.bind(null, {})).not.toThrow(); - }); - - it('should return enumerable values', () => { - const foo = Object.defineProperties( - {}, - { - x: {value: 10, enumerable: true}, - y: {value: 20}, - }, - ); - - expect(Object.values(foo)).toEqual([10]); - - const bar = {x: 10, y: 20}; - expect(Object.values(bar)).toEqual([10, 20]); - }); - - it('should work with proto-less objects', () => { - const foo = Object.create(null, { - x: {value: 10, enumerable: true}, - y: {value: 20}, - }); - - expect(Object.values(foo)).toEqual([10]); - }); - - it('should return only own values', () => { - const foo = Object.create( - {z: 30}, - { - x: {value: 10, enumerable: true}, - y: {value: 20}, - }, - ); - - expect(Object.values(foo)).toEqual([10]); - }); - - it('should convert to object primitive string', () => { - expect(Object.values('ab')).toEqual(['a', 'b']); - }); - }); -}); diff --git a/packages/polyfills/console.js b/packages/polyfills/console.js deleted file mode 100644 index e843f4f74caa..000000000000 --- a/packages/polyfills/console.js +++ /dev/null @@ -1,631 +0,0 @@ -/** - * 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. - * - * @polyfill - * @nolint - * @format - */ - -/* eslint-disable no-shadow, eqeqeq, curly, no-unused-vars, no-void, no-control-regex */ - -/** - * This pipes all of our console logging functions to native logging so that - * JavaScript errors in required modules show up in Xcode via NSLog. - */ -const inspect = (function () { - // Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - // - // https://github.com/joyent/node/blob/master/lib/util.js - - function inspect(obj, opts) { - var ctx = { - seen: [], - formatValueCalls: 0, - stylize: stylizeNoColor, - }; - return formatValue(ctx, obj, opts.depth); - } - - function stylizeNoColor(str, styleType) { - return str; - } - - function arrayToHash(array) { - var hash = {}; - - array.forEach(function (val, idx) { - hash[val] = true; - }); - - return hash; - } - - function formatValue(ctx, value, recurseTimes) { - ctx.formatValueCalls++; - if (ctx.formatValueCalls > 200) { - return `[TOO BIG formatValueCalls ${ctx.formatValueCalls} exceeded limit of 200]`; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if ( - isError(value) && - (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0) - ) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', - array = false, - braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function (key) { - return formatProperty( - ctx, - value, - recurseTimes, - visibleKeys, - key, - array, - ); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); - } - - function formatPrimitive(ctx, value) { - if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = - "'" + - JSON.stringify(value) - .replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + - "'"; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) return ctx.stylize('null', 'null'); - } - - function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; - } - - function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push( - formatProperty( - ctx, - value, - recurseTimes, - visibleKeys, - String(i), - true, - ), - ); - } else { - output.push(''); - } - } - keys.forEach(function (key) { - if (!key.match(/^\d+$/)) { - output.push( - formatProperty(ctx, value, recurseTimes, visibleKeys, key, true), - ); - } - }); - return output; - } - - function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || {value: value[key]}; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str - .split('\n') - .map(function (line) { - return ' ' + line; - }) - .join('\n') - .substr(2); - } else { - str = - '\n' + - str - .split('\n') - .map(function (line) { - return ' ' + line; - }) - .join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; - } - - function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function (prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return ( - braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1] - ); - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; - } - - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - function isArray(ar) { - return Array.isArray(ar); - } - - function isBoolean(arg) { - return typeof arg === 'boolean'; - } - - function isNull(arg) { - return arg === null; - } - - function isNullOrUndefined(arg) { - return arg == null; - } - - function isNumber(arg) { - return typeof arg === 'number'; - } - - function isString(arg) { - return typeof arg === 'string'; - } - - function isSymbol(arg) { - return typeof arg === 'symbol'; - } - - function isUndefined(arg) { - return arg === void 0; - } - - function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; - } - - function isObject(arg) { - return typeof arg === 'object' && arg !== null; - } - - function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; - } - - function isError(e) { - return ( - isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error) - ); - } - - function isFunction(arg) { - return typeof arg === 'function'; - } - - function objectToString(o) { - return Object.prototype.toString.call(o); - } - - function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); - } - - return inspect; -})(); - -const OBJECT_COLUMN_NAME = '(index)'; -const LOG_LEVELS = { - trace: 0, - info: 1, - warn: 2, - error: 3, -}; -const INSPECTOR_LEVELS = []; -INSPECTOR_LEVELS[LOG_LEVELS.trace] = 'debug'; -INSPECTOR_LEVELS[LOG_LEVELS.info] = 'log'; -INSPECTOR_LEVELS[LOG_LEVELS.warn] = 'warning'; -INSPECTOR_LEVELS[LOG_LEVELS.error] = 'error'; - -// Strip the inner function in getNativeLogFunction(), if in dev also -// strip method printing to originalConsole. -const INSPECTOR_FRAMES_TO_SKIP = __DEV__ ? 2 : 1; - -function getNativeLogFunction(level) { - return function () { - let str; - if (arguments.length === 1 && typeof arguments[0] === 'string') { - str = arguments[0]; - } else { - str = Array.prototype.map - .call(arguments, function (arg) { - return inspect(arg, {depth: 10}); - }) - .join(', '); - } - - // TRICKY - // If more than one argument is provided, the code above collapses them all - // into a single formatted string. This transform wraps string arguments in - // single quotes (e.g. "foo" -> "'foo'") which then breaks the "Warning:" - // check below. So it's important that we look at the first argument, rather - // than the formatted argument string. - const firstArg = arguments[0]; - - let logLevel = level; - if ( - typeof firstArg === 'string' && - firstArg.slice(0, 9) === 'Warning: ' && - logLevel >= LOG_LEVELS.error - ) { - // React warnings use console.error so that a stack trace is shown, - // but we don't (currently) want these to show a redbox - // (Note: Logic duplicated in ExceptionsManager.js.) - logLevel = LOG_LEVELS.warn; - } - if (global.__inspectorLog) { - global.__inspectorLog( - INSPECTOR_LEVELS[logLevel], - str, - [].slice.call(arguments), - INSPECTOR_FRAMES_TO_SKIP, - ); - } - if (groupStack.length) { - str = groupFormat('', str); - } - global.nativeLoggingHook(str, logLevel); - }; -} - -function repeat(element, n) { - return Array.apply(null, Array(n)).map(function () { - return element; - }); -} - -function consoleTablePolyfill(rows) { - // convert object -> array - if (!Array.isArray(rows)) { - var data = rows; - rows = []; - for (var key in data) { - if (data.hasOwnProperty(key)) { - var row = data[key]; - row[OBJECT_COLUMN_NAME] = key; - rows.push(row); - } - } - } - if (rows.length === 0) { - global.nativeLoggingHook('', LOG_LEVELS.info); - return; - } - - var columns = Object.keys(rows[0]).sort(); - var stringRows = []; - var columnWidths = []; - - // Convert each cell to a string. Also - // figure out max cell width for each column - columns.forEach(function (k, i) { - columnWidths[i] = k.length; - for (var j = 0; j < rows.length; j++) { - var cellStr = (rows[j][k] || '?').toString(); - stringRows[j] = stringRows[j] || []; - stringRows[j][i] = cellStr; - columnWidths[i] = Math.max(columnWidths[i], cellStr.length); - } - }); - - // Join all elements in the row into a single string with | separators - // (appends extra spaces to each cell to make separators | aligned) - function joinRow(row, space) { - var cells = row.map(function (cell, i) { - var extraSpaces = repeat(' ', columnWidths[i] - cell.length).join(''); - return cell + extraSpaces; - }); - space = space || ' '; - return cells.join(space + '|' + space); - } - - var separators = columnWidths.map(function (columnWidth) { - return repeat('-', columnWidth).join(''); - }); - var separatorRow = joinRow(separators, '-'); - var header = joinRow(columns); - var table = [header, separatorRow]; - - for (var i = 0; i < rows.length; i++) { - table.push(joinRow(stringRows[i])); - } - - // Notice extra empty line at the beginning. - // Native logging hook adds "RCTLog >" at the front of every - // logged string, which would shift the header and screw up - // the table - global.nativeLoggingHook('\n' + table.join('\n'), LOG_LEVELS.info); -} - -const GROUP_PAD = '\u2502'; // Box light vertical -const GROUP_OPEN = '\u2510'; // Box light down+left -const GROUP_CLOSE = '\u2518'; // Box light up+left - -const groupStack = []; - -function groupFormat(prefix, msg) { - // Insert group formatting before the console message - return groupStack.join('') + prefix + ' ' + (msg || ''); -} - -function consoleGroupPolyfill(label) { - global.nativeLoggingHook(groupFormat(GROUP_OPEN, label), LOG_LEVELS.info); - groupStack.push(GROUP_PAD); -} - -function consoleGroupCollapsedPolyfill(label) { - global.nativeLoggingHook(groupFormat(GROUP_CLOSE, label), LOG_LEVELS.info); - groupStack.push(GROUP_PAD); -} - -function consoleGroupEndPolyfill() { - groupStack.pop(); - global.nativeLoggingHook(groupFormat(GROUP_CLOSE), LOG_LEVELS.info); -} - -function consoleAssertPolyfill(expression, label) { - if (!expression) { - global.nativeLoggingHook('Assertion failed: ' + label, LOG_LEVELS.error); - } -} - -if (global.nativeLoggingHook) { - const originalConsole = global.console; - // Preserve the original `console` as `originalConsole` - if (__DEV__ && originalConsole) { - const descriptor = Object.getOwnPropertyDescriptor(global, 'console'); - if (descriptor) { - Object.defineProperty(global, 'originalConsole', descriptor); - } - } - - global.console = { - error: getNativeLogFunction(LOG_LEVELS.error), - info: getNativeLogFunction(LOG_LEVELS.info), - log: getNativeLogFunction(LOG_LEVELS.info), - warn: getNativeLogFunction(LOG_LEVELS.warn), - trace: getNativeLogFunction(LOG_LEVELS.trace), - debug: getNativeLogFunction(LOG_LEVELS.trace), - table: consoleTablePolyfill, - group: consoleGroupPolyfill, - groupEnd: consoleGroupEndPolyfill, - groupCollapsed: consoleGroupCollapsedPolyfill, - assert: consoleAssertPolyfill, - }; - - Object.defineProperty(console, '_isPolyfilled', { - value: true, - enumerable: false, - }); - - // If available, also call the original `console` method since that is - // sometimes useful. Ex: on OS X, this will let you see rich output in - // the Safari Web Inspector console. - if (__DEV__ && originalConsole) { - Object.keys(console).forEach(methodName => { - const reactNativeMethod = console[methodName]; - if (originalConsole[methodName]) { - console[methodName] = function () { - originalConsole[methodName](...arguments); - reactNativeMethod.apply(console, arguments); - }; - } - }); - - // The following methods are not supported by this polyfill but - // we still should pass them to original console if they are - // supported by it. - ['clear', 'dir', 'dirxml', 'profile', 'profileEnd'].forEach(methodName => { - if (typeof originalConsole[methodName] === 'function') { - console[methodName] = function () { - originalConsole[methodName](...arguments); - }; - } - }); - } -} else if (!global.console) { - function stub() {} - const log = global.print || stub; - - global.console = { - debug: log, - error: log, - info: log, - log: log, - trace: log, - warn: log, - assert(expression, label) { - if (!expression) { - log('Assertion failed: ' + label); - } - }, - clear: stub, - dir: stub, - dirxml: stub, - group: stub, - groupCollapsed: stub, - groupEnd: stub, - profile: stub, - profileEnd: stub, - table: stub, - }; - - Object.defineProperty(console, '_isPolyfilled', { - value: true, - enumerable: false, - }); -} diff --git a/packages/polyfills/error-guard.js b/packages/polyfills/error-guard.js deleted file mode 100644 index 389b5a20f814..000000000000 --- a/packages/polyfills/error-guard.js +++ /dev/null @@ -1,123 +0,0 @@ -/** - * 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 - * @flow strict - * @polyfill - */ - -let _inGuard = 0; - -type ErrorHandler = (error: mixed, isFatal: boolean) => void; -type Fn = (...Args) => Return; - -/** - * This is the error handler that is called when we encounter an exception - * when loading a module. This will report any errors encountered before - * ExceptionsManager is configured. - */ -let _globalHandler: ErrorHandler = function onError( - e: mixed, - isFatal: boolean, -) { - throw e; -}; - -/** - * The particular require runtime that we are using looks for a global - * `ErrorUtils` object and if it exists, then it requires modules with the - * error handler specified via ErrorUtils.setGlobalHandler by calling the - * require function with applyWithGuard. Since the require module is loaded - * before any of the modules, this ErrorUtils must be defined (and the handler - * set) globally before requiring anything. - */ -const ErrorUtils = { - setGlobalHandler(fun: ErrorHandler): void { - _globalHandler = fun; - }, - getGlobalHandler(): ErrorHandler { - return _globalHandler; - }, - reportError(error: mixed): void { - _globalHandler && _globalHandler(error, false); - }, - reportFatalError(error: mixed): void { - // NOTE: This has an untyped call site in Metro. - _globalHandler && _globalHandler(error, true); - }, - applyWithGuard, TOut>( - fun: Fn, - context?: ?mixed, - args?: ?TArgs, - // Unused, but some code synced from www sets it to null. - unused_onError?: null, - // Some callers pass a name here, which we ignore. - unused_name?: ?string, - ): ?TOut { - try { - _inGuard++; - /* $FlowFixMe[incompatible-call] : TODO T48204745 (1) apply(context, - * null) is fine. (2) array -> rest array should work */ - /* $FlowFixMe[incompatible-type] : TODO T48204745 (1) apply(context, - * null) is fine. (2) array -> rest array should work */ - return fun.apply(context, args); - } catch (e) { - ErrorUtils.reportError(e); - } finally { - _inGuard--; - } - return null; - }, - applyWithGuardIfNeeded, TOut>( - fun: Fn, - context?: ?mixed, - args?: ?TArgs, - ): ?TOut { - if (ErrorUtils.inGuard()) { - /* $FlowFixMe[incompatible-call] : TODO T48204745 (1) apply(context, - * null) is fine. (2) array -> rest array should work */ - /* $FlowFixMe[incompatible-type] : TODO T48204745 (1) apply(context, - * null) is fine. (2) array -> rest array should work */ - return fun.apply(context, args); - } else { - ErrorUtils.applyWithGuard(fun, context, args); - } - return null; - }, - inGuard(): boolean { - return !!_inGuard; - }, - guard, TOut>( - fun: Fn, - name?: ?string, - context?: ?mixed, - ): ?(...TArgs) => ?TOut { - // TODO: (moti) T48204753 Make sure this warning is never hit and remove it - types - // should be sufficient. - if (typeof fun !== 'function') { - console.warn('A function must be passed to ErrorUtils.guard, got ', fun); - return null; - } - const guardName = name ?? fun.name ?? ''; - /* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by - * Flow's LTI update could not be added via codemod */ - function guarded(...args: TArgs): ?TOut { - return ErrorUtils.applyWithGuard( - fun, - context ?? this, - args, - null, - guardName, - ); - } - - return guarded; - }, -}; - -global.ErrorUtils = ErrorUtils; - -export type ErrorUtilsT = typeof ErrorUtils; diff --git a/packages/polyfills/index.js b/packages/polyfills/index.js deleted file mode 100644 index 5979051ac301..000000000000 --- a/packages/polyfills/index.js +++ /dev/null @@ -1,16 +0,0 @@ -/** - * 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 - */ - -'use strict'; - -module.exports = () => [ - require.resolve('./console.js'), - require.resolve('./error-guard.js'), - require.resolve('./Object.es8.js'), -]; diff --git a/packages/polyfills/package.json b/packages/polyfills/package.json deleted file mode 100644 index 58a2b3a70494..000000000000 --- a/packages/polyfills/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "@react-native/polyfills", - "version": "2.0.0", - "description": "Polyfills for React Native.", - "repository": { - "type": "git", - "url": "git@github.com:facebook/react-native.git", - "directory": "packages/polyfills" - }, - "license": "MIT" -} diff --git a/packages/react-native-bots/.babelrc b/packages/react-native-bots/.babelrc deleted file mode 100644 index 0967ef424bce..000000000000 --- a/packages/react-native-bots/.babelrc +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/packages/react-native-bots/README.md b/packages/react-native-bots/README.md deleted file mode 100644 index 95857e343bbd..000000000000 --- a/packages/react-native-bots/README.md +++ /dev/null @@ -1,25 +0,0 @@ -## Danger - -[Danger](http://danger.systems/js/) is a JavaScript runtime which helps you provide continuous feedback inside GitHub. -It's used inside Github Actions to analyze the contents of a GitHub pull request. - -If you want to test changes to Danger, I'd recommend checking out an existing PR and then running the `danger pr` command. -You'll need a GitHub Public Access Token (PAT). It will look like `ghp_`. - -So, for example: - -``` -DANGER_GITHUB_API_TOKEN=ghp_ yarn danger pr https://github.com/facebook/react-native/pull/1234 -``` - -## Code Analysis Bot - -The code analysis bot provides lint and other results as inline reviews on GitHub. It runs as part of the Circle CI analysis workflow. - -If you want to test changes to the Code Analysis Bot, I'd recommend checking out an existing PR and then running the `analyze pr` command. -You'll need a GitHub token. You can re-use this one: `312d354b5c36f082cfe9` `07973d757026bdd9f196` (just remove the space). -So, for example: - -``` -GITHUB_TOKEN=[ENV_ABOVE] GITHUB_PR_NUMBER=1234 yarn lint-ci -``` diff --git a/packages/react-native-bots/code-analysis-bot.js b/packages/react-native-bots/code-analysis-bot.js deleted file mode 100644 index 2b95ae2dd05f..000000000000 --- a/packages/react-native-bots/code-analysis-bot.js +++ /dev/null @@ -1,350 +0,0 @@ -/** - * 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 - */ - -'use strict'; - -if (!process.env.GITHUB_OWNER) { - console.error('Missing GITHUB_OWNER. Example: facebook'); - process.exit(1); -} -if (!process.env.GITHUB_REPO) { - console.error('Missing GITHUB_REPO. Example: react-native'); - process.exit(1); -} - -const path = require('path'); - -function push(arr, key, value) { - if (!arr[key]) { - arr[key] = []; - } - arr[key].push(value); -} - -const converterSummary = { - eslint: - '`eslint` found some issues. Run `yarn lint --fix` to automatically fix problems.', - flow: '`flow` found some issues. Run `yarn flow check` to analyze your code and address any errors.', - shellcheck: - '`shellcheck` found some issues. Run `yarn shellcheck` to analyze shell scripts.', - 'google-java-format': - '`google-java-format` found some issues. See https://github.com/google/google-java-format', -}; - -/** - * There is unfortunately no standard format to report an error, so we have - * to write a specific converter for each tool we want to support. - * - * Those functions take a json object as input and fill the output with the - * following format: - * - * { [ path: string ]: Array< { message: string, line: number }> } - * - * This is an object where the keys are the path of the files and values - * is an array of objects of the shape message and line. - */ -const converters = { - raw: function (output, input) { - for (let key in input) { - input[key].forEach(function (message) { - push(output, key, message); - }); - } - }, - - 'google-java-format': function (output, input) { - if (!input) { - return; - } - - input.forEach(function (change) { - push(output, change.file, { - message: `\`google-java-format\` suggested changes: -\`\`\`diff -${change.description} -\`\`\` -`, - line: change.line, - converter: 'google-java-format', - }); - }); - }, - - flow: function (output, input) { - if (!input || !input.errors) { - return; - } - - input.errors.forEach(function (error) { - push(output, error.message[0].path, { - message: error.message.map(message => message.descr).join(' '), - line: error.message[0].line, - converter: 'flow', - }); - }); - }, - - eslint: function (output, input) { - if (!input) { - return; - } - - input.forEach(function (file) { - file.messages.forEach(function (message) { - push(output, file.filePath, { - message: message.ruleId + ': ' + message.message, - line: message.line, - converter: 'eslint', - }); - }); - }); - }, - - shellcheck: function (output, input) { - if (!input) { - return; - } - - input.forEach(function (report) { - push(output, report.file, { - message: - '**[SC' + - report.code + - '](https://github.com/koalaman/shellcheck/wiki/SC' + - report.code + - '):** (' + - report.level + - ') ' + - report.message, - line: report.line, - endLine: report.endLine, - column: report.column, - endColumn: report.endColumn, - converter: 'shellcheck', - }); - }); - }, -}; - -/** - * Sadly we can't just give the line number to github, we have to give the - * line number relative to the patch file which is super annoying. This - * little function builds a map of line number in the file to line number - * in the patch file - */ -function getLineMapFromPatch(patchString) { - let diffLineIndex = 0; - let fileLineIndex = 0; - let lineMap = {}; - - patchString.split('\n').forEach(line => { - if (line.match(/^@@/)) { - fileLineIndex = line.match(/\+([0-9]+)/)[1] - 1; - return; - } - - diffLineIndex++; - if (line[0] !== '-') { - fileLineIndex++; - if (line[0] === '+') { - lineMap[fileLineIndex] = diffLineIndex; - } - } - }); - - return lineMap; -} - -async function sendReview( - octokit, - owner, - repo, - pull_number, - commit_id, - body, - comments, -) { - if (process.env.GITHUB_TOKEN) { - if (comments.length === 0) { - // Do not leave an empty review. - return; - } else if (comments.length > 5) { - // Avoid noisy reviews and rely solely on the body of the review. - comments = []; - } - - const event = 'REQUEST_CHANGES'; - - const opts = { - owner, - repo, - pull_number, - commit_id, - body, - event, - comments, - }; - - await octokit.pulls.createReview(opts); - } else { - if (comments.length === 0) { - console.log('No issues found.'); - return; - } - - if (process.env.CIRCLE_CI) { - console.error( - 'Code analysis found issues, but the review cannot be posted to GitHub without an access token.', - ); - process.exit(1); - } - - let results = body + '\n'; - comments.forEach(comment => { - results += - comment.path + ':' + comment.position + ': ' + comment.body + '\n'; - }); - console.log(results); - } -} - -async function main(messages, owner, repo, pull_number) { - // No message, we don't need to do anything :) - if (Object.keys(messages).length === 0) { - return; - } - - if (!process.env.GITHUB_TOKEN) { - console.log( - 'Missing GITHUB_TOKEN. Example: 5fd88b964fa214c4be2b144dc5af5d486a2f8c1e. Review feedback with code analysis results will not be provided on GitHub without a valid token.', - ); - } - - // https://octokit.github.io/rest.js/ - const {Octokit} = require('@octokit/rest'); - const octokit = new Octokit({ - auth: process.env.GITHUB_TOKEN, - userAgent: 'react-native-code-analysis-bot', - }); - - const opts = { - owner, - repo, - pull_number, - }; - - const {data: pull} = await octokit.pulls.get(opts); - const {data: files} = await octokit.pulls.listFiles(opts); - - const comments = []; - const convertersUsed = []; - - files - .filter(file => messages[file.filename]) - .forEach(file => { - // github api sometimes does not return a patch on large commits - if (!file.patch) { - return; - } - const lineMap = getLineMapFromPatch(file.patch); - messages[file.filename].forEach(message => { - if (lineMap[message.line]) { - const comment = { - path: file.filename, - position: lineMap[message.line], - body: message.message, - }; - convertersUsed.push(message.converter); - comments.push(comment); - } - }); // forEach - }); // filter - - let body = '**Code analysis results:**\n\n'; - const uniqueconvertersUsed = [...new Set(convertersUsed)]; - uniqueconvertersUsed.forEach(converter => { - body += '* ' + converterSummary[converter] + '\n'; - }); - - await sendReview( - octokit, - owner, - repo, - pull_number, - pull.head.sha, - body, - comments, - ); -} - -let content = ''; -process.stdin.resume(); -process.stdin.on('data', function (buf) { - content += buf.toString(); -}); -process.stdin.on('end', function () { - let messages = {}; - - // Since we send a few http requests to setup the process, we don't want - // to run this file one time per code analysis tool. Instead, we write all - // the results in the same stdin stream. - // The format of this stream is - // - // name-of-the-converter - // {"json":"payload"} - // name-of-the-other-converter - // {"other": ["json", "payload"]} - // - // In order to generate such stream, here is a sample bash command: - // - // cat <(echo eslint; npm run lint --silent -- --format=json; echo flow; flow --json) | node code-analysis-bot.js - - const lines = content.trim().split('\n'); - for (let i = 0; i < Math.ceil(lines.length / 2); ++i) { - const converter = converters[lines[i * 2]]; - if (!converter) { - throw new Error('Unknown converter ' + lines[i * 2]); - } - let json; - try { - json = JSON.parse(lines[i * 2 + 1]); - } catch (e) {} - - converter(messages, json); - } - - // The paths are returned in absolute from code analysis tools but github works - // on paths relative from the root of the project. Doing the normalization here. - const pwd = path.resolve('.'); - for (let absolutePath in messages) { - const relativePath = path.relative(pwd, absolutePath); - if (relativePath === absolutePath) { - continue; - } - messages[relativePath] = messages[absolutePath]; - delete messages[absolutePath]; - } - - const owner = process.env.GITHUB_OWNER; - const repo = process.env.GITHUB_REPO; - - if (!process.env.GITHUB_PR_NUMBER) { - console.error( - 'Missing GITHUB_PR_NUMBER. Example: 4687. Review feedback with code analysis results cannot be provided on GitHub without a valid pull request number.', - ); - // for master branch, don't throw an error - process.exit(0); - } - - const number = process.env.GITHUB_PR_NUMBER; - - (async () => { - await main(messages, owner, repo, number); - })(); -}); diff --git a/packages/react-native-bots/dangerfile.js b/packages/react-native-bots/dangerfile.js deleted file mode 100644 index f5bc31129a6b..000000000000 --- a/packages/react-native-bots/dangerfile.js +++ /dev/null @@ -1,114 +0,0 @@ -/** - * 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 - */ - -'use strict'; - -const {danger, fail, /*message,*/ warn} = require('danger'); -const includes = require('lodash.includes'); -const eslint = require('@seadub/danger-plugin-eslint'); - -const isFromPhabricator = - danger.github.pr.body && - danger.github.pr.body.toLowerCase().includes('differential revision:'); - -// Provides advice if a summary section is missing, or body is too short -const includesSummary = - danger.github.pr.body && - danger.github.pr.body.toLowerCase().includes('## summary'); -if (!danger.github.pr.body || danger.github.pr.body.length < 50) { - fail(':grey_question: This pull request needs a description.'); -} else if (!includesSummary && !isFromPhabricator) { - // PRs from Phabricator always includes the Summary by default. - const title = ':clipboard: Missing Summary'; - const idea = - 'Can you add a Summary? ' + - 'To do so, add a "## Summary" section to your PR description. ' + - 'This is a good place to explain the motivation for making this change.'; - warn(`${title} - ${idea}`); -} - -// Warns if there are changes to package.json, and tags the team. -const packageChanged = includes(danger.git.modified_files, 'package.json'); -if (packageChanged) { - const title = ':lock: package.json'; - const idea = - 'Changes were made to package.json. ' + - 'This will require a manual import by a Facebook employee.'; - warn(`${title} - ${idea}`); -} - -// Provides advice if a test plan is missing. -const includesTestPlan = - danger.github.pr.body && - danger.github.pr.body.toLowerCase().includes('## test plan'); -if (!includesTestPlan && !isFromPhabricator) { - // PRs from Phabricator never exports the Test Plan so let's disable this check. - const title = ':clipboard: Missing Test Plan'; - const idea = - 'Can you add a Test Plan? ' + - 'To do so, add a "## Test Plan" section to your PR description. ' + - 'A Test Plan lets us know how these changes were tested.'; - warn(`${title} - ${idea}`); -} - -// Regex looks for given categories, types, a file/framework/component, and a message - broken into 4 capture groups -const changelogRegex = - /\[\s?(ANDROID|GENERAL|IOS|JS|JAVASCRIPT|INTERNAL)\s?\]\s?\[\s?(ADDED|CHANGED|DEPRECATED|REMOVED|FIXED|SECURITY)\s?\]\s*?-?\s*?(.*)/gi; -const internalChangelogRegex = /\[\s?(INTERNAL)\s?\].*/gi; -const includesChangelog = - danger.github.pr.body && - (danger.github.pr.body.toLowerCase().includes('## changelog') || - danger.github.pr.body.toLowerCase().includes('release notes') || - // PR exports from Phabricator have a `Changelog:` entry for the changelog. - danger.github.pr.body.toLowerCase().includes('changelog:')); -const correctlyFormattedChangelog = changelogRegex.test(danger.github.pr.body); -const containsInternalChangelog = internalChangelogRegex.test( - danger.github.pr.body, -); - -// Provides advice if a changelog is missing -const changelogInstructions = - 'A changelog entry has the following format: `[CATEGORY] [TYPE] - Message`.\n\n
CATEGORY may be:\n\n- General\n- iOS\n- Android\n- JavaScript\n- Internal (for changes that do not need to be called out in the release notes)\n\nTYPE may be:\n\n- Added, for new features.\n- Changed, for changes in existing functionality.\n- Deprecated, for soon-to-be removed features.\n- Removed, for now removed features.\n- Fixed, for any bug fixes.\n- Security, in case of vulnerabilities.\n\nMESSAGE may answer "what and why" on a feature level. Use this to briefly tell React Native users about notable changes.
'; -if (!includesChangelog) { - const title = ':clipboard: Missing Changelog'; - const idea = - 'Can you add a Changelog? ' + - 'To do so, add a "## Changelog" section to your PR description. ' + - changelogInstructions; - fail(`${title} - ${idea}`); -} else if (!correctlyFormattedChangelog && !containsInternalChangelog) { - const title = ':clipboard: Verify Changelog Format'; - const idea = changelogInstructions; - fail(`${title} - ${idea}`); -} - -// Warns if the PR is opened against stable, as commits need to be cherry picked and tagged by a release maintainer. -// Fails if the PR is opened against anything other than `main` or `-stable`. -const isMergeRefMain = danger.github.pr.base.ref === 'main'; -const isMergeRefStable = danger.github.pr.base.ref.endsWith('-stable'); -if (!isMergeRefMain && !isMergeRefStable) { - const title = ':exclamation: Base Branch'; - const idea = - 'The base branch for this PR is something other than `main` or a `-stable` branch. [Are you sure you want to target something other than the `main` branch?](https://reactnative.dev/docs/contributing#pull-requests)'; - fail(`${title} - ${idea}`); -} - -// If the PR is opened against stable should add `Pick Request` label -if (isMergeRefStable) { - danger.github.api.issues.addLabels({ - owner: danger.github.pr.base.repo.owner.login, - repo: danger.github.pr.base.repo.name, - issue_number: danger.github.pr.number, - labels: ['Pick Request'], - }); -} - -// Ensures that eslint is run from root folder and that it can find .eslintrc -process.chdir('../../'); -eslint.default(); diff --git a/packages/react-native-bots/datastore.js b/packages/react-native-bots/datastore.js deleted file mode 100644 index 962b49c09a21..000000000000 --- a/packages/react-native-bots/datastore.js +++ /dev/null @@ -1,178 +0,0 @@ -/** - * 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 - */ - -'use strict'; - -const {initializeApp} = require('firebase/app'); -const {getAuth, signInWithEmailAndPassword} = require('firebase/auth'); -const firestore = require('firebase/firestore'); - -/** - * Initializes store, and optionally authenticates current user. - * - * @param {string?} email - * @param {string?} password - * @returns {Promise} Reference to store instance - */ -async function initializeStore(email, password) { - const PROJECT_ID = 'react-native-1583841384889'; - const apiKey = [ - 'AIzaSyCm', - '5hN3nVNY', - 'tF9zkSHa', - 'oFpeVe3g', - 'LceuC0Q', - ].join(''); - const firebaseApp = initializeApp({ - apiKey, - authDomain: `${PROJECT_ID}.firebaseapp.com`, - databaseURL: `https://${PROJECT_ID}.firebaseio.com`, - projectId: PROJECT_ID, - storageBucket: `${PROJECT_ID}.appspot.com`, - messagingSenderId: '329254200967', - appId: '1:329254200967:web:c465681d024115bc303a22', - measurementId: 'G-ZKSZ7SCLHK', - }); - - if (email && password) { - await signInWithEmailAndPassword( - getAuth(firebaseApp), - email, - password, - ).catch(error => console.log(error)); - } - - return firestore.getFirestore(firebaseApp); -} - -/** - * Initializes 'binary-sizes' collection using the initial commit's data. - * - * @param {firebase.firestore.Firestore} db Reference to store instance - */ -function initializeBinarySizesCollection(db) { - const collectionRef = getBinarySizesCollection(db); - const docRef = firestore.doc( - collectionRef, - 'a15603d8f1ecdd673d80be318293cee53eb4475d', - ); - firestore.setDoc(docRef, { - 'android-hermes-arm64-v8a': 0, - 'android-hermes-armeabi-v7a': 0, - 'android-hermes-x86': 0, - 'android-hermes-x86_64': 0, - 'android-jsc-arm64-v8a': 0, - 'android-jsc-armeabi-v7a': 0, - 'android-jsc-x86': 0, - 'android-jsc-x86_64': 0, - 'ios-universal': 0, - timestamp: new Date('Thu Jan 29 17:10:49 2015 -0800'), - }); -} - -/** - * Returns 'binary-sizes' collection. - * - * @param {firebase.firestore.Firestore} db Reference to store instance - */ -function getBinarySizesCollection(db) { - const BINARY_SIZES_COLLECTION = 'binary-sizes'; - return firestore.collection(db, BINARY_SIZES_COLLECTION); -} - -/** - * Creates or updates the specified entry. - * - * @param {firebase.firestore.CollectionReference} collection - * @param {string} sha The Git SHA used to identify the entry - * @param {firebase.firestore.UpdateData} data The data to be inserted/updated - * @param {string} branch The Git branch where this data was computed for - * @returns {Promise} - */ -function createOrUpdateDocument(collectionRef, sha, data, branch) { - const stampedData = { - ...data, - timestamp: firestore.Timestamp.now(), - branch, - }; - const docRef = firestore.doc(collectionRef, sha); - return firestore.updateDoc(docRef, stampedData).catch(async error => { - if (error.code === 'not-found') { - await firestore - .setDoc(docRef, stampedData) - .catch(setError => console.log(setError)); - } else { - console.log(error); - } - }); -} - -/** - * Returns the latest document in collection. - * - * @param {firebase.firestore.CollectionReference} collection - * @param {string} branch The Git branch for the data - * @returns {Promise} - */ -async function getLatestDocument(collectionRef, branch) { - try { - const querySnapshot = await firestore.getDocs( - firestore.query( - collectionRef, - firestore.orderBy('timestamp', 'desc'), - firestore.where('branch', '==', branch), - firestore.limit(1), - ), - ); - if (querySnapshot.empty) { - return undefined; - } - - const doc = querySnapshot.docs[0]; - return { - ...doc.data(), - commit: doc.id, - }; - } catch (error) { - console.log(error); - return undefined; - } -} - -/** - * Terminates the supplied store. - * - * Documentation says that we don't need to call `terminate()` but the script - * will just hang around until the connection times out if we don't. - * - * @param {Promise} db - */ -async function terminateStore(db) { - await firestore.terminate(db); -} - -/** - * Example usage: - * - * const datastore = require('./datastore'); - * const store = datastore.initializeStore(); - * const binarySizes = datastore.getBinarySizesCollection(store); - * console.log(await getLatestDocument(binarySizes)); - * console.log(await createOrUpdateDocument(binarySizes, 'some-id', {data: 0})); - * terminateStore(store); - * - */ -module.exports = { - initializeStore, - initializeBinarySizesCollection, - getBinarySizesCollection, - createOrUpdateDocument, - getLatestDocument, - terminateStore, -}; diff --git a/packages/react-native-bots/make-comment.js b/packages/react-native-bots/make-comment.js deleted file mode 100644 index 5d117867ce0f..000000000000 --- a/packages/react-native-bots/make-comment.js +++ /dev/null @@ -1,139 +0,0 @@ -/** - * 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 - */ - -'use strict'; - -/** - * Updates the comment matching specified pattern. - * @param {import('@octokit/rest').Octokit} octokit Octokit instance - * @param {{ owner: string; repo: string; issue_number: string; }} issueParams - * @param {string} body Comment body - * @param {string} replacePattern Pattern for finding the comment to update - */ -async function updateComment(octokit, issueParams, body, replacePattern) { - if (!replacePattern) { - return false; - } - - const authenticatedUser = await octokit.users.getAuthenticated(); - if (authenticatedUser.status !== 200 || !authenticatedUser.data) { - console.warn(authenticatedUser); - return false; - } - - const comments = await octokit.issues.listComments(issueParams); - if (comments.status !== 200 || !comments.data) { - console.warn(comments); - return false; - } - - const authedUserId = authenticatedUser.data.id; - const pattern = new RegExp(replacePattern, 'g'); - const comment = comments.data.find( - // eslint-disable-next-line no-shadow - ({user, body}) => user.id === authedUserId && pattern.test(body), - ); - if (!comment) { - return false; - } - - octokit.issues.updateComment({ - ...issueParams, - comment_id: comment.id, - body, - }); - return true; -} - -/** - * Creates or updates a comment with specified pattern. - * @param {{ auth: string; owner: string; repo: string; issue_number: string; }} params - * @param {string} body Comment body - * @param {string} replacePattern Pattern for finding the comment to update - */ -async function createOrUpdateComment( - {auth, ...issueParams}, - body, - replacePattern, -) { - if (!body) { - return; - } - - const {Octokit} = require('@octokit/rest'); - const octokit = new Octokit({auth}); - - if (await updateComment(octokit, issueParams, body, replacePattern)) { - return; - } - - // We found no comments to replace, so we'll create a new one. - - octokit.issues.createComment({ - ...issueParams, - body, - }); -} - -/** - * Validates that required environment variables are set. - * @returns {boolean} `true` if everything is in order; `false` otherwise. - */ -function validateEnvironment() { - const { - GITHUB_TOKEN, - GITHUB_OWNER, - GITHUB_REPO, - GITHUB_PR_NUMBER, - GITHUB_REF, - } = process.env; - - // We need the following variables to post a comment on a PR - if ( - !GITHUB_TOKEN || - !GITHUB_OWNER || - !GITHUB_REPO || - !GITHUB_PR_NUMBER || - !GITHUB_REF - ) { - if (!GITHUB_TOKEN) { - console.error( - 'Missing GITHUB_TOKEN. Example: ghp_5fd88b964fa214c4be2b144dc5af5d486a2. PR feedback cannot be provided on GitHub without a valid token.', - ); - } - if (!GITHUB_OWNER) { - console.error('Missing GITHUB_OWNER. Example: facebook'); - } - if (!GITHUB_REPO) { - console.error('Missing GITHUB_REPO. Example: react-native'); - } - if (!GITHUB_PR_NUMBER) { - console.error( - 'Missing GITHUB_PR_NUMBER. Example: 4687. PR feedback cannot be provided on GitHub without a valid pull request number.', - ); - } - if (!GITHUB_REF) { - console.error("Missing GITHUB_REF. This should've been set by the CI."); - } - - return false; - } - console.log(' GITHUB_TOKEN=REDACTED'); - console.log(` GITHUB_OWNER=${GITHUB_OWNER}`); - console.log(` GITHUB_REPO=${GITHUB_REPO}`); - console.log(` GITHUB_PR_NUMBER=${GITHUB_PR_NUMBER}`); - console.log(` GITHUB_REF=${GITHUB_REF}`); - - return true; -} - -module.exports = { - createOrUpdateComment, - validateEnvironment, -}; diff --git a/packages/react-native-bots/package.json b/packages/react-native-bots/package.json deleted file mode 100644 index a4a010507228..000000000000 --- a/packages/react-native-bots/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "@react-native/bots", - "version": "0.0.0", - "private": true, - "devDependencies": { - "@seadub/danger-plugin-eslint": "^3.0.2", - "danger": "^11.0.2", - "eslint": "^8.19.0", - "lodash.includes": "^4.3.0", - "minimatch": "^3.0.4" - }, - "dependencies": { - "@octokit/rest": "^18.12.0", - "firebase": "^9.6.5" - } -} diff --git a/packages/react-native-bots/post-artifacts-link.js b/packages/react-native-bots/post-artifacts-link.js deleted file mode 100644 index 314f782b1a2b..000000000000 --- a/packages/react-native-bots/post-artifacts-link.js +++ /dev/null @@ -1,86 +0,0 @@ -/** - * 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 - */ - -'use strict'; - -const { - CIRCLE_BUILD_URL, - GITHUB_OWNER, - GITHUB_PR_NUMBER, - GITHUB_REPO, - GITHUB_SHA, - GITHUB_TOKEN, -} = process.env; - -const { - createOrUpdateComment, - validateEnvironment: validateEnvironmentForMakeComment, -} = require('./make-comment'); - -/** - * Creates or updates a comment with specified pattern. - * @param {{ auth: string; owner: string; repo: string; issue_number: string; }} params - * @param {string} buildURL link to circleCI build - * @param {string} commitSha github sha of PR - */ -function postArtifactLink(params, buildUrl, commitSha) { - // build url link is redirected by CircleCI so appending `/artifacts` doesn't work - const artifactLink = buildUrl; - const comment = [ - `PR build artifact${ - commitSha != null ? ` for ${commitSha}` : '' - } is ready.`, - `To use, download tarball from "Artifacts" tab in [this CircleCI job](${artifactLink}) then run \`yarn add \` in your React Native project.`, - ].join('\n'); - createOrUpdateComment(params, comment); -} - -/** - * Validates that required environment variables are set. - * @returns {boolean} `true` if everything is in order; `false` otherwise. - */ -function validateEnvironment() { - if ( - !validateEnvironmentForMakeComment() || - !CIRCLE_BUILD_URL || - !GITHUB_SHA - ) { - if (!GITHUB_SHA) { - console.error("Missing GITHUB_SHA. This should've been set by the CI."); - } - if (!CIRCLE_BUILD_URL) { - console.error( - "Missing CIRCLE_BUILD_URL. This should've been set by the CI.", - ); - } - return false; - } - - console.log(` GITHUB_SHA=${GITHUB_SHA}`); - console.log(` CIRCLE_BUILD_URL=${CIRCLE_BUILD_URL}`); - - return true; -} - -if (!validateEnvironment()) { - process.exit(1); -} - -try { - const params = { - auth: GITHUB_TOKEN, - owner: GITHUB_OWNER, - repo: GITHUB_REPO, - issue_number: GITHUB_PR_NUMBER, - }; - postArtifactLink(params, CIRCLE_BUILD_URL, GITHUB_SHA); -} catch (error) { - console.error(error); - process.exitCode = 1; -} diff --git a/packages/react-native-bots/report-bundle-size.js b/packages/react-native-bots/report-bundle-size.js deleted file mode 100644 index 35d1f468c423..000000000000 --- a/packages/react-native-bots/report-bundle-size.js +++ /dev/null @@ -1,258 +0,0 @@ -/** - * 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 - */ - -'use strict'; - -const { - GITHUB_TOKEN, - GITHUB_OWNER, - GITHUB_REPO, - GITHUB_PR_NUMBER, - GITHUB_REF, - GITHUB_SHA, -} = process.env; - -const fs = require('fs'); -const datastore = require('./datastore'); -const { - createOrUpdateComment, - validateEnvironment: validateEnvironmentForMakeComment, -} = require('./make-comment'); - -/** - * Generates and submits a comment. If this is run on the main or release branch, data is - * committed to the store instead. - * @param {{ - 'android-hermes-arm64-v8a'?: number; - 'android-hermes-armeabi-v7a'?: number; - 'android-hermes-x86'?: number; - 'android-hermes-x86_64'?: number; - 'android-jsc-arm64-v8a'?: number; - 'android-jsc-armeabi-v7a'?: number; - 'android-jsc-x86'?: number; - 'android-jsc-x86_64'?: number; - 'ios-universal'?: number; - }} stats - */ -async function reportSizeStats(stats, replacePattern) { - const {FIREBASE_APP_EMAIL, FIREBASE_APP_PASS} = process.env; - const store = await datastore.initializeStore( - FIREBASE_APP_EMAIL, - FIREBASE_APP_PASS, - ); - const collection = datastore.getBinarySizesCollection(store); - - if (!isPullRequest(GITHUB_REF)) { - // Ensure we only store numbers greater than zero. - const validatedStats = Object.keys(stats).reduce((validated, key) => { - const value = stats[key]; - if (typeof value !== 'number' || value <= 0) { - return validated; - } - - validated[key] = value; - return validated; - }, {}); - - if (Object.keys(validatedStats).length > 0) { - // Print out the new stats - const document = - (await datastore.getLatestDocument(collection, GITHUB_REF)) || {}; - const formattedStats = formatBundleStats(document, validatedStats); - console.log(formattedStats); - - await datastore.createOrUpdateDocument( - collection, - GITHUB_SHA, - validatedStats, - GITHUB_REF, - ); - } - } else { - const params = { - auth: GITHUB_TOKEN, - owner: GITHUB_OWNER, - repo: GITHUB_REPO, - issue_number: GITHUB_PR_NUMBER, - }; - - // For PRs, always compare vs main. - const document = - (await datastore.getLatestDocument(collection, 'main')) || {}; - const comment = formatBundleStats(document, stats); - createOrUpdateComment(params, comment, replacePattern); - } - - await datastore.terminateStore(store); -} - -/** - * Format the new bundle stats as compared to the latest stored entry. - * @param {firebase.firestore.DocumentData} document the latest entry to compare against - * @param {firebase.firestore.UpdateData} stats The stats to be formatted - * @returns {string} - */ -function formatBundleStats(document, stats) { - const diffFormatter = new Intl.NumberFormat('en', {signDisplay: 'always'}); - const sizeFormatter = new Intl.NumberFormat('en', {}); - - // | Platform | Engine | Arch | Size (bytes) | Diff | - // |:---------|:-------|:------------|-------------:|-----:| - // | android | hermes | arm64-v8a | 9437184 | ±0 | - // | android | hermes | armeabi-v7a | 9015296 | ±0 | - // | android | hermes | x86 | 9498624 | ±0 | - // | android | hermes | x86_64 | 9965568 | ±0 | - // | android | jsc | arm64-v8a | 9236480 | ±0 | - // | android | jsc | armeabi-v7a | 8814592 | ±0 | - // | android | jsc | x86 | 9297920 | ±0 | - // | android | jsc | x86_64 | 9764864 | ±0 | - // | android | jsc | x86_64 | 9764864 | ±0 | - // | ios | - | universal | 10715136 | ±0 | - const formatted = [ - '| Platform | Engine | Arch | Size (bytes) | Diff |', - '|:---------|:-------|:-----|-------------:|-----:|', - ...Object.keys(stats).map(identifier => { - const [size, diff] = (() => { - const statSize = stats[identifier]; - if (!statSize) { - return ['n/a', '--']; - } else if (!(identifier in document)) { - return [statSize, 'n/a']; - } else { - return [ - sizeFormatter.format(statSize), - diffFormatter.format(statSize - document[identifier]), - ]; - } - })(); - - const [platform, engineOrArch, ...archParts] = identifier.split('-'); - const arch = archParts.join('-') || engineOrArch; - const engine = arch === engineOrArch ? '-' : engineOrArch; // e.g. 'ios-universal' - return `| ${platform} | ${engine} | ${arch} | ${size} | ${diff} |`; - }), - '', - `Base commit: ${document.commit || ''}`, - `Branch: ${document.branch || ''}`, - ].join('\n'); - - return formatted; -} - -/** - * Returns the size of the file at specified path in bytes. - * @param {fs.PathLike} path - * @returns {number} - */ -function getFileSize(path) { - try { - const stats = fs.statSync(path); - return stats.size; - } catch { - return 0; - } -} - -/** - * Returns the size of the APK for specified JS engine and architecture. - * @param {'hermes' | 'jsc'} engine - * @param {'arm64-v8a' | 'armeabi-v7a' | 'x86' | 'x86_64'} arch - */ -function android_getApkSize(engine, arch) { - return getFileSize( - `packages/rn-tester/android/app/build/outputs/apk/${engine}/release/app-${engine}-${arch}-release.apk`, - ); -} - -/** - * Returns whether the specified ref points to a pull request. - */ -function isPullRequest(ref) { - return ref !== 'main' && !/^\d+\.\d+-stable$/.test(ref); -} - -/** - * Validates that required environment variables are set. - * @returns {boolean} `true` if everything is in order; `false` otherwise. - */ -function validateEnvironment() { - if (!GITHUB_REF) { - console.error("Missing GITHUB_REF. This should've been set by the CI."); - return false; - } - - if (isPullRequest(GITHUB_REF)) { - if (!validateEnvironmentForMakeComment()) { - return false; - } - } else if (!GITHUB_SHA) { - // To update the data store, we need the SHA associated with the build - console.error("Missing GITHUB_SHA. This should've been set by the CI."); - return false; - } - - console.log(` GITHUB_SHA=${GITHUB_SHA}`); - - return true; -} - -/** - * Reports app bundle size. - * @param {string} target - */ -async function report(target) { - switch (target) { - case 'android': - await reportSizeStats( - { - 'android-hermes-arm64-v8a': android_getApkSize('hermes', 'arm64-v8a'), - 'android-hermes-armeabi-v7a': android_getApkSize( - 'hermes', - 'armeabi-v7a', - ), - 'android-hermes-x86': android_getApkSize('hermes', 'x86'), - 'android-hermes-x86_64': android_getApkSize('hermes', 'x86_64'), - 'android-jsc-arm64-v8a': android_getApkSize('jsc', 'arm64-v8a'), - 'android-jsc-armeabi-v7a': android_getApkSize('jsc', 'armeabi-v7a'), - 'android-jsc-x86': android_getApkSize('jsc', 'x86'), - 'android-jsc-x86_64': android_getApkSize('jsc', 'x86_64'), - }, - '\\| android \\| hermes \\| arm', - ); - break; - - case 'ios': - await reportSizeStats( - { - 'ios-universal': getFileSize( - 'packages/rn-tester/build/Build/Products/Release-iphonesimulator/RNTester.app/RNTester', - ), - }, - '\\| ios \\| - \\| universal \\|', - ); - break; - - default: { - const path = require('path'); - console.log(`Syntax: ${path.basename(process.argv[1])} [android | ios]`); - process.exitCode = 2; - break; - } - } -} - -if (!validateEnvironment()) { - process.exit(1); -} - -const {[2]: target} = process.argv; -report(target).catch(error => { - console.error(error); - process.exitCode = 1; -}); diff --git a/packages/react-native-codegen/.babelrc b/packages/react-native-codegen/.babelrc deleted file mode 100644 index 7a6194fbaa55..000000000000 --- a/packages/react-native-codegen/.babelrc +++ /dev/null @@ -1,12 +0,0 @@ -{ - "plugins": [ - "@babel/plugin-proposal-object-rest-spread", - "@babel/plugin-transform-async-to-generator", - "@babel/plugin-transform-destructuring", - "@babel/plugin-transform-flow-strip-types", - "@babel/plugin-syntax-dynamic-import", - "@babel/plugin-proposal-class-properties", - "@babel/plugin-proposal-nullish-coalescing-operator", - "@babel/plugin-proposal-optional-chaining" - ] -} diff --git a/packages/react-native-codegen/.prettierrc b/packages/react-native-codegen/.prettierrc deleted file mode 100644 index 600a26c49518..000000000000 --- a/packages/react-native-codegen/.prettierrc +++ /dev/null @@ -1,8 +0,0 @@ -{ - "arrowParens": "avoid", - "bracketSameLine": true, - "bracketSpacing": false, - "requirePragma": true, - "singleQuote": true, - "trailingComma": "all" -} diff --git a/packages/react-native-codegen/BUCK b/packages/react-native-codegen/BUCK deleted file mode 100644 index d06563f4a08c..000000000000 --- a/packages/react-native-codegen/BUCK +++ /dev/null @@ -1,111 +0,0 @@ -load("//tools/build_defs:fb_native_wrapper.bzl", "fb_native") -load("//tools/build_defs/oss:rn_defs.bzl", "ANDROID", "APPLE", "IOS", "IS_OSS_BUILD", "react_native_root_target", "react_native_target", "rn_android_library", "rn_xplat_cxx_library") -load("//tools/build_defs/third_party:yarn_defs.bzl", "yarn_workspace") -load(":DEFS.bzl", "rn_codegen_cli", "rn_codegen_components", "rn_codegen_modules") - -rn_codegen_cli() - -SETUP_ENV_DEPS = [] if IS_OSS_BUILD else [ - "//xplat/js:setup_env", -] - -fb_native.genrule( - name = "codegen_tests_schema", - srcs = glob( - [ - "**/e2e/__test_fixtures__/components/*NativeComponent.js", - "**/e2e/__test_fixtures__/modules/Native*.js", - ], - ), - out = "schema-codegen_tests.json", - cmd = "$(exe {}) $OUT $SRCS".format(react_native_root_target("packages/react-native-codegen:write_to_json")), -) - -rn_codegen_components( - name = "codegen_tests", - schema_target = ":codegen_tests_schema", -) - -rn_codegen_modules( - name = "FBReactNativeTestSpec", - android_package_name = "com.facebook.fbreact.specs", - ios_assume_nonnull = False, - schema_target = ":codegen_tests_schema", -) - -rn_android_library( - name = "rn_codegen_library_java", - srcs = glob( - ["buck_tests/*.java"], - ), - autoglob = False, - language = "JAVA", - visibility = [ - "PUBLIC", - ], - deps = [ - react_native_target("java/com/facebook/react/bridge:bridge"), - react_native_target("java/com/facebook/react/common:common"), - react_native_target("java/com/facebook/react/views/view:view"), - react_native_target("java/com/facebook/react/uimanager:uimanager"), - ":generated_components_java-codegen_tests", - ], -) - -rn_xplat_cxx_library( - name = "rn_codegen_library", - srcs = ["buck_tests/emptyFile.cpp"], - headers = [], - platforms = (ANDROID, APPLE), - preprocessor_flags = [ - "-DLOG_TAG=\"ReactNative\"", - "-DWITH_FBSYSTRACE=1", - ], - visibility = [ - "PUBLIC", - ], - deps = [ - ":generated_components-codegen_tests", - ], -) - -rn_xplat_cxx_library( - name = "rn_codegen_library_mm", - srcs = ["buck_tests/emptyFile.mm"], - headers = [], - apple_sdks = (IOS,), - platforms = APPLE, - preprocessor_flags = [ - "-DLOG_TAG=\"ReactNative\"", - "-DWITH_FBSYSTRACE=1", - ], - visibility = [ - "PUBLIC", - ], - deps = [ - ":FBReactNativeTestSpec", - ":generated_components-codegen_tests", - ], -) - -yarn_workspace( - name = "yarn-workspace", - srcs = glob( - ["src/**/*.js"], - exclude = [ - "**/__fixtures__/**", - "**/__flowtests__/**", - "**/__mocks__/**", - "**/__server_snapshot_tests__/**", - "**/__tests__/**", - "**/node_modules/**", - "**/node_modules/.bin/**", - "**/.*", - "**/.*/**", - "**/.*/.*", - "**/*.xcodeproj/**", - "**/*.xcworkspace/**", - ], - ), - visibility = ["PUBLIC"], -) diff --git a/packages/react-native-codegen/DEFS.bzl b/packages/react-native-codegen/DEFS.bzl deleted file mode 100644 index 48201e82d063..000000000000 --- a/packages/react-native-codegen/DEFS.bzl +++ /dev/null @@ -1,591 +0,0 @@ -# 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. - -load("//tools/build_defs:buckconfig.bzl", "read_bool") -load("//tools/build_defs:fb_native_wrapper.bzl", "fb_native") -load( - "//tools/build_defs/oss:rn_defs.bzl", - "ANDROID", - "APPLE", - "CXX", - "IOS", - "IS_OSS_BUILD", - "MACOSX", - "WINDOWS", - "YOGA_CXX_TARGET", - "fb_xplat_cxx_test", - "get_apple_compiler_flags", - "get_apple_inspector_flags", - "get_preprocessor_flags_for_build_mode", - "react_native_dep", - "react_native_desktop_root_target", - "react_native_root_target", - "react_native_target", - "react_native_xplat_shared_library_target", - "react_native_xplat_target", - "react_native_xplat_target_apple", - "rn_android_library", - "rn_apple_library", - "rn_xplat_cxx_library", -) -load("//tools/build_defs/third_party:yarn_defs.bzl", "yarn_workspace_binary") - -# Call this in the react-native-codegen/BUCK file -def rn_codegen_cli(): - if not IS_OSS_BUILD: - # FB Internal Setup - yarn_workspace_binary( - name = "write_to_json", - main = "src/cli/combine/combine-js-to-schema-cli.js", - root = "//xplat/js:workspace", - deps = [ - ":yarn-workspace", - ], - visibility = ["PUBLIC"], - ) - yarn_workspace_binary( - name = "generate_all_from_schema", - main = "src/cli/generators/generate-all.js", - root = "//xplat/js:workspace", - deps = [ - ":yarn-workspace", - ], - visibility = ["PUBLIC"], - ) - else: - # OSS setup, assumes yarn and node (v12.0.0+) are installed. - fb_native.genrule( - name = "setup_cli", - srcs = native.glob([ - "scripts/**/*", - "src/**/*", - ], exclude = [ - "__tests__/**/*", - ]) + [ - ".babelrc", - ".prettierrc", - "package.json", - ], - out = "build", - bash = r""" - set -euo pipefail - mkdir -p "$OUT" - rsync -rLptgoD "$SRCDIR/" "$OUT" - cd "$OUT" - yarn install 2> >(grep -v '^warning' 1>&2) - yarn run build - """, - ) - - fb_native.sh_binary( - name = "write_to_json", - main = "scripts/buck-oss/combine_js_to_schema.sh", - resources = [ - ":setup_cli", - ], - visibility = ["PUBLIC"], - ) - - fb_native.sh_binary( - name = "generate_all_from_schema", - main = "scripts/buck-oss/generate-all.sh", - resources = [ - ":setup_cli", - ], - visibility = ["PUBLIC"], - ) - -def rn_codegen_modules( - name, - android_package_name, - ios_assume_nonnull, - library_labels = [], - schema_target = ""): - generate_fixtures_rule_name = "{}-codegen-modules".format(name) - generate_module_hobjcpp_name = "{}-codegen-modules-hobjcpp".format(name) - generate_module_mm_name = "{}-codegen-modules-mm".format(name) - generate_module_java_name = "{}-codegen-modules-java".format(name) - generate_module_java_zip_name = "{}-codegen-modules-java_zip".format(name) - generate_module_jni_h_name = "{}-codegen-modules-jni_h".format(name) - generate_module_jni_cpp_name = "{}-codegen-modules-jni_cpp".format(name) - - fb_native.genrule( - name = generate_fixtures_rule_name, - srcs = native.glob(["src/generators/**/*.js"]), - cmd = "$(exe {generator_script}) $(location {schema_target}) {library_name} $OUT {android_package_name} {ios_assume_nonnull}".format( - generator_script = react_native_root_target("packages/react-native-codegen:generate_all_from_schema"), - schema_target = schema_target, - library_name = name, - android_package_name = android_package_name, - ios_assume_nonnull = ios_assume_nonnull, - ), - out = "codegenfiles-{}".format(name), - labels = ["codegen_rule", "uses_local_filesystem_abspaths"], - ) - - ################## - # Android handling - ################## - fb_native.genrule( - name = generate_module_java_name, - cmd = "mkdir -p $OUT/{spec_path} && cp -r $(location {generator_target})/java/{spec_path}/* $OUT/{spec_path}/".format( - spec_path = android_package_name.replace(".", "/"), - generator_target = ":" + generate_fixtures_rule_name, - ), - out = "src", - labels = ["codegen_rule"], - ) - - fb_native.zip_file( - name = generate_module_java_zip_name, - srcs = [":{}".format(generate_module_java_name)], - out = "{}.src.zip".format(generate_module_java_zip_name), - labels = ["codegen_rule"], - ) - - fb_native.genrule( - name = generate_module_jni_h_name, - cmd = "cp $(location :{})/jni/{}.h $OUT".format(generate_fixtures_rule_name, name), - out = "{}.h".format(name), - labels = ["codegen_rule"], - ) - - fb_native.genrule( - name = generate_module_jni_cpp_name, - cmd = "cp $(location :{})/jni/{}-generated.cpp $OUT".format(generate_fixtures_rule_name, name), - out = "{}-generated.cpp".format(name), - labels = ["codegen_rule"], - ) - - rn_android_library( - name = "{}".format(name), - srcs = [ - ":{}".format(generate_module_java_zip_name), - ], - autoglob = False, - labels = library_labels + ["codegen_rule"], - language = "JAVA", - visibility = ["PUBLIC"], - deps = [ - react_native_dep("third-party/java/jsr-305:jsr-305"), - react_native_dep("third-party/java/jsr-330:jsr-330"), - react_native_target("java/com/facebook/react/bridge:bridge"), - react_native_target("java/com/facebook/react/common:common"), - ], - exported_deps = [ - react_native_target("java/com/facebook/react/turbomodule/core/interfaces:interfaces"), - ], - ) - - rn_xplat_cxx_library( - name = "{}-jni".format(name), - srcs = [ - ":{}".format(generate_module_jni_cpp_name), - ], - header_namespace = "", - headers = [ - ":{}".format(generate_module_jni_h_name), - ], - exported_headers = { - "{}/{}.h".format(name, name): ":{}".format(generate_module_jni_h_name), - }, - force_static = True, - preprocessor_flags = [ - "-DLOG_TAG=\"ReactNative\"", - "-DWITH_FBSYSTRACE=1", - ], - visibility = [ - "PUBLIC", - ], - deps = [], - exported_deps = [ - react_native_xplat_shared_library_target("jsi:jsi"), - react_native_xplat_target("react/nativemodule/core:core"), - ], - platforms = (ANDROID,), - labels = library_labels + ["codegen_rule"], - ) - - ############## - # iOS handling - ############## - if not IS_OSS_BUILD: - # iOS Buck build isn't fully working in OSS, so let's skip it for OSS for now. - fb_native.genrule( - name = generate_module_hobjcpp_name, - cmd = "cp $(location :{})/{}/{}.h $OUT".format(generate_fixtures_rule_name, name, name), - out = "{}.h".format(name), - labels = ["codegen_rule"], - ) - - fb_native.genrule( - name = generate_module_mm_name, - cmd = "cp $(location :{})/{}/{}-generated.mm $OUT".format(generate_fixtures_rule_name, name, name), - out = "{}-generated.mm".format(name), - labels = ["codegen_rule"], - ) - - rn_apple_library( - name = "{}Apple".format(name), - extension_api_only = True, - header_namespace = "", - sdks = (IOS), - compiler_flags = [ - "-Wno-unused-private-field", - ], - exported_headers = { - "{}/{}.h".format(name, name): ":{}".format(generate_module_hobjcpp_name), - }, - headers = [ - ":{}".format(generate_module_hobjcpp_name), - ], - srcs = [ - ":{}".format(generate_module_mm_name), - ], - autoglob = False, - labels = library_labels + ["codegen_rule"], - visibility = ["PUBLIC"], - exported_deps = [ - "//xplat/js/react-native-github:RCTTypeSafety", - "//xplat/js/react-native-github/Libraries/RCTRequired:RCTRequired", - react_native_xplat_target_apple("react/nativemodule/core:core"), - ], - ) - -def rn_codegen_components( - name = "", - schema_target = "", - library_labels = []): - generate_fixtures_rule_name = "generate_fixtures_components-{}".format(name) - generate_component_descriptor_h_name = "generate_component_descriptor_h-{}".format(name) - generate_component_hobjcpp_name = "generate_component_hobjcpp-{}".format(name) - generate_event_emitter_cpp_name = "generate_event_emitter_cpp-{}".format(name) - generate_event_emitter_h_name = "generate_event_emitter_h-{}".format(name) - generate_props_cpp_name = "generate_props_cpp-{}".format(name) - generate_props_h_name = "generated_props_h-{}".format(name) - generate_state_cpp_name = "generate_state_cpp-{}".format(name) - generate_state_h_name = "generated_state_h-{}".format(name) - generate_tests_cpp_name = "generate_tests_cpp-{}".format(name) - generate_shadow_node_cpp_name = "generated_shadow_node_cpp-{}".format(name) - generate_shadow_node_h_name = "generated_shadow_node_h-{}".format(name) - copy_generated_java_files = "copy_generated_java_files-{}".format(name) - copy_generated_cxx_files = "copy_generated_cxx_files-{}".format(name) - zip_generated_java_files = "zip_generated_java_files-{}".format(name) - zip_generated_cxx_files = "zip_generated_cxx_files-{}".format(name) - - fb_native.genrule( - name = generate_fixtures_rule_name, - srcs = native.glob(["src/generators/**/*.js"]), - cmd = "$(exe {}) $(location {}) {} $OUT".format(react_native_root_target("packages/react-native-codegen:generate_all_from_schema"), schema_target, name), - out = "codegenfiles-{}".format(name), - labels = ["codegen_rule", "uses_local_filesystem_abspaths"], - ) - - fb_native.genrule( - name = generate_component_descriptor_h_name, - cmd = "cp $(location :{})/ComponentDescriptors.h $OUT".format(generate_fixtures_rule_name), - out = "ComponentDescriptors.h", - labels = ["codegen_rule"], - ) - - fb_native.genrule( - name = generate_component_hobjcpp_name, - cmd = "cp $(location :{})/RCTComponentViewHelpers.h $OUT".format(generate_fixtures_rule_name), - out = "RCTComponentViewHelpers.h", - labels = ["codegen_rule"], - ) - - fb_native.genrule( - name = generate_event_emitter_cpp_name, - cmd = "cp $(location :{})/EventEmitters.cpp $OUT".format(generate_fixtures_rule_name), - out = "EventEmitters.cpp", - labels = ["codegen_rule"], - ) - - fb_native.genrule( - name = generate_event_emitter_h_name, - cmd = "cp $(location :{})/EventEmitters.h $OUT".format(generate_fixtures_rule_name), - out = "EventEmitters.h", - labels = ["codegen_rule"], - ) - - fb_native.genrule( - name = generate_props_cpp_name, - cmd = "cp $(location :{})/Props.cpp $OUT".format(generate_fixtures_rule_name), - out = "Props.cpp", - labels = ["codegen_rule"], - ) - - fb_native.genrule( - name = generate_state_cpp_name, - cmd = "cp $(location :{})/States.cpp $OUT".format(generate_fixtures_rule_name), - out = "States.cpp", - labels = ["codegen_rule"], - ) - - fb_native.genrule( - name = generate_tests_cpp_name, - cmd = "cp $(location :{})/Tests.cpp $OUT".format(generate_fixtures_rule_name), - out = "Tests.cpp", - labels = ["codegen_rule"], - ) - - fb_native.genrule( - name = generate_props_h_name, - cmd = "cp $(location :{})/Props.h $OUT".format(generate_fixtures_rule_name), - out = "Props.h", - labels = ["codegen_rule"], - ) - - fb_native.genrule( - name = generate_state_h_name, - cmd = "cp $(location :{})/States.h $OUT".format(generate_fixtures_rule_name), - out = "States.h", - labels = ["codegen_rule"], - ) - - fb_native.genrule( - name = copy_generated_java_files, - # TODO: support different package name internally. - # Right now, it's hardcoded to `com.facebook.react.viewmanagers`. - cmd = "mkdir -p $OUT/com/facebook/react/viewmanagers && cp -R $(location :{})/java/com/facebook/react/viewmanagers/* $OUT/com/facebook/react/viewmanagers".format(generate_fixtures_rule_name), - out = "java", - labels = ["codegen_rule"], - ) - - fb_native.genrule( - name = copy_generated_cxx_files, - # The command below is filtering C++ iOS files, this will be refactored when C++ codegen is finished. - cmd = "mkdir -p $OUT && find $(location :{}) -not -path '*/rncore*' -not -path '*Tests*' -not -path '*NativeModules*' -not -path '*RCTComponentViewHelpers*' -type f \\( -iname \\*.h -o -iname \\*.cpp \\) -print0 -exec cp {{}} $OUT \\;".format(generate_fixtures_rule_name), - out = "cxx", - labels = ["codegen_rule"], - ) - - fb_native.zip_file( - name = zip_generated_cxx_files, - srcs = [":{}".format(copy_generated_cxx_files)], - out = "{}.src.zip".format(zip_generated_cxx_files), - visibility = ["PUBLIC"], - labels = ["codegen_rule"], - ) - - fb_native.zip_file( - name = zip_generated_java_files, - srcs = [":{}".format(copy_generated_java_files)], - out = "{}.src.zip".format(zip_generated_java_files), - visibility = ["PUBLIC"], - labels = ["codegen_rule"], - ) - - fb_native.genrule( - name = generate_shadow_node_cpp_name, - cmd = "cp $(location :{})/ShadowNodes.cpp $OUT".format(generate_fixtures_rule_name), - out = "ShadowNodes.cpp", - labels = ["codegen_rule"], - ) - - fb_native.genrule( - name = generate_shadow_node_h_name, - cmd = "cp $(location :{})/ShadowNodes.h $OUT".format(generate_fixtures_rule_name), - out = "ShadowNodes.h", - labels = ["codegen_rule"], - ) - - ############## - # iOS handling - ############## - if not IS_OSS_BUILD: - # iOS Buck build isn't fully working in OSS, so let's skip it for OSS for now. - if is_running_buck_project(): - rn_xplat_cxx_library(name = "generated_components-{}".format(name), visibility = ["PUBLIC"]) - else: - rn_xplat_cxx_library( - name = "generated_components-{}".format(name), - srcs = [ - ":{}".format(generate_event_emitter_cpp_name), - ":{}".format(generate_props_cpp_name), - ":{}".format(generate_state_cpp_name), - ":{}".format(generate_shadow_node_cpp_name), - ], - headers = [ - ":{}".format(generate_component_descriptor_h_name), - ":{}".format(generate_event_emitter_h_name), - ":{}".format(generate_props_h_name), - ":{}".format(generate_state_h_name), - ":{}".format(generate_shadow_node_h_name), - ], - header_namespace = "react/renderer/components/{}".format(name), - exported_headers = { - "ComponentDescriptors.h": ":{}".format(generate_component_descriptor_h_name), - "EventEmitters.h": ":{}".format(generate_event_emitter_h_name), - "Props.h": ":{}".format(generate_props_h_name), - "RCTComponentViewHelpers.h": ":{}".format(generate_component_hobjcpp_name), - "ShadowNodes.h": ":{}".format(generate_shadow_node_h_name), - "States.h": ":{}".format(generate_state_h_name), - }, - fbobjc_compiler_flags = get_apple_compiler_flags(), - fbobjc_preprocessor_flags = get_preprocessor_flags_for_build_mode() + get_apple_inspector_flags(), - ios_exported_headers = { - "ComponentViewHelpers.h": ":{}".format(generate_component_hobjcpp_name), - }, - ios_headers = [ - ":{}".format(generate_component_hobjcpp_name), - ], - labels = library_labels + ["codegen_rule"], - platforms = (ANDROID, APPLE, CXX), - preprocessor_flags = [ - "-DLOG_TAG=\"ReactNative\"", - "-DWITH_FBSYSTRACE=1", - ], - tests = [":generated_tests-{}".format(name)], - visibility = ["PUBLIC"], - deps = [ - react_native_xplat_target("react/renderer/debug:debug"), - react_native_xplat_target("react/renderer/core:core"), - react_native_xplat_target("react/renderer/graphics:graphics"), - react_native_xplat_target("react/renderer/components/image:image"), - react_native_xplat_target("react/renderer/imagemanager:imagemanager"), - react_native_xplat_target("react/renderer/components/view:view"), - ], - ) - - # Tests - fb_xplat_cxx_test( - name = "generated_tests-{}".format(name), - # TODO T96844980: Fix and enable generated_tests-codegen_testsAndroid - srcs = [] if ANDROID else [ - ":{}".format(generate_tests_cpp_name), - ], - apple_sdks = (IOS, MACOSX), - fbandroid_use_instrumentation_test = True, - compiler_flags = [ - "-fexceptions", - "-frtti", - "-std=c++17", - "-Wall", - ], - contacts = ["oncall+react_native@xmail.facebook.com"], - labels = library_labels + ["codegen_rule"], - platforms = (ANDROID, APPLE, CXX), - deps = [ - YOGA_CXX_TARGET, - react_native_xplat_target("react/renderer/core:core"), - "//xplat/third-party/gmock:gtest", - ":generated_components-{}".format(name), - ], - ) - - ################## - # Android handling - ################## - if is_running_buck_project(): - rn_android_library(name = "generated_components_java-{}".format(name), autoglob = False, language = "JAVA") - else: - rn_android_library( - name = "generated_components_java-{}".format(name), - srcs = [ - ":{}".format(zip_generated_java_files), - ], - language = "JAVA", - autoglob = False, - labels = library_labels + ["codegen_rule"], - visibility = ["PUBLIC"], - deps = [ - react_native_dep("third-party/android/androidx:annotation"), - react_native_target("java/com/facebook/react/bridge:bridge"), - react_native_target("java/com/facebook/react/uimanager:interfaces"), - ], - ) - - rn_android_library( - name = "generated_components_cxx-{}".format(name), - srcs = [ - ":{}".format(zip_generated_cxx_files), - ], - language = "JAVA", - autoglob = False, - labels = library_labels + ["codegen_rule"], - visibility = ["PUBLIC"], - deps = [ - react_native_dep("third-party/android/androidx:annotation"), - react_native_target("java/com/facebook/react/bridge:bridge"), - react_native_target("java/com/facebook/react/common:common"), - react_native_target("java/com/facebook/react/turbomodule/core:core"), - react_native_target("java/com/facebook/react/uimanager:uimanager"), - ], - ) - -def rn_codegen_cxx_modules( - name = "", - schema_target = "", - library_labels = []): - generate_fixtures_rule_name = "generate_fixtures_cxx-{}".format(name) - generate_module_h_name = "generate_module_h-{}".format(name) - generate_module_cpp_name = "generate_module_cpp-{}".format(name) - - fb_native.genrule( - name = generate_fixtures_rule_name, - srcs = native.glob(["src/generators/**/*.js"]), - cmd = "$(exe {}) $(location {}) {} $OUT {}".format(react_native_root_target("packages/react-native-codegen:generate_all_from_schema"), schema_target, name, name), - out = "codegenfiles-{}".format(name), - labels = ["codegen_rule"], - ) - - fb_native.genrule( - name = generate_module_h_name, - cmd = "cp $(location :{})/{}JSI.h $OUT".format(generate_fixtures_rule_name, name), - cmd_exe = "copy $(location :{})\\{}JSI.h $OUT".format(generate_fixtures_rule_name, name), - out = "{}JSI.h".format(name), - labels = ["codegen_rule"], - ) - - fb_native.genrule( - name = generate_module_cpp_name, - cmd = "cp $(location :{})/{}JSI-generated.cpp $OUT".format(generate_fixtures_rule_name, name), - cmd_exe = "copy $(location :{})\\{}JSI-generated.cpp $OUT".format(generate_fixtures_rule_name, name), - out = "{}JSI-generated.cpp".format(name), - labels = ["codegen_rule"], - ) - - if is_running_buck_project(): - rn_xplat_cxx_library(name = "{}JSI".format(name), visibility = ["PUBLIC"]) - else: - rn_xplat_cxx_library( - name = "{}JSI".format(name), - srcs = [ - ":{}".format(generate_module_cpp_name), - ], - headers = [ - ":{}".format(generate_module_h_name), - ], - header_namespace = "", - exported_headers = { - "{}/{}JSI.h".format(name, name): ":{}".format(generate_module_h_name), - }, - fbobjc_compiler_flags = get_apple_compiler_flags(), - fbobjc_preprocessor_flags = get_preprocessor_flags_for_build_mode() + get_apple_inspector_flags(), - labels = library_labels + ["codegen_rule"], - platforms = (ANDROID, APPLE, CXX, WINDOWS), - preprocessor_flags = [ - "-DLOG_TAG=\"ReactNative\"", - "-DWITH_FBSYSTRACE=1", - ], - visibility = ["PUBLIC"], - fbandroid_exported_deps = [ - react_native_xplat_target("react/nativemodule/core:core"), - ], - ios_exported_deps = [ - react_native_xplat_target("react/nativemodule/core:core"), - ], - macosx_exported_deps = [ - react_native_desktop_root_target(":bridging"), - ], - windows_exported_deps = [ - react_native_desktop_root_target(":bridging"), - ], - ) - -def is_running_buck_project(): - return read_bool("fbandroid", "is_running_buck_project", False) diff --git a/packages/react-native-codegen/README.md b/packages/react-native-codegen/README.md deleted file mode 100644 index d1661e4e5bbf..000000000000 --- a/packages/react-native-codegen/README.md +++ /dev/null @@ -1,21 +0,0 @@ -# react-native-codegen - -[![Version][version-badge]][package] - -## Installation - -``` -yarn add --dev react-native-codegen -``` - -*Note: We're using `yarn` to install deps. Feel free to change commands to use `npm` 3+ and `npx` if you like* - -[version-badge]: https://img.shields.io/npm/v/react-native-codegen?style=flat-square -[package]: https://www.npmjs.com/package/react-native-codegen - -## Testing - -To run the tests in this package, run the following commands from the react Native root folder: - -1. `yarn` to install the dependencies. You just need to run this once -2. `yarn jest react-native-codegen`. diff --git a/packages/react-native-codegen/buck_tests/emptyFile.cpp b/packages/react-native-codegen/buck_tests/emptyFile.cpp deleted file mode 100644 index 624a0fdeda85..000000000000 --- a/packages/react-native-codegen/buck_tests/emptyFile.cpp +++ /dev/null @@ -1,14 +0,0 @@ -/* - * 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. - */ - -#import - -// TODO: Import every prop and event to asset they're generated - -int main() { - return 0; -} diff --git a/packages/react-native-codegen/buck_tests/emptyFile.mm b/packages/react-native-codegen/buck_tests/emptyFile.mm deleted file mode 100644 index 8dac3f61a54f..000000000000 --- a/packages/react-native-codegen/buck_tests/emptyFile.mm +++ /dev/null @@ -1,18 +0,0 @@ -/* - * 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. - */ - -#import -#import -#import -#import - -// TODO: Import every prop and event to asset they're generated - -int main() -{ - return 0; -} diff --git a/packages/react-native-codegen/buck_tests/java/ArrayPropsNativeComponentViewManager.java b/packages/react-native-codegen/buck_tests/java/ArrayPropsNativeComponentViewManager.java deleted file mode 100644 index 9a13a534a07e..000000000000 --- a/packages/react-native-codegen/buck_tests/java/ArrayPropsNativeComponentViewManager.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.uimanager; - -import android.view.ViewGroup; -import com.facebook.react.bridge.ReadableArray; -import com.facebook.react.viewmanagers.ArrayPropsNativeComponentViewManagerDelegate; -import com.facebook.react.viewmanagers.ArrayPropsNativeComponentViewManagerInterface; - -public class ArrayPropsNativeComponentViewManager extends SimpleViewManager - implements ArrayPropsNativeComponentViewManagerInterface { - - public static final String REACT_CLASS = "ArrayPropsNativeComponentView"; - - @Override - public String getName() { - return REACT_CLASS; - } - - private void test() { - ArrayPropsNativeComponentViewManagerDelegate - delegate = new ArrayPropsNativeComponentViewManagerDelegate<>(this); - } - - @Override - public ViewGroup createViewInstance(ThemedReactContext context) { - throw new IllegalStateException(); - } - - @Override - public void setNames(ViewGroup view, ReadableArray value) {} - - @Override - public void setDisableds(ViewGroup view, ReadableArray value) {} - - @Override - public void setProgress(ViewGroup view, ReadableArray value) {} - - @Override - public void setRadii(ViewGroup view, ReadableArray value) {} - - @Override - public void setColors(ViewGroup view, ReadableArray value) {} - - @Override - public void setSrcs(ViewGroup view, ReadableArray value) {} - - @Override - public void setPoints(ViewGroup view, ReadableArray value) {} - - @Override - public void setEdgeInsets(ViewGroup view, ReadableArray value) {} - - @Override - public void setSizes(ViewGroup view, ReadableArray value) {} - - @Override - public void setObject(ViewGroup view, ReadableArray value) {} -} diff --git a/packages/react-native-codegen/buck_tests/java/BooleanPropNativeComponentViewManager.java b/packages/react-native-codegen/buck_tests/java/BooleanPropNativeComponentViewManager.java deleted file mode 100644 index 102c55a43ea8..000000000000 --- a/packages/react-native-codegen/buck_tests/java/BooleanPropNativeComponentViewManager.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.uimanager; - -import android.view.ViewGroup; -import androidx.annotation.Nullable; -import com.facebook.react.viewmanagers.BooleanPropNativeComponentViewManagerDelegate; -import com.facebook.react.viewmanagers.BooleanPropNativeComponentViewManagerInterface; - -public class BooleanPropNativeComponentViewManager extends SimpleViewManager - implements BooleanPropNativeComponentViewManagerInterface { - - public static final String REACT_CLASS = "BooleanPropNativeComponentView"; - - @Override - public String getName() { - return REACT_CLASS; - } - - private void test() { - BooleanPropNativeComponentViewManagerDelegate - delegate = new BooleanPropNativeComponentViewManagerDelegate<>(this); - } - - @Override - public ViewGroup createViewInstance(ThemedReactContext context) { - throw new IllegalStateException(); - } - - @Override - public void setDisabled(ViewGroup view, boolean value) {} - - @Override - public void setDisabledNullable(ViewGroup view, @Nullable Boolean value) {} -} diff --git a/packages/react-native-codegen/buck_tests/java/ColorPropNativeComponentViewManager.java b/packages/react-native-codegen/buck_tests/java/ColorPropNativeComponentViewManager.java deleted file mode 100644 index 97fb8e0accd8..000000000000 --- a/packages/react-native-codegen/buck_tests/java/ColorPropNativeComponentViewManager.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.uimanager; - -import android.view.ViewGroup; -import com.facebook.react.viewmanagers.ColorPropNativeComponentViewManagerDelegate; -import com.facebook.react.viewmanagers.ColorPropNativeComponentViewManagerInterface; - -public class ColorPropNativeComponentViewManager extends SimpleViewManager - implements ColorPropNativeComponentViewManagerInterface { - - public static final String REACT_CLASS = "ColorPropNativeComponentView"; - - @Override - public String getName() { - return REACT_CLASS; - } - - private void test() { - ColorPropNativeComponentViewManagerDelegate - delegate = new ColorPropNativeComponentViewManagerDelegate<>(this); - } - - @Override - public ViewGroup createViewInstance(ThemedReactContext context) { - throw new IllegalStateException(); - } - - @Override - public void setTintColor(ViewGroup view, Integer value) {} -} diff --git a/packages/react-native-codegen/buck_tests/java/EdgeInsetsPropNativeComponentViewManager.java b/packages/react-native-codegen/buck_tests/java/EdgeInsetsPropNativeComponentViewManager.java deleted file mode 100644 index a1d14a7025b1..000000000000 --- a/packages/react-native-codegen/buck_tests/java/EdgeInsetsPropNativeComponentViewManager.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.uimanager; - -import android.view.ViewGroup; -import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.viewmanagers.EdgeInsetsPropNativeComponentViewManagerDelegate; -import com.facebook.react.viewmanagers.EdgeInsetsPropNativeComponentViewManagerInterface; - -public class EdgeInsetsPropNativeComponentViewManager extends SimpleViewManager - implements EdgeInsetsPropNativeComponentViewManagerInterface { - - public static final String REACT_CLASS = "EdgeInsetsPropNativeComponentView"; - - @Override - public String getName() { - return REACT_CLASS; - } - - private void test() { - EdgeInsetsPropNativeComponentViewManagerDelegate< - ViewGroup, EdgeInsetsPropNativeComponentViewManager> - delegate = new EdgeInsetsPropNativeComponentViewManagerDelegate<>(this); - } - - @Override - public ViewGroup createViewInstance(ThemedReactContext context) { - throw new IllegalStateException(); - } - - @Override - public void setContentInset(ViewGroup view, ReadableMap value) {} -} diff --git a/packages/react-native-codegen/buck_tests/java/EnumPropNativeComponentViewManager.java b/packages/react-native-codegen/buck_tests/java/EnumPropNativeComponentViewManager.java deleted file mode 100644 index a7fd1c09b699..000000000000 --- a/packages/react-native-codegen/buck_tests/java/EnumPropNativeComponentViewManager.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.uimanager; - -import android.view.ViewGroup; -import com.facebook.react.viewmanagers.EnumPropNativeComponentViewManagerDelegate; -import com.facebook.react.viewmanagers.EnumPropNativeComponentViewManagerInterface; - -public class EnumPropNativeComponentViewManager extends SimpleViewManager - implements EnumPropNativeComponentViewManagerInterface { - - public static final String REACT_CLASS = "EnumPropNativeComponentView"; - - @Override - public String getName() { - return REACT_CLASS; - } - - private void test() { - EnumPropNativeComponentViewManagerDelegate - delegate = new EnumPropNativeComponentViewManagerDelegate<>(this); - } - - @Override - public ViewGroup createViewInstance(ThemedReactContext context) { - throw new IllegalStateException(); - } - - @Override - public void setAlignment(ViewGroup view, String value) {} - - @Override - public void setIntervals(ViewGroup view, Integer value) {} -} diff --git a/packages/react-native-codegen/buck_tests/java/EventNestedObjectPropsNativeComponentViewManager.java b/packages/react-native-codegen/buck_tests/java/EventNestedObjectPropsNativeComponentViewManager.java deleted file mode 100644 index def1346b2f22..000000000000 --- a/packages/react-native-codegen/buck_tests/java/EventNestedObjectPropsNativeComponentViewManager.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.uimanager; - -import android.view.ViewGroup; -import com.facebook.react.viewmanagers.EventNestedObjectPropsNativeComponentViewManagerDelegate; -import com.facebook.react.viewmanagers.EventNestedObjectPropsNativeComponentViewManagerInterface; - -public class EventNestedObjectPropsNativeComponentViewManager extends SimpleViewManager - implements EventNestedObjectPropsNativeComponentViewManagerInterface { - - public static final String REACT_CLASS = "EventNestedObjectPropsNativeComponentView"; - - @Override - public String getName() { - return REACT_CLASS; - } - - private void test() { - EventNestedObjectPropsNativeComponentViewManagerDelegate< - ViewGroup, EventNestedObjectPropsNativeComponentViewManager> - delegate = new EventNestedObjectPropsNativeComponentViewManagerDelegate<>(this); - } - - @Override - public ViewGroup createViewInstance(ThemedReactContext context) { - throw new IllegalStateException(); - } - - @Override - public void setDisabled(ViewGroup view, boolean value) {} -} diff --git a/packages/react-native-codegen/buck_tests/java/EventPropsNativeComponentViewManager.java b/packages/react-native-codegen/buck_tests/java/EventPropsNativeComponentViewManager.java deleted file mode 100644 index 96cd9ad9b5ce..000000000000 --- a/packages/react-native-codegen/buck_tests/java/EventPropsNativeComponentViewManager.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.uimanager; - -import android.view.ViewGroup; -import com.facebook.react.viewmanagers.EventPropsNativeComponentViewManagerDelegate; -import com.facebook.react.viewmanagers.EventPropsNativeComponentViewManagerInterface; - -public class EventPropsNativeComponentViewManager extends SimpleViewManager - implements EventPropsNativeComponentViewManagerInterface { - - public static final String REACT_CLASS = "EventPropsNativeComponentView"; - - @Override - public String getName() { - return REACT_CLASS; - } - - private void test() { - EventPropsNativeComponentViewManagerDelegate - delegate = new EventPropsNativeComponentViewManagerDelegate<>(this); - } - - @Override - public ViewGroup createViewInstance(ThemedReactContext context) { - throw new IllegalStateException(); - } - - @Override - public void setDisabled(ViewGroup view, boolean value) {} -} diff --git a/packages/react-native-codegen/buck_tests/java/FloatPropsNativeComponentViewManager.java b/packages/react-native-codegen/buck_tests/java/FloatPropsNativeComponentViewManager.java deleted file mode 100644 index b620fba704df..000000000000 --- a/packages/react-native-codegen/buck_tests/java/FloatPropsNativeComponentViewManager.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.uimanager; - -import android.view.ViewGroup; -import androidx.annotation.Nullable; -import com.facebook.react.viewmanagers.FloatPropsNativeComponentViewManagerDelegate; -import com.facebook.react.viewmanagers.FloatPropsNativeComponentViewManagerInterface; - -public class FloatPropsNativeComponentViewManager extends SimpleViewManager - implements FloatPropsNativeComponentViewManagerInterface { - - public static final String REACT_CLASS = "FloatPropsNativeComponentView"; - - @Override - public String getName() { - return REACT_CLASS; - } - - private void test() { - FloatPropsNativeComponentViewManagerDelegate - delegate = new FloatPropsNativeComponentViewManagerDelegate<>(this); - } - - @Override - public ViewGroup createViewInstance(ThemedReactContext context) { - throw new IllegalStateException(); - } - - @Override - public void setBlurRadius(ViewGroup view, float value) {} - - @Override - public void setBlurRadius2(ViewGroup view, float value) {} - - @Override - public void setBlurRadius3(ViewGroup view, float value) {} - - @Override - public void setBlurRadius4(ViewGroup view, float value) {} - - @Override - public void setBlurRadius5(ViewGroup view, float value) {} - - @Override - public void setBlurRadius6(ViewGroup view, float value) {} - - @Override - public void setBlurRadiusNullable(ViewGroup view, @Nullable Float value) {} -} diff --git a/packages/react-native-codegen/buck_tests/java/ImagePropNativeComponentViewManager.java b/packages/react-native-codegen/buck_tests/java/ImagePropNativeComponentViewManager.java deleted file mode 100644 index ec64469d725a..000000000000 --- a/packages/react-native-codegen/buck_tests/java/ImagePropNativeComponentViewManager.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.uimanager; - -import android.view.ViewGroup; -import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.viewmanagers.ImagePropNativeComponentViewManagerDelegate; -import com.facebook.react.viewmanagers.ImagePropNativeComponentViewManagerInterface; - -public class ImagePropNativeComponentViewManager extends SimpleViewManager - implements ImagePropNativeComponentViewManagerInterface { - - public static final String REACT_CLASS = "ImagePropNativeComponentView"; - - @Override - public String getName() { - return REACT_CLASS; - } - - private void test() { - ImagePropNativeComponentViewManagerDelegate - delegate = new ImagePropNativeComponentViewManagerDelegate<>(this); - } - - @Override - public ViewGroup createViewInstance(ThemedReactContext context) { - throw new IllegalStateException(); - } - - @Override - public void setThumbImage(ViewGroup view, ReadableMap value) {} -} diff --git a/packages/react-native-codegen/buck_tests/java/IntegerPropNativeComponentViewManager.java b/packages/react-native-codegen/buck_tests/java/IntegerPropNativeComponentViewManager.java deleted file mode 100644 index 7c24b7206312..000000000000 --- a/packages/react-native-codegen/buck_tests/java/IntegerPropNativeComponentViewManager.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.uimanager; - -import android.view.ViewGroup; -import com.facebook.react.viewmanagers.IntegerPropNativeComponentViewManagerDelegate; -import com.facebook.react.viewmanagers.IntegerPropNativeComponentViewManagerInterface; - -public class IntegerPropNativeComponentViewManager extends SimpleViewManager - implements IntegerPropNativeComponentViewManagerInterface { - - public static final String REACT_CLASS = "IntegerPropNativeComponentView"; - - @Override - public String getName() { - return REACT_CLASS; - } - - private void test() { - IntegerPropNativeComponentViewManagerDelegate - delegate = new IntegerPropNativeComponentViewManagerDelegate<>(this); - } - - @Override - public ViewGroup createViewInstance(ThemedReactContext context) { - throw new IllegalStateException(); - } - - @Override - public void setProgress1(ViewGroup view, int value) {} - - @Override - public void setProgress2(ViewGroup view, int value) {} - - @Override - public void setProgress3(ViewGroup view, int value) {} -} diff --git a/packages/react-native-codegen/buck_tests/java/InterfaceOnlyNativeComponentViewManager.java b/packages/react-native-codegen/buck_tests/java/InterfaceOnlyNativeComponentViewManager.java deleted file mode 100644 index a14f8d1e7fb1..000000000000 --- a/packages/react-native-codegen/buck_tests/java/InterfaceOnlyNativeComponentViewManager.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.uimanager; - -import android.view.ViewGroup; -import com.facebook.react.viewmanagers.InterfaceOnlyNativeComponentViewManagerDelegate; -import com.facebook.react.viewmanagers.InterfaceOnlyNativeComponentViewManagerInterface; - -public class InterfaceOnlyNativeComponentViewManager extends SimpleViewManager - implements InterfaceOnlyNativeComponentViewManagerInterface { - - public static final String REACT_CLASS = "InterfaceOnlyNativeComponentView"; - - @Override - public String getName() { - return REACT_CLASS; - } - - private void test() { - InterfaceOnlyNativeComponentViewManagerDelegate< - ViewGroup, InterfaceOnlyNativeComponentViewManager> - delegate = new InterfaceOnlyNativeComponentViewManagerDelegate<>(this); - } - - @Override - public ViewGroup createViewInstance(ThemedReactContext context) { - throw new IllegalStateException(); - } - - @Override - public void setTitle(ViewGroup view, String value) {} -} diff --git a/packages/react-native-codegen/buck_tests/java/MultiNativePropNativeComponentViewManager.java b/packages/react-native-codegen/buck_tests/java/MultiNativePropNativeComponentViewManager.java deleted file mode 100644 index 776213db5a56..000000000000 --- a/packages/react-native-codegen/buck_tests/java/MultiNativePropNativeComponentViewManager.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.uimanager; - -import android.view.ViewGroup; -import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.viewmanagers.MultiNativePropNativeComponentViewManagerDelegate; -import com.facebook.react.viewmanagers.MultiNativePropNativeComponentViewManagerInterface; - -public class MultiNativePropNativeComponentViewManager extends SimpleViewManager - implements MultiNativePropNativeComponentViewManagerInterface { - - public static final String REACT_CLASS = "MultiNativePropNativeComponentView"; - - @Override - public String getName() { - return REACT_CLASS; - } - - private void test() { - MultiNativePropNativeComponentViewManagerDelegate< - ViewGroup, MultiNativePropNativeComponentViewManager> - delegate = new MultiNativePropNativeComponentViewManagerDelegate<>(this); - } - - @Override - public ViewGroup createViewInstance(ThemedReactContext context) { - throw new IllegalStateException(); - } - - @Override - public void setThumbImage(ViewGroup view, ReadableMap value) {} - - @Override - public void setColor(ViewGroup view, Integer value) {} - - @Override - public void setThumbTintColor(ViewGroup view, Integer value) {} - - @Override - public void setPoint(ViewGroup view, ReadableMap value) {} -} diff --git a/packages/react-native-codegen/buck_tests/java/NoPropsNoEventsNativeComponentViewManager.java b/packages/react-native-codegen/buck_tests/java/NoPropsNoEventsNativeComponentViewManager.java deleted file mode 100644 index 2055db426626..000000000000 --- a/packages/react-native-codegen/buck_tests/java/NoPropsNoEventsNativeComponentViewManager.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.uimanager; - -import android.view.ViewGroup; -import com.facebook.react.viewmanagers.NoPropsNoEventsNativeComponentViewManagerDelegate; -import com.facebook.react.viewmanagers.NoPropsNoEventsNativeComponentViewManagerInterface; - -public class NoPropsNoEventsNativeComponentViewManager extends SimpleViewManager - implements NoPropsNoEventsNativeComponentViewManagerInterface { - - public static final String REACT_CLASS = "NoPropsNoEventsNativeComponentView"; - - @Override - public String getName() { - return REACT_CLASS; - } - - private void test() { - NoPropsNoEventsNativeComponentViewManagerDelegate< - ViewGroup, NoPropsNoEventsNativeComponentViewManager> - delegate = new NoPropsNoEventsNativeComponentViewManagerDelegate<>(this); - } - - @Override - public ViewGroup createViewInstance(ThemedReactContext context) { - throw new IllegalStateException(); - } -} diff --git a/packages/react-native-codegen/buck_tests/java/ObjectPropsNativeComponentManager.java b/packages/react-native-codegen/buck_tests/java/ObjectPropsNativeComponentManager.java deleted file mode 100644 index 592f9050560a..000000000000 --- a/packages/react-native-codegen/buck_tests/java/ObjectPropsNativeComponentManager.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.uimanager; - -import android.view.ViewGroup; -import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.viewmanagers.ObjectPropsNativeComponentManagerDelegate; -import com.facebook.react.viewmanagers.ObjectPropsNativeComponentManagerInterface; - -public class ObjectPropsNativeComponentManager extends SimpleViewManager - implements ObjectPropsNativeComponentManagerInterface { - - public static final String REACT_CLASS = "ObjectPropsNativeComponent"; - - @Override - public String getName() { - return REACT_CLASS; - } - - private void test() { - ObjectPropsNativeComponentManagerDelegate - delegate = new ObjectPropsNativeComponentManagerDelegate<>(this); - } - - @Override - public ViewGroup createViewInstance(ThemedReactContext context) { - throw new IllegalStateException(); - } - - @Override - public void setObjectProp(ViewGroup view, ReadableMap value) {} - - @Override - public void setObjectArrayProp(ViewGroup view, ReadableMap value) {} - - @Override - public void setObjectPrimitiveRequiredProp(ViewGroup view, ReadableMap value) {} -} diff --git a/packages/react-native-codegen/buck_tests/java/PointPropNativeComponentViewManager.java b/packages/react-native-codegen/buck_tests/java/PointPropNativeComponentViewManager.java deleted file mode 100644 index 63383fe8d4ec..000000000000 --- a/packages/react-native-codegen/buck_tests/java/PointPropNativeComponentViewManager.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.uimanager; - -import android.view.ViewGroup; -import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.viewmanagers.PointPropNativeComponentViewManagerDelegate; -import com.facebook.react.viewmanagers.PointPropNativeComponentViewManagerInterface; - -public class PointPropNativeComponentViewManager extends SimpleViewManager - implements PointPropNativeComponentViewManagerInterface { - - public static final String REACT_CLASS = "PointPropNativeComponentView"; - - @Override - public String getName() { - return REACT_CLASS; - } - - private void test() { - PointPropNativeComponentViewManagerDelegate - delegate = new PointPropNativeComponentViewManagerDelegate<>(this); - } - - @Override - public ViewGroup createViewInstance(ThemedReactContext context) { - throw new IllegalStateException(); - } - - @Override - public void setStartPoint(ViewGroup view, ReadableMap value) {} -} diff --git a/packages/react-native-codegen/buck_tests/java/StringPropNativeComponentViewManager.java b/packages/react-native-codegen/buck_tests/java/StringPropNativeComponentViewManager.java deleted file mode 100644 index 15e10043d54a..000000000000 --- a/packages/react-native-codegen/buck_tests/java/StringPropNativeComponentViewManager.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.uimanager; - -import android.view.ViewGroup; -import com.facebook.react.viewmanagers.StringPropNativeComponentViewManagerDelegate; -import com.facebook.react.viewmanagers.StringPropNativeComponentViewManagerInterface; - -public class StringPropNativeComponentViewManager extends SimpleViewManager - implements StringPropNativeComponentViewManagerInterface { - - public static final String REACT_CLASS = "StringPropNativeComponentView"; - - @Override - public String getName() { - return REACT_CLASS; - } - - private void test() { - StringPropNativeComponentViewManagerDelegate - delegate = new StringPropNativeComponentViewManagerDelegate<>(this); - } - - @Override - public ViewGroup createViewInstance(ThemedReactContext context) { - throw new IllegalStateException(); - } - - @Override - public void setPlaceholder(ViewGroup view, String value) {} - - @Override - public void setDefaultValue(ViewGroup view, String value) {} -} diff --git a/packages/react-native-codegen/e2e/__test_fixtures__/components/ArrayPropsNativeComponent.js b/packages/react-native-codegen/e2e/__test_fixtures__/components/ArrayPropsNativeComponent.js deleted file mode 100644 index b65f3ce50b39..000000000000 --- a/packages/react-native-codegen/e2e/__test_fixtures__/components/ArrayPropsNativeComponent.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * 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 - * @flow strict-local - */ - -import type {PointValue} from '../../../../../Libraries/StyleSheet/StyleSheetTypes'; -import type {ColorValue} from '../../../../../Libraries/StyleSheet/StyleSheet'; -import type {ImageSource} from '../../../../../Libraries/Image/ImageSource'; -import type { - Int32, - Float, - WithDefault, -} from '../../../../../Libraries/Types/CodegenTypes'; -import type {ViewProps} from '../../../../../Libraries/Components/View/ViewPropTypes'; -import codegenNativeComponent from '../../../../../Libraries/Utilities/codegenNativeComponent'; -import type {HostComponent} from '../../../../../Libraries/Renderer/shims/ReactNativeTypes'; - -type NativeProps = $ReadOnly<{| - ...ViewProps, - - // Props - names?: $ReadOnlyArray, - disableds?: $ReadOnlyArray, - progress?: $ReadOnlyArray, - radii?: $ReadOnlyArray, - colors?: $ReadOnlyArray, - srcs?: $ReadOnlyArray, - points?: $ReadOnlyArray, - // TODO(T104760003) Fix EdgeInsetsValue in codegen - // edgeInsets?: $ReadOnlyArray, - sizes?: WithDefault<$ReadOnlyArray<'small' | 'large'>, 'small'>, - object?: $ReadOnlyArray<$ReadOnly<{|prop: string|}>>, - arrayOfObjects?: $ReadOnlyArray<$ReadOnly<{|prop1: Float, prop2: Int32|}>>, -|}>; - -export default (codegenNativeComponent( - 'ArrayPropsNativeComponentView', -): HostComponent); diff --git a/packages/react-native-codegen/e2e/__test_fixtures__/components/BooleanPropNativeComponent.js b/packages/react-native-codegen/e2e/__test_fixtures__/components/BooleanPropNativeComponent.js deleted file mode 100644 index 8a1c8ae458e5..000000000000 --- a/packages/react-native-codegen/e2e/__test_fixtures__/components/BooleanPropNativeComponent.js +++ /dev/null @@ -1,26 +0,0 @@ -/** - * 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 - * @flow strict-local - */ - -import type {WithDefault} from '../../../../../Libraries/Types/CodegenTypes'; -import type {ViewProps} from '../../../../../Libraries/Components/View/ViewPropTypes'; -import codegenNativeComponent from '../../../../../Libraries/Utilities/codegenNativeComponent'; -import type {HostComponent} from '../../../../../Libraries/Renderer/shims/ReactNativeTypes'; - -type NativeProps = $ReadOnly<{| - ...ViewProps, - - // Props - disabled?: WithDefault, - disabledNullable?: WithDefault, -|}>; - -export default (codegenNativeComponent( - 'BooleanPropNativeComponentView', -): HostComponent); diff --git a/packages/react-native-codegen/e2e/__test_fixtures__/components/ColorPropNativeComponent.js b/packages/react-native-codegen/e2e/__test_fixtures__/components/ColorPropNativeComponent.js deleted file mode 100644 index a01dedbd75ec..000000000000 --- a/packages/react-native-codegen/e2e/__test_fixtures__/components/ColorPropNativeComponent.js +++ /dev/null @@ -1,25 +0,0 @@ -/** - * 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 - * @flow strict-local - */ - -import type {ColorValue} from '../../../../../Libraries/StyleSheet/StyleSheet'; -import type {ViewProps} from '../../../../../Libraries/Components/View/ViewPropTypes'; -import codegenNativeComponent from '../../../../../Libraries/Utilities/codegenNativeComponent'; -import type {HostComponent} from '../../../../../Libraries/Renderer/shims/ReactNativeTypes'; - -type NativeProps = $ReadOnly<{| - ...ViewProps, - - // Props - tintColor?: ColorValue, -|}>; - -export default (codegenNativeComponent( - 'ColorPropNativeComponentView', -): HostComponent); diff --git a/packages/react-native-codegen/e2e/__test_fixtures__/components/EdgeInsetsPropNativeComponent.js b/packages/react-native-codegen/e2e/__test_fixtures__/components/EdgeInsetsPropNativeComponent.js deleted file mode 100644 index a30e80d93419..000000000000 --- a/packages/react-native-codegen/e2e/__test_fixtures__/components/EdgeInsetsPropNativeComponent.js +++ /dev/null @@ -1,25 +0,0 @@ -/** - * 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 - * @flow strict-local - */ - -import type {ViewProps} from '../../../../../Libraries/Components/View/ViewPropTypes'; -import codegenNativeComponent from '../../../../../Libraries/Utilities/codegenNativeComponent'; -import type {HostComponent} from '../../../../../Libraries/Renderer/shims/ReactNativeTypes'; - -type NativeProps = $ReadOnly<{| - ...ViewProps, - - // Props - // TODO(T104760003) Fix EdgeInsetsValue in codegen - // contentInset?: EdgeInsetsValue, -|}>; - -export default (codegenNativeComponent( - 'EdgeInsetsPropNativeComponentView', -): HostComponent); diff --git a/packages/react-native-codegen/e2e/__test_fixtures__/components/EnumPropNativeComponent.js b/packages/react-native-codegen/e2e/__test_fixtures__/components/EnumPropNativeComponent.js deleted file mode 100644 index b8f113e5df39..000000000000 --- a/packages/react-native-codegen/e2e/__test_fixtures__/components/EnumPropNativeComponent.js +++ /dev/null @@ -1,26 +0,0 @@ -/** - * 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 - * @flow strict-local - */ - -import type {WithDefault} from '../../../../../Libraries/Types/CodegenTypes'; -import type {ViewProps} from '../../../../../Libraries/Components/View/ViewPropTypes'; -import codegenNativeComponent from '../../../../../Libraries/Utilities/codegenNativeComponent'; -import type {HostComponent} from '../../../../../Libraries/Renderer/shims/ReactNativeTypes'; - -type NativeProps = $ReadOnly<{| - ...ViewProps, - - // Props - alignment?: WithDefault<'top' | 'center' | 'bottom-right', 'center'>, - intervals?: WithDefault<0 | 15 | 30 | 60, 0>, -|}>; - -export default (codegenNativeComponent( - 'EnumPropNativeComponentView', -): HostComponent); diff --git a/packages/react-native-codegen/e2e/__test_fixtures__/components/EventNestedObjectPropsNativeComponent.js b/packages/react-native-codegen/e2e/__test_fixtures__/components/EventNestedObjectPropsNativeComponent.js deleted file mode 100644 index 50d336cb9ce7..000000000000 --- a/packages/react-native-codegen/e2e/__test_fixtures__/components/EventNestedObjectPropsNativeComponent.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 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 - * @flow strict-local - */ - -import type { - Int32, - BubblingEventHandler, - WithDefault, -} from '../../../../../Libraries/Types/CodegenTypes'; -import type {ViewProps} from '../../../../../Libraries/Components/View/ViewPropTypes'; -import codegenNativeComponent from '../../../../../Libraries/Utilities/codegenNativeComponent'; -import type {HostComponent} from '../../../../../Libraries/Renderer/shims/ReactNativeTypes'; - -type OnChangeEvent = $ReadOnly<{| - location: { - source: {url: string, ...}, - x: Int32, - y: Int32, - ... - }, -|}>; - -type NativeProps = $ReadOnly<{| - ...ViewProps, - - // Props - disabled?: WithDefault, - - // Events - onChange?: ?BubblingEventHandler, -|}>; - -export default (codegenNativeComponent( - 'EventNestedObjectPropsNativeComponentView', -): HostComponent); diff --git a/packages/react-native-codegen/e2e/__test_fixtures__/components/EventPropsNativeComponent.js b/packages/react-native-codegen/e2e/__test_fixtures__/components/EventPropsNativeComponent.js deleted file mode 100644 index 77193d4452e7..000000000000 --- a/packages/react-native-codegen/e2e/__test_fixtures__/components/EventPropsNativeComponent.js +++ /dev/null @@ -1,63 +0,0 @@ -/** - * 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 - * @flow strict-local - */ - -import type { - Int32, - Float, - BubblingEventHandler, - DirectEventHandler, - WithDefault, -} from '../../../../../Libraries/Types/CodegenTypes'; -import type {ViewProps} from '../../../../../Libraries/Components/View/ViewPropTypes'; -import codegenNativeComponent from '../../../../../Libraries/Utilities/codegenNativeComponent'; -import type {HostComponent} from '../../../../../Libraries/Renderer/shims/ReactNativeTypes'; - -type OnChangeEvent = $ReadOnly<{| - value: boolean, - source?: string, - progress: ?Int32, - scale?: ?Float, -|}>; - -type OnEventDirect = $ReadOnly<{| - value: boolean, -|}>; - -type OnOrientationChangeEvent = $ReadOnly<{| - orientation: 'landscape' | 'portrait', -|}>; - -type NativeProps = $ReadOnly<{| - ...ViewProps, - - // Props - disabled?: WithDefault, - - // Events - onChange?: ?BubblingEventHandler, - onEventDirect?: ?DirectEventHandler, - onEventDirectWithPaperName?: ?DirectEventHandler< - OnEventDirect, - 'paperDirectName', - >, - onOrientationChange?: ?DirectEventHandler< - OnOrientationChangeEvent, - 'paperBubblingName', - >, - onEnd?: ?BubblingEventHandler, - onEventBubblingWithPaperName?: ?BubblingEventHandler< - null, - 'paperBubblingName', - >, -|}>; - -export default (codegenNativeComponent( - 'EventPropsNativeComponentView', -): HostComponent); diff --git a/packages/react-native-codegen/e2e/__test_fixtures__/components/FloatPropsNativeComponent.js b/packages/react-native-codegen/e2e/__test_fixtures__/components/FloatPropsNativeComponent.js deleted file mode 100644 index 3793ef93284d..000000000000 --- a/packages/react-native-codegen/e2e/__test_fixtures__/components/FloatPropsNativeComponent.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 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 - * @flow strict-local - */ - -import type { - WithDefault, - Float, -} from '../../../../../Libraries/Types/CodegenTypes'; -import type {ViewProps} from '../../../../../Libraries/Components/View/ViewPropTypes'; -import codegenNativeComponent from '../../../../../Libraries/Utilities/codegenNativeComponent'; -import type {HostComponent} from '../../../../../Libraries/Renderer/shims/ReactNativeTypes'; - -type NativeProps = $ReadOnly<{| - ...ViewProps, - - // Props - blurRadius: Float, - blurRadius2?: WithDefault, - blurRadius3?: WithDefault, - blurRadius4?: WithDefault, - blurRadius5?: WithDefault, - blurRadius6?: WithDefault, - blurRadiusNullable?: WithDefault, -|}>; - -export default (codegenNativeComponent( - 'FloatPropsNativeComponentView', -): HostComponent); diff --git a/packages/react-native-codegen/e2e/__test_fixtures__/components/ImagePropNativeComponent.js b/packages/react-native-codegen/e2e/__test_fixtures__/components/ImagePropNativeComponent.js deleted file mode 100644 index f90a857afd80..000000000000 --- a/packages/react-native-codegen/e2e/__test_fixtures__/components/ImagePropNativeComponent.js +++ /dev/null @@ -1,25 +0,0 @@ -/** - * 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 - * @flow strict-local - */ - -import type {ImageSource} from '../../../../../Libraries/Image/ImageSource'; -import type {ViewProps} from '../../../../../Libraries/Components/View/ViewPropTypes'; -import codegenNativeComponent from '../../../../../Libraries/Utilities/codegenNativeComponent'; -import type {HostComponent} from '../../../../../Libraries/Renderer/shims/ReactNativeTypes'; - -type NativeProps = $ReadOnly<{| - ...ViewProps, - - // Props - thumbImage?: ImageSource, -|}>; - -export default (codegenNativeComponent( - 'ImagePropNativeComponentView', -): HostComponent); diff --git a/packages/react-native-codegen/e2e/__test_fixtures__/components/IntegerPropNativeComponent.js b/packages/react-native-codegen/e2e/__test_fixtures__/components/IntegerPropNativeComponent.js deleted file mode 100644 index f9cd8dadc9fe..000000000000 --- a/packages/react-native-codegen/e2e/__test_fixtures__/components/IntegerPropNativeComponent.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 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 - * @flow strict-local - */ - -import type { - WithDefault, - Int32, -} from '../../../../../Libraries/Types/CodegenTypes'; -import type {ViewProps} from '../../../../../Libraries/Components/View/ViewPropTypes'; -import codegenNativeComponent from '../../../../../Libraries/Utilities/codegenNativeComponent'; -import type {HostComponent} from '../../../../../Libraries/Renderer/shims/ReactNativeTypes'; - -type NativeProps = $ReadOnly<{| - ...ViewProps, - - // Props - progress1?: WithDefault, - progress2?: WithDefault, - progress3?: WithDefault, -|}>; - -export default (codegenNativeComponent( - 'IntegerPropNativeComponentView', -): HostComponent); diff --git a/packages/react-native-codegen/e2e/__test_fixtures__/components/InterfaceOnlyNativeComponent.js b/packages/react-native-codegen/e2e/__test_fixtures__/components/InterfaceOnlyNativeComponent.js deleted file mode 100644 index ec192240ddeb..000000000000 --- a/packages/react-native-codegen/e2e/__test_fixtures__/components/InterfaceOnlyNativeComponent.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 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 - * @flow strict-local - */ - -import type { - BubblingEventHandler, - WithDefault, -} from '../../../../../Libraries/Types/CodegenTypes'; -import type {ViewProps} from '../../../../../Libraries/Components/View/ViewPropTypes'; -import codegenNativeComponent from '../../../../../Libraries/Utilities/codegenNativeComponent'; -import type {HostComponent} from '../../../../../Libraries/Renderer/shims/ReactNativeTypes'; - -type NativeProps = $ReadOnly<{| - ...ViewProps, - - // Props - title?: WithDefault, - - // Events - onChange?: ?BubblingEventHandler<$ReadOnly<{|value: boolean|}>>, -|}>; - -export default (codegenNativeComponent( - 'InterfaceOnlyNativeComponentView', - { - interfaceOnly: true, - paperComponentName: 'RCTInterfaceOnlyComponent', - }, -): HostComponent); diff --git a/packages/react-native-codegen/e2e/__test_fixtures__/components/MultiNativePropNativeComponent.js b/packages/react-native-codegen/e2e/__test_fixtures__/components/MultiNativePropNativeComponent.js deleted file mode 100644 index a1a2b601d7f4..000000000000 --- a/packages/react-native-codegen/e2e/__test_fixtures__/components/MultiNativePropNativeComponent.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 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 - * @flow strict-local - */ - -import type {PointValue} from '../../../../../Libraries/StyleSheet/StyleSheetTypes'; -import type {ColorValue} from '../../../../../Libraries/StyleSheet/StyleSheet'; -import type {ImageSource} from '../../../../../Libraries/Image/ImageSource'; -import type {ViewProps} from '../../../../../Libraries/Components/View/ViewPropTypes'; -import codegenNativeComponent from '../../../../../Libraries/Utilities/codegenNativeComponent'; -import type {HostComponent} from '../../../../../Libraries/Renderer/shims/ReactNativeTypes'; - -type NativeProps = $ReadOnly<{| - ...ViewProps, - - // Props - thumbImage?: ImageSource, - color?: ColorValue, - thumbTintColor?: ColorValue, - point?: PointValue, -|}>; - -export default (codegenNativeComponent( - 'MultiNativePropNativeComponentView', -): HostComponent); diff --git a/packages/react-native-codegen/e2e/__test_fixtures__/components/NoPropsNoEventsNativeComponent.js b/packages/react-native-codegen/e2e/__test_fixtures__/components/NoPropsNoEventsNativeComponent.js deleted file mode 100644 index 2beb9ecb9cd6..000000000000 --- a/packages/react-native-codegen/e2e/__test_fixtures__/components/NoPropsNoEventsNativeComponent.js +++ /dev/null @@ -1,23 +0,0 @@ -/** - * 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 - * @flow strict-local - */ - -import type {ViewProps} from '../../../../../Libraries/Components/View/ViewPropTypes'; -import codegenNativeComponent from '../../../../../Libraries/Utilities/codegenNativeComponent'; -import type {HostComponent} from '../../../../../Libraries/Renderer/shims/ReactNativeTypes'; - -type NativeProps = $ReadOnly<{| - ...ViewProps, - - // No Props or events -|}>; - -export default (codegenNativeComponent( - 'NoPropsNoEventsNativeComponentView', -): HostComponent); diff --git a/packages/react-native-codegen/e2e/__test_fixtures__/components/ObjectPropsNativeComponent.js b/packages/react-native-codegen/e2e/__test_fixtures__/components/ObjectPropsNativeComponent.js deleted file mode 100644 index 8d7391970a35..000000000000 --- a/packages/react-native-codegen/e2e/__test_fixtures__/components/ObjectPropsNativeComponent.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * 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 - * @flow strict-local - */ - -import type {ViewProps} from '../../../../../Libraries/Components/View/ViewPropTypes'; -import type {ImageSource} from '../../../../../Libraries/Image/ImageSource'; -import type {PointValue} from '../../../../../Libraries/StyleSheet/StyleSheetTypes'; -import type {ColorValue} from '../../../../../Libraries/StyleSheet/StyleSheet'; -import type { - Int32, - Float, - WithDefault, -} from '../../../../../Libraries/Types/CodegenTypes'; -import codegenNativeComponent from '../../../../../Libraries/Utilities/codegenNativeComponent'; -import type {HostComponent} from '../../../../../Libraries/Renderer/shims/ReactNativeTypes'; - -type ObjectArrayPropType = $ReadOnly<{| - array: $ReadOnlyArray, -|}>; - -type NativeProps = $ReadOnly<{| - ...ViewProps, - - // Props - objectProp?: $ReadOnly<{| - stringProp?: WithDefault, - booleanProp: boolean, - floatProp: Float, - intProp: Int32, - stringEnumProp?: WithDefault<'small' | 'large', 'small'>, - intEnumProp?: WithDefault<0 | 1, 0>, - |}>, - objectArrayProp: ObjectArrayPropType, - objectPrimitiveRequiredProp: $ReadOnly<{| - image: ImageSource, - color?: ColorValue, - point: ?PointValue, - |}>, -|}>; - -export default (codegenNativeComponent( - 'ObjectPropsNativeComponent', -): HostComponent); diff --git a/packages/react-native-codegen/e2e/__test_fixtures__/components/PointPropNativeComponent.js b/packages/react-native-codegen/e2e/__test_fixtures__/components/PointPropNativeComponent.js deleted file mode 100644 index ad6edbac37bc..000000000000 --- a/packages/react-native-codegen/e2e/__test_fixtures__/components/PointPropNativeComponent.js +++ /dev/null @@ -1,25 +0,0 @@ -/** - * 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 - * @flow strict-local - */ - -import type {PointValue} from '../../../../../Libraries/StyleSheet/StyleSheetTypes'; -import type {ViewProps} from '../../../../../Libraries/Components/View/ViewPropTypes'; -import codegenNativeComponent from '../../../../../Libraries/Utilities/codegenNativeComponent'; -import type {HostComponent} from '../../../../../Libraries/Renderer/shims/ReactNativeTypes'; - -type NativeProps = $ReadOnly<{| - ...ViewProps, - - // Props - startPoint?: PointValue, -|}>; - -export default (codegenNativeComponent( - 'PointPropNativeComponentView', -): HostComponent); diff --git a/packages/react-native-codegen/e2e/__test_fixtures__/components/StringPropNativeComponent.js b/packages/react-native-codegen/e2e/__test_fixtures__/components/StringPropNativeComponent.js deleted file mode 100644 index 478375d6e2df..000000000000 --- a/packages/react-native-codegen/e2e/__test_fixtures__/components/StringPropNativeComponent.js +++ /dev/null @@ -1,26 +0,0 @@ -/** - * 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 - * @flow strict-local - */ - -import type {WithDefault} from '../../../../../Libraries/Types/CodegenTypes'; -import type {ViewProps} from '../../../../../Libraries/Components/View/ViewPropTypes'; -import codegenNativeComponent from '../../../../../Libraries/Utilities/codegenNativeComponent'; -import type {HostComponent} from '../../../../../Libraries/Renderer/shims/ReactNativeTypes'; - -type NativeProps = $ReadOnly<{| - ...ViewProps, - - // Props - placeholder?: WithDefault, - defaultValue?: string, -|}>; - -export default (codegenNativeComponent( - 'StringPropNativeComponentView', -): HostComponent); diff --git a/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeArrayTurboModule.js b/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeArrayTurboModule.js deleted file mode 100644 index 5b7d621a6557..000000000000 --- a/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeArrayTurboModule.js +++ /dev/null @@ -1,25 +0,0 @@ -/** - * 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 - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export type ArrayType = string; -type AnotherArray = Array; - -export interface Spec extends TurboModule { - +getArray: (a: Array) => Array; - +getReadOnlyArray: (a: Array) => $ReadOnlyArray; - +getArrayWithAlias: (a: AnotherArray, b: Array) => AnotherArray; -} - -export default (TurboModuleRegistry.getEnforcing( - 'SampleTurboModule', -): Spec); diff --git a/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeBooleanTurboModule.js b/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeBooleanTurboModule.js deleted file mode 100644 index a898b1302883..000000000000 --- a/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeBooleanTurboModule.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export type Boolean = boolean; -type AnotherBoolean = Boolean; - -export interface Spec extends TurboModule { - +getBoolean: (arg: boolean) => boolean; - +getBooleanWithAlias: (arg: Boolean) => AnotherBoolean; -} - -export default (TurboModuleRegistry.getEnforcing( - 'SampleTurboModule', -): Spec); diff --git a/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeCallbackTurboModule.js b/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeCallbackTurboModule.js deleted file mode 100644 index 71bb14cf72f8..000000000000 --- a/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeCallbackTurboModule.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export type String = string; -type CB = (value: String) => void; - -export interface Spec extends TurboModule { - +getValueWithCallback: (callback: (value: string) => void) => void; - +getValueWithCallbackWithAlias: (c: CB) => void; -} - -export default (TurboModuleRegistry.getEnforcing( - 'SampleTurboModule', -): Spec); diff --git a/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeNullableTurboModule.js b/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeNullableTurboModule.js deleted file mode 100644 index e56e0346ad1d..000000000000 --- a/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeNullableTurboModule.js +++ /dev/null @@ -1,25 +0,0 @@ -/** - * 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 - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export interface Spec extends TurboModule { - +getBool: (a: ?boolean) => ?boolean; - +getNumber: (a: ?number) => ?number; - +getString: (a: ?number) => ?string; - +getArray: (a: ?Array) => ?Array; - +getObject: (a: ?Object) => ?Object; - +getValueWithPromise: () => ?Promise; -} - -export default (TurboModuleRegistry.getEnforcing( - 'SampleTurboModule', -): Spec); diff --git a/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeNumberTurboModule.js b/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeNumberTurboModule.js deleted file mode 100644 index e47a31a2d3ed..000000000000 --- a/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeNumberTurboModule.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export type Number = number; -type AnotherNumber = Number; - -export interface Spec extends TurboModule { - +getNumber: (arg: number) => number; - +getNumberWithAlias: (arg: Number) => AnotherNumber; -} - -export default (TurboModuleRegistry.getEnforcing( - 'SampleTurboModule', -): Spec); diff --git a/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeObjectTurboModule.js b/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeObjectTurboModule.js deleted file mode 100644 index e3b2d5df8c5a..000000000000 --- a/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeObjectTurboModule.js +++ /dev/null @@ -1,63 +0,0 @@ -/** - * 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 - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export type GenericObject = Object; -type AnotherGenericObject = GenericObject; - -export interface Spec extends TurboModule { - +getGenericObject: (arg: Object) => Object; - +getGenericObjectReadOnly: (arg: Object) => $ReadOnly<{|a: string|}>; - +getGenericObjectWithAlias: (arg: GenericObject) => AnotherGenericObject; - +difficultObject: (A: {| - D: boolean, - E: {| - D: boolean, - E: number, - F: string, - |}, - F: string, - |}) => {| - D: boolean, - E: {| - D: boolean, - E: {| - D: boolean, - E: number, - F: string, - |}, - F: string, - |}, - F: string, - |}; - +getConstants: () => {| - D: boolean, - E: {| - D: boolean, - E: {| - D: boolean, - E: {| - D: boolean, - E: number, - F: string, - |}, - F: string, - |}, - F: string, - |}, - F: string, - |}; -} - -export default (TurboModuleRegistry.getEnforcing( - 'SampleTurboModule', -): Spec); diff --git a/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeOptionalObjectTurboModule.js b/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeOptionalObjectTurboModule.js deleted file mode 100644 index 692bd52ff73c..000000000000 --- a/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeOptionalObjectTurboModule.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 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 - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export interface Spec extends TurboModule { - +getConstants: () => {| - D?: ?boolean, - A?: Array, - E?: ?{| - D?: ?boolean, - E?: ?{| - D?: ?boolean, - E?: ?{| - D?: boolean, - E?: number, - F?: string, - |}, - F?: string, - |}, - F?: string, - |}, - F?: string, - |}; -} - -export default (TurboModuleRegistry.getEnforcing( - 'SampleTurboModule', -): Spec); diff --git a/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativePromiseTurboModule.js b/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativePromiseTurboModule.js deleted file mode 100644 index 610b3bab899a..000000000000 --- a/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativePromiseTurboModule.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export type String = string; -type AnotherPromise = Promise; - -export interface Spec extends TurboModule { - +getValueWithPromise: (error: boolean) => Promise; - +getValueWithPromiseWithAlias: (arg: String) => AnotherPromise; -} - -export default (TurboModuleRegistry.getEnforcing( - 'SampleTurboModule', -): Spec); diff --git a/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeSampleTurboModule.js b/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeSampleTurboModule.js deleted file mode 100644 index 12496b4ec75d..000000000000 --- a/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeSampleTurboModule.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * 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 - */ - -import type { - RootTag, - TurboModule, -} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -type Animal = {| - name: string, -|}; - -export interface Spec extends TurboModule { - // Exported methods. - +getConstants: () => {| - const1: boolean, - const2: number, - const3: string, - |}; - +voidFunc: () => void; - +getBool: (arg: boolean) => boolean; - +getNumber: (arg: number) => number; - +getString: (arg: string) => string; - +getArray: (arg: Array) => Array; - +getObject: (arg: Object) => Object; - +getObjectShape: (arg: {|prop: number|}) => {|prop: number|}; - +getAlias: (arg: Animal) => Animal; - +getRootTag: (arg: RootTag) => RootTag; - +getValue: ( - x: number, - getValuegetValuegetValuegetValuegetValuey: string, - z: Object, - ) => Object; - +getValueWithCallback: (callback: (value: string) => void) => void; - +getValueWithPromise: (error: boolean) => Promise; -} - -export default (TurboModuleRegistry.getEnforcing( - 'SampleTurboModule', -): Spec); diff --git a/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeSampleTurboModuleArrays.js b/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeSampleTurboModuleArrays.js deleted file mode 100644 index d320bd2fb338..000000000000 --- a/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeSampleTurboModuleArrays.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * 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 - */ - -import type { - RootTag, - TurboModule, -} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -type Animal = {| - name: string, -|}; - -export interface Spec extends TurboModule { - // Exported methods. - +getConstants: () => {| - const1: Array, - const2: Array, - const3: Array, - id?: Array, - |}; - +voidFunc: () => void; - +getBool: (id: Array) => Array; - +getNumber: (arg: Array) => Array; - +getString: (arg: Array) => Array; - +getArray: (arg: Array>) => Array>; - +getObject: (arg: Array) => Array; - +getObjectShape: (arg: Array<{|prop: number|}>) => Array<{|prop: number|}>; - +getAlias: (arg: Array) => Array; - +getRootTag: (arg: Array) => Array; - +getValue: ( - x: Array, - y: Array, - z: Array, - ) => Array; - +getValueWithCallback: (callback: (value: Array) => void) => void; - +getValueWithPromise: (error: Array) => Promise>; -} - -export default (TurboModuleRegistry.getEnforcing( - 'SampleTurboModuleArrays', -): Spec); diff --git a/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeSampleTurboModuleNullable.js b/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeSampleTurboModuleNullable.js deleted file mode 100644 index 2a736f08e927..000000000000 --- a/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeSampleTurboModuleNullable.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 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 - */ - -import type { - RootTag, - TurboModule, -} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -type Animal = ?{| - name: ?string, -|}; - -export interface Spec extends TurboModule { - // Exported methods. - +getConstants: () => {| - const1: ?boolean, - const2: ?number, - const3: ?string, - |}; - +voidFunc: () => void; - +getBool: (arg: ?boolean) => ?boolean; - +getNumber: (arg: ?number) => ?number; - +getString: (arg: ?string) => ?string; - +getArray: (arg: ?Array) => ?Array; - +getObject: (arg: ?Object) => ?Object; - +getObjectShape: (arg: ?{|prop: ?number|}) => ?{|prop: ?number|}; - +getAlias: (arg: ?Animal) => ?Animal; - +getRootTag: (arg: ?RootTag) => ?RootTag; - +getValue: (x: ?number, y: ?string, z: ?Object) => ?Object; - +getValueWithCallback: (callback: (value: ?string) => void) => void; - +getValueWithPromise: (error: ?boolean) => ?Promise; -} - -export default (TurboModuleRegistry.getEnforcing( - 'SampleTurboModuleNullable', -): Spec); diff --git a/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeSampleTurboModuleNullableAndOptional.js b/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeSampleTurboModuleNullableAndOptional.js deleted file mode 100644 index b8981a22ab2d..000000000000 --- a/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeSampleTurboModuleNullableAndOptional.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 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 - */ - -import type { - RootTag, - TurboModule, -} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -type Animal = ?{| - name?: ?string, -|}; - -export interface Spec extends TurboModule { - // Exported methods. - +getConstants?: () => {| - const1?: ?boolean, - const2?: ?number, - const3?: ?string, - |}; - +voidFunc?: () => void; - +getBool?: (arg?: ?boolean) => ?boolean; - +getNumber?: (arg?: ?number) => ?number; - +getString?: (arg?: ?string) => ?string; - +getArray?: (arg?: ?Array) => ?Array; - +getObject?: (arg?: ?Object) => ?Object; - +getObjectShape?: (arg?: {|prop?: ?number|}) => {|prop?: ?number|}; - +getAlias?: (arg?: ?Animal) => ?Animal; - +getRootTag?: (arg?: ?RootTag) => ?RootTag; - +getValue?: (x?: ?number, y?: ?string, z?: ?Object) => ?Object; - +getValueWithCallback?: (callback?: ?(value?: ?string) => void) => void; - +getValueWithPromise?: (error?: ?boolean) => ?Promise; -} - -export default (TurboModuleRegistry.getEnforcing( - 'SampleTurboModuleNullableAndOptional', -): Spec); diff --git a/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeSampleTurboModuleOptional.js b/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeSampleTurboModuleOptional.js deleted file mode 100644 index d1b56f989388..000000000000 --- a/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeSampleTurboModuleOptional.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 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 - */ - -import type { - RootTag, - TurboModule, -} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -type Animal = {| - name?: string, -|}; - -export interface Spec extends TurboModule { - // Exported methods. - +getConstants?: () => {| - const1?: boolean, - const2?: number, - const3?: string, - |}; - +voidFunc?: () => void; - +getBool?: (arg?: boolean) => boolean; - +getNumber?: (arg?: number) => number; - +getString?: (arg?: string) => string; - +getArray?: (arg?: Array) => Array; - +getObject?: (arg?: Object) => Object; - +getObjectShape?: (arg?: {|prop?: number|}) => {|prop?: number|}; - +getAlias?: (arg?: Animal) => Animal; - +getRootTag?: (arg?: RootTag) => RootTag; - +getValue?: (x?: number, y?: string, z?: Object) => Object; - +getValueWithCallback?: (callback?: (value?: string) => void) => void; - +getValueWithPromise?: (error?: boolean) => Promise; -} - -export default (TurboModuleRegistry.getEnforcing( - 'SampleTurboModuleOptional', -): Spec); diff --git a/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeStringTurboModule.js b/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeStringTurboModule.js deleted file mode 100644 index b78372382b82..000000000000 --- a/packages/react-native-codegen/e2e/__test_fixtures__/modules/NativeStringTurboModule.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export type String = string; -type AnotherString = String; - -export interface Spec extends TurboModule { - +getString: (arg: string) => string; - +getStringWithAlias: (arg: String) => AnotherString; -} - -export default (TurboModuleRegistry.getEnforcing( - 'SampleTurboModule', -): Spec); diff --git a/packages/react-native-codegen/e2e/__tests__/components/GenerateComponentDescriptorH-test.js b/packages/react-native-codegen/e2e/__tests__/components/GenerateComponentDescriptorH-test.js deleted file mode 100644 index 8d35cca3843e..000000000000 --- a/packages/react-native-codegen/e2e/__tests__/components/GenerateComponentDescriptorH-test.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const {parseFile} = require('../../../src/parsers/utils'); -const FlowParser = require('../../../src/parsers/flow'); -const generator = require('../../../src/generators/components/GenerateComponentDescriptorH'); -const fs = require('fs'); - -const FIXTURE_DIR = `${__dirname}/../../__test_fixtures__/components`; - -const fixtures = fs.readdirSync(FIXTURE_DIR); - -fixtures.forEach(fixture => { - it(`GenerateComponentDescriptorH can generate for '${fixture}'`, () => { - const libName = 'RNCodegenModuleFixtures'; - const schema = parseFile( - `${FIXTURE_DIR}/${fixture}`, - FlowParser.buildSchema, - ); - const output = generator.generate(libName, schema); - expect(Object.fromEntries(output)).toMatchSnapshot(); - }); -}); diff --git a/packages/react-native-codegen/e2e/__tests__/components/GenerateComponentHObjCpp-test.js b/packages/react-native-codegen/e2e/__tests__/components/GenerateComponentHObjCpp-test.js deleted file mode 100644 index 89d14fc74a63..000000000000 --- a/packages/react-native-codegen/e2e/__tests__/components/GenerateComponentHObjCpp-test.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const {parseFile} = require('../../../src/parsers/utils'); -const FlowParser = require('../../../src/parsers/flow'); -const generator = require('../../../src/generators/components/GenerateComponentHObjCpp'); -const fs = require('fs'); - -const FIXTURE_DIR = `${__dirname}/../../__test_fixtures__/components`; - -const fixtures = fs.readdirSync(FIXTURE_DIR); - -fixtures.forEach(fixture => { - it(`GenerateComponentHObjCpp can generate for '${fixture}'`, () => { - const libName = 'RNCodegenModuleFixtures'; - const schema = parseFile( - `${FIXTURE_DIR}/${fixture}`, - FlowParser.buildSchema, - ); - const output = generator.generate(libName, schema); - expect(Object.fromEntries(output)).toMatchSnapshot(); - }); -}); diff --git a/packages/react-native-codegen/e2e/__tests__/components/GenerateEventEmitterCpp-test.js b/packages/react-native-codegen/e2e/__tests__/components/GenerateEventEmitterCpp-test.js deleted file mode 100644 index 603c77b56607..000000000000 --- a/packages/react-native-codegen/e2e/__tests__/components/GenerateEventEmitterCpp-test.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const {parseFile} = require('../../../src/parsers/utils'); -const FlowParser = require('../../../src/parsers/flow'); -const generator = require('../../../src/generators/components/GenerateEventEmitterCpp'); -const fs = require('fs'); - -const FIXTURE_DIR = `${__dirname}/../../__test_fixtures__/components`; - -const fixtures = fs.readdirSync(FIXTURE_DIR); - -fixtures.forEach(fixture => { - it(`GenerateEventEmitterCpp can generate for '${fixture}'`, () => { - const libName = 'RNCodegenModuleFixtures'; - const schema = parseFile( - `${FIXTURE_DIR}/${fixture}`, - FlowParser.buildSchema, - ); - const output = generator.generate(libName, schema); - expect(Object.fromEntries(output)).toMatchSnapshot(); - }); -}); diff --git a/packages/react-native-codegen/e2e/__tests__/components/GenerateEventEmitterH-test.js b/packages/react-native-codegen/e2e/__tests__/components/GenerateEventEmitterH-test.js deleted file mode 100644 index 05b1082297cc..000000000000 --- a/packages/react-native-codegen/e2e/__tests__/components/GenerateEventEmitterH-test.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const {parseFile} = require('../../../src/parsers/utils'); -const FlowParser = require('../../../src/parsers/flow'); -const generator = require('../../../src/generators/components/GenerateEventEmitterH'); -const fs = require('fs'); - -const FIXTURE_DIR = `${__dirname}/../../__test_fixtures__/components`; - -const fixtures = fs.readdirSync(FIXTURE_DIR); - -fixtures.forEach(fixture => { - it(`GenerateEventEmitterH can generate for '${fixture}'`, () => { - const libName = 'RNCodegenModuleFixtures'; - const schema = parseFile( - `${FIXTURE_DIR}/${fixture}`, - FlowParser.buildSchema, - ); - const output = generator.generate(libName, schema); - expect(Object.fromEntries(output)).toMatchSnapshot(); - }); -}); diff --git a/packages/react-native-codegen/e2e/__tests__/components/GeneratePropsCpp-test.js b/packages/react-native-codegen/e2e/__tests__/components/GeneratePropsCpp-test.js deleted file mode 100644 index 131d4f4fd668..000000000000 --- a/packages/react-native-codegen/e2e/__tests__/components/GeneratePropsCpp-test.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const {parseFile} = require('../../../src/parsers/utils'); -const FlowParser = require('../../../src/parsers/flow'); -const generator = require('../../../src/generators/components/GeneratePropsCpp'); -const fs = require('fs'); - -const FIXTURE_DIR = `${__dirname}/../../__test_fixtures__/components`; - -const fixtures = fs.readdirSync(FIXTURE_DIR); - -fixtures.forEach(fixture => { - it(`GeneratePropsCpp can generate for '${fixture}'`, () => { - const libName = 'RNCodegenModuleFixtures'; - const schema = parseFile( - `${FIXTURE_DIR}/${fixture}`, - FlowParser.buildSchema, - ); - const output = generator.generate(libName, schema); - expect(Object.fromEntries(output)).toMatchSnapshot(); - }); -}); diff --git a/packages/react-native-codegen/e2e/__tests__/components/GeneratePropsH-test.js b/packages/react-native-codegen/e2e/__tests__/components/GeneratePropsH-test.js deleted file mode 100644 index 0600f6bb70d1..000000000000 --- a/packages/react-native-codegen/e2e/__tests__/components/GeneratePropsH-test.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const {parseFile} = require('../../../src/parsers/utils'); -const FlowParser = require('../../../src/parsers/flow'); -const generator = require('../../../src/generators/components/GeneratePropsH'); -const fs = require('fs'); - -const FIXTURE_DIR = `${__dirname}/../../__test_fixtures__/components`; - -const fixtures = fs.readdirSync(FIXTURE_DIR); - -fixtures.forEach(fixture => { - it(`GeneratePropsH can generate for '${fixture}'`, () => { - const libName = 'RNCodegenModuleFixtures'; - const schema = parseFile( - `${FIXTURE_DIR}/${fixture}`, - FlowParser.buildSchema, - ); - const output = generator.generate(libName, schema); - expect(Object.fromEntries(output)).toMatchSnapshot(); - }); -}); diff --git a/packages/react-native-codegen/e2e/__tests__/components/GeneratePropsJavaDelegate-test.js b/packages/react-native-codegen/e2e/__tests__/components/GeneratePropsJavaDelegate-test.js deleted file mode 100644 index 3f87386c4a0e..000000000000 --- a/packages/react-native-codegen/e2e/__tests__/components/GeneratePropsJavaDelegate-test.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const {parseFile} = require('../../../src/parsers/utils'); -const FlowParser = require('../../../src/parsers/flow'); -const generator = require('../../../src/generators/components/GeneratePropsJavaDelegate'); -const fs = require('fs'); - -const FIXTURE_DIR = `${__dirname}/../../__test_fixtures__/components`; - -const fixtures = fs.readdirSync(FIXTURE_DIR); - -fixtures.forEach(fixture => { - it(`GeneratePropsJavaDelegate can generate for '${fixture}'`, () => { - const libName = 'RNCodegenModuleFixtures'; - const schema = parseFile( - `${FIXTURE_DIR}/${fixture}`, - FlowParser.buildSchema, - ); - const output = generator.generate(libName, schema); - expect(Object.fromEntries(output)).toMatchSnapshot(); - }); -}); diff --git a/packages/react-native-codegen/e2e/__tests__/components/GeneratePropsJavaInterface-test.js b/packages/react-native-codegen/e2e/__tests__/components/GeneratePropsJavaInterface-test.js deleted file mode 100644 index 40fcfe3d9d02..000000000000 --- a/packages/react-native-codegen/e2e/__tests__/components/GeneratePropsJavaInterface-test.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const {parseFile} = require('../../../src/parsers/utils'); -const FlowParser = require('../../../src/parsers/flow'); -const generator = require('../../../src/generators/components/GeneratePropsJavaInterface'); -const fs = require('fs'); - -const FIXTURE_DIR = `${__dirname}/../../__test_fixtures__/components`; -const fixtures = fs.readdirSync(FIXTURE_DIR); - -fixtures.forEach(fixture => { - it(`GeneratePropsJavaInterface can generate for '${fixture}'`, () => { - const libName = 'RNCodegenModuleFixtures'; - const schema = parseFile( - `${FIXTURE_DIR}/${fixture}`, - FlowParser.buildSchema, - ); - const output = generator.generate(libName, schema, undefined, false); - expect(Object.fromEntries(output)).toMatchSnapshot(); - }); -}); diff --git a/packages/react-native-codegen/e2e/__tests__/components/GenerateShadowNodeCpp-test.js b/packages/react-native-codegen/e2e/__tests__/components/GenerateShadowNodeCpp-test.js deleted file mode 100644 index a4fa38bddab7..000000000000 --- a/packages/react-native-codegen/e2e/__tests__/components/GenerateShadowNodeCpp-test.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const {parseFile} = require('../../../src/parsers/utils'); -const FlowParser = require('../../../src/parsers/flow'); -const generator = require('../../../src/generators/components/GenerateShadowNodeCpp'); -const fs = require('fs'); - -const FIXTURE_DIR = `${__dirname}/../../__test_fixtures__/components`; -const fixtures = fs.readdirSync(FIXTURE_DIR); - -fixtures.forEach(fixture => { - it(`GenerateShadowNodeCpp can generate for '${fixture}'`, () => { - const libName = 'RNCodegenModuleFixtures'; - const schema = parseFile( - `${FIXTURE_DIR}/${fixture}`, - FlowParser.buildSchema, - ); - const output = generator.generate(libName, schema, undefined, false); - expect(Object.fromEntries(output)).toMatchSnapshot(); - }); -}); diff --git a/packages/react-native-codegen/e2e/__tests__/components/GenerateShadowNodeH-test.js b/packages/react-native-codegen/e2e/__tests__/components/GenerateShadowNodeH-test.js deleted file mode 100644 index 0af0ba44f4b2..000000000000 --- a/packages/react-native-codegen/e2e/__tests__/components/GenerateShadowNodeH-test.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const {parseFile} = require('../../../src/parsers/utils'); -const FlowParser = require('../../../src/parsers/flow'); -const generator = require('../../../src/generators/components/GenerateShadowNodeH'); -const fs = require('fs'); - -const FIXTURE_DIR = `${__dirname}/../../__test_fixtures__/components`; -const fixtures = fs.readdirSync(FIXTURE_DIR); - -fixtures.forEach(fixture => { - it(`GenerateShadowNodeH can generate for '${fixture}'`, () => { - const libName = 'RNCodegenModuleFixtures'; - const schema = parseFile( - `${FIXTURE_DIR}/${fixture}`, - FlowParser.buildSchema, - ); - const output = generator.generate(libName, schema, undefined, false); - expect(Object.fromEntries(output)).toMatchSnapshot(); - }); -}); diff --git a/packages/react-native-codegen/e2e/__tests__/components/GenerateViewConfigJs-test.js b/packages/react-native-codegen/e2e/__tests__/components/GenerateViewConfigJs-test.js deleted file mode 100644 index fa4d90797ba4..000000000000 --- a/packages/react-native-codegen/e2e/__tests__/components/GenerateViewConfigJs-test.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const {parseFile} = require('../../../src/parsers/utils'); -const FlowParser = require('../../../src/parsers/flow'); -const generator = require('../../../src/generators/components/GenerateViewConfigJs'); -const fs = require('fs'); - -const FIXTURE_DIR = `${__dirname}/../../__test_fixtures__/components`; - -const fixtures = fs.readdirSync(FIXTURE_DIR); - -fixtures.forEach(fixture => { - it(`GenerateViewConfigJs can generate for '${fixture}'`, () => { - const libName = 'RNCodegenModuleFixtures'; - const schema = parseFile( - `${FIXTURE_DIR}/${fixture}`, - FlowParser.buildSchema, - ); - const output = generator.generate(libName, schema); - expect(output).toMatchSnapshot(); - }); -}); diff --git a/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GenerateComponentDescriptorH-test.js.snap b/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GenerateComponentDescriptorH-test.js.snap deleted file mode 100644 index 7c91b013e455..000000000000 --- a/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GenerateComponentDescriptorH-test.js.snap +++ /dev/null @@ -1,449 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GenerateComponentDescriptorH can generate for 'ArrayPropsNativeComponent.js' 1`] = ` -Object { - "ComponentDescriptors.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using ArrayPropsNativeComponentViewComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate for 'BooleanPropNativeComponent.js' 1`] = ` -Object { - "ComponentDescriptors.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using BooleanPropNativeComponentViewComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate for 'ColorPropNativeComponent.js' 1`] = ` -Object { - "ComponentDescriptors.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using ColorPropNativeComponentViewComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate for 'EdgeInsetsPropNativeComponent.js' 1`] = ` -Object { - "ComponentDescriptors.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using EdgeInsetsPropNativeComponentViewComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate for 'EnumPropNativeComponent.js' 1`] = ` -Object { - "ComponentDescriptors.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using EnumPropNativeComponentViewComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate for 'EventNestedObjectPropsNativeComponent.js' 1`] = ` -Object { - "ComponentDescriptors.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using EventNestedObjectPropsNativeComponentViewComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate for 'EventPropsNativeComponent.js' 1`] = ` -Object { - "ComponentDescriptors.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using EventPropsNativeComponentViewComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate for 'FloatPropsNativeComponent.js' 1`] = ` -Object { - "ComponentDescriptors.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using FloatPropsNativeComponentViewComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate for 'ImagePropNativeComponent.js' 1`] = ` -Object { - "ComponentDescriptors.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using ImagePropNativeComponentViewComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate for 'IntegerPropNativeComponent.js' 1`] = ` -Object { - "ComponentDescriptors.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using IntegerPropNativeComponentViewComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate for 'InterfaceOnlyNativeComponent.js' 1`] = ` -Object { - "ComponentDescriptors.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate for 'MultiNativePropNativeComponent.js' 1`] = ` -Object { - "ComponentDescriptors.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using MultiNativePropNativeComponentViewComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate for 'NoPropsNoEventsNativeComponent.js' 1`] = ` -Object { - "ComponentDescriptors.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using NoPropsNoEventsNativeComponentViewComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate for 'ObjectPropsNativeComponent.js' 1`] = ` -Object { - "ComponentDescriptors.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using ObjectPropsNativeComponentComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate for 'PointPropNativeComponent.js' 1`] = ` -Object { - "ComponentDescriptors.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using PointPropNativeComponentViewComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate for 'StringPropNativeComponent.js' 1`] = ` -Object { - "ComponentDescriptors.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using StringPropNativeComponentViewComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; diff --git a/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GenerateComponentHObjCpp-test.js.snap b/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GenerateComponentHObjCpp-test.js.snap deleted file mode 100644 index 3a6cc0fb294a..000000000000 --- a/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GenerateComponentHObjCpp-test.js.snap +++ /dev/null @@ -1,401 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GenerateComponentHObjCpp can generate for 'ArrayPropsNativeComponent.js' 1`] = ` -Object { - "RCTComponentViewHelpers.h": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTArrayPropsNativeComponentViewViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate for 'BooleanPropNativeComponent.js' 1`] = ` -Object { - "RCTComponentViewHelpers.h": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTBooleanPropNativeComponentViewViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate for 'ColorPropNativeComponent.js' 1`] = ` -Object { - "RCTComponentViewHelpers.h": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTColorPropNativeComponentViewViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate for 'EdgeInsetsPropNativeComponent.js' 1`] = ` -Object { - "RCTComponentViewHelpers.h": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTEdgeInsetsPropNativeComponentViewViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate for 'EnumPropNativeComponent.js' 1`] = ` -Object { - "RCTComponentViewHelpers.h": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTEnumPropNativeComponentViewViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate for 'EventNestedObjectPropsNativeComponent.js' 1`] = ` -Object { - "RCTComponentViewHelpers.h": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTEventNestedObjectPropsNativeComponentViewViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate for 'EventPropsNativeComponent.js' 1`] = ` -Object { - "RCTComponentViewHelpers.h": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTEventPropsNativeComponentViewViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate for 'FloatPropsNativeComponent.js' 1`] = ` -Object { - "RCTComponentViewHelpers.h": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTFloatPropsNativeComponentViewViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate for 'ImagePropNativeComponent.js' 1`] = ` -Object { - "RCTComponentViewHelpers.h": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTImagePropNativeComponentViewViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate for 'IntegerPropNativeComponent.js' 1`] = ` -Object { - "RCTComponentViewHelpers.h": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTIntegerPropNativeComponentViewViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate for 'InterfaceOnlyNativeComponent.js' 1`] = ` -Object { - "RCTComponentViewHelpers.h": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTInterfaceOnlyNativeComponentViewViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate for 'MultiNativePropNativeComponent.js' 1`] = ` -Object { - "RCTComponentViewHelpers.h": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTMultiNativePropNativeComponentViewViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate for 'NoPropsNoEventsNativeComponent.js' 1`] = ` -Object { - "RCTComponentViewHelpers.h": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTNoPropsNoEventsNativeComponentViewViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate for 'ObjectPropsNativeComponent.js' 1`] = ` -Object { - "RCTComponentViewHelpers.h": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTObjectPropsNativeComponentViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate for 'PointPropNativeComponent.js' 1`] = ` -Object { - "RCTComponentViewHelpers.h": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTPointPropNativeComponentViewViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate for 'StringPropNativeComponent.js' 1`] = ` -Object { - "RCTComponentViewHelpers.h": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTStringPropNativeComponentViewViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; diff --git a/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GenerateEventEmitterCpp-test.js.snap b/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GenerateEventEmitterCpp-test.js.snap deleted file mode 100644 index 07ce71990ed2..000000000000 --- a/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GenerateEventEmitterCpp-test.js.snap +++ /dev/null @@ -1,469 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GenerateEventEmitterCpp can generate for 'ArrayPropsNativeComponent.js' 1`] = ` -Object { - "EventEmitters.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate for 'BooleanPropNativeComponent.js' 1`] = ` -Object { - "EventEmitters.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate for 'ColorPropNativeComponent.js' 1`] = ` -Object { - "EventEmitters.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate for 'EdgeInsetsPropNativeComponent.js' 1`] = ` -Object { - "EventEmitters.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate for 'EnumPropNativeComponent.js' 1`] = ` -Object { - "EventEmitters.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate for 'EventNestedObjectPropsNativeComponent.js' 1`] = ` -Object { - "EventEmitters.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - -void EventNestedObjectPropsNativeComponentViewEventEmitter::onChange(OnChange event) const { - dispatchEvent(\\"change\\", [event=std::move(event)](jsi::Runtime &runtime) { - auto payload = jsi::Object(runtime); - { - auto location = jsi::Object(runtime); - { - auto source = jsi::Object(runtime); - source.setProperty(runtime, \\"url\\", event.location.source.url); - - location.setProperty(runtime, \\"source\\", source); - } -location.setProperty(runtime, \\"x\\", event.location.x); -location.setProperty(runtime, \\"y\\", event.location.y); - - payload.setProperty(runtime, \\"location\\", location); - } - return payload; - }); -} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate for 'EventPropsNativeComponent.js' 1`] = ` -Object { - "EventEmitters.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - -void EventPropsNativeComponentViewEventEmitter::onChange(OnChange event) const { - dispatchEvent(\\"change\\", [event=std::move(event)](jsi::Runtime &runtime) { - auto payload = jsi::Object(runtime); - payload.setProperty(runtime, \\"value\\", event.value); -payload.setProperty(runtime, \\"source\\", event.source); -payload.setProperty(runtime, \\"progress\\", event.progress); -payload.setProperty(runtime, \\"scale\\", event.scale); - return payload; - }); -} -void EventPropsNativeComponentViewEventEmitter::onEventDirect(OnEventDirect event) const { - dispatchEvent(\\"eventDirect\\", [event=std::move(event)](jsi::Runtime &runtime) { - auto payload = jsi::Object(runtime); - payload.setProperty(runtime, \\"value\\", event.value); - return payload; - }); -} -void EventPropsNativeComponentViewEventEmitter::onEventDirectWithPaperName(OnEventDirectWithPaperName event) const { - dispatchEvent(\\"eventDirectWithPaperName\\", [event=std::move(event)](jsi::Runtime &runtime) { - auto payload = jsi::Object(runtime); - payload.setProperty(runtime, \\"value\\", event.value); - return payload; - }); -} -void EventPropsNativeComponentViewEventEmitter::onOrientationChange(OnOrientationChange event) const { - dispatchEvent(\\"orientationChange\\", [event=std::move(event)](jsi::Runtime &runtime) { - auto payload = jsi::Object(runtime); - payload.setProperty(runtime, \\"orientation\\", toString(event.orientation)); - return payload; - }); -} -void EventPropsNativeComponentViewEventEmitter::onEnd(OnEnd event) const { - dispatchEvent(\\"end\\", [event=std::move(event)](jsi::Runtime &runtime) { - auto payload = jsi::Object(runtime); - - return payload; - }); -} -void EventPropsNativeComponentViewEventEmitter::onEventBubblingWithPaperName(OnEventBubblingWithPaperName event) const { - dispatchEvent(\\"eventBubblingWithPaperName\\", [event=std::move(event)](jsi::Runtime &runtime) { - auto payload = jsi::Object(runtime); - - return payload; - }); -} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate for 'FloatPropsNativeComponent.js' 1`] = ` -Object { - "EventEmitters.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate for 'ImagePropNativeComponent.js' 1`] = ` -Object { - "EventEmitters.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate for 'IntegerPropNativeComponent.js' 1`] = ` -Object { - "EventEmitters.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate for 'InterfaceOnlyNativeComponent.js' 1`] = ` -Object { - "EventEmitters.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - -void InterfaceOnlyNativeComponentViewEventEmitter::onChange(OnChange event) const { - dispatchEvent(\\"change\\", [event=std::move(event)](jsi::Runtime &runtime) { - auto payload = jsi::Object(runtime); - payload.setProperty(runtime, \\"value\\", event.value); - return payload; - }); -} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate for 'MultiNativePropNativeComponent.js' 1`] = ` -Object { - "EventEmitters.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate for 'NoPropsNoEventsNativeComponent.js' 1`] = ` -Object { - "EventEmitters.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate for 'ObjectPropsNativeComponent.js' 1`] = ` -Object { - "EventEmitters.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate for 'PointPropNativeComponent.js' 1`] = ` -Object { - "EventEmitters.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate for 'StringPropNativeComponent.js' 1`] = ` -Object { - "EventEmitters.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; diff --git a/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GenerateEventEmitterH-test.js.snap b/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GenerateEventEmitterH-test.js.snap deleted file mode 100644 index e7be3226bd8c..000000000000 --- a/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GenerateEventEmitterH-test.js.snap +++ /dev/null @@ -1,606 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GenerateEventEmitterH can generate for 'ArrayPropsNativeComponent.js' 1`] = ` -Object { - "EventEmitters.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT ArrayPropsNativeComponentViewEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate for 'BooleanPropNativeComponent.js' 1`] = ` -Object { - "EventEmitters.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT BooleanPropNativeComponentViewEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate for 'ColorPropNativeComponent.js' 1`] = ` -Object { - "EventEmitters.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT ColorPropNativeComponentViewEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate for 'EdgeInsetsPropNativeComponent.js' 1`] = ` -Object { - "EventEmitters.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT EdgeInsetsPropNativeComponentViewEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate for 'EnumPropNativeComponent.js' 1`] = ` -Object { - "EventEmitters.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT EnumPropNativeComponentViewEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate for 'EventNestedObjectPropsNativeComponent.js' 1`] = ` -Object { - "EventEmitters.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT EventNestedObjectPropsNativeComponentViewEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - struct OnChangeLocationSource { - std::string url; - }; - - struct OnChangeLocation { - OnChangeLocationSource source; - int x; - int y; - }; - - struct OnChange { - OnChangeLocation location; - }; - - void onChange(OnChange value) const; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate for 'EventPropsNativeComponent.js' 1`] = ` -Object { - "EventEmitters.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT EventPropsNativeComponentViewEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - struct OnChange { - bool value; - std::string source; - int progress; - Float scale; - }; - - struct OnEventDirect { - bool value; - }; - - struct OnEventDirectWithPaperName { - bool value; - }; - - enum class OnOrientationChangeOrientation { - Landscape, - Portrait - }; - - static char const *toString(const OnOrientationChangeOrientation value) { - switch (value) { - case OnOrientationChangeOrientation::Landscape: return \\"landscape\\"; - case OnOrientationChangeOrientation::Portrait: return \\"portrait\\"; - } - } - - struct OnOrientationChange { - OnOrientationChangeOrientation orientation; - }; - - struct OnEnd { - - }; - - struct OnEventBubblingWithPaperName { - - }; - - void onChange(OnChange value) const; - - void onEventDirect(OnEventDirect value) const; - - void onEventDirectWithPaperName(OnEventDirectWithPaperName value) const; - - void onOrientationChange(OnOrientationChange value) const; - - void onEnd(OnEnd value) const; - - void onEventBubblingWithPaperName(OnEventBubblingWithPaperName value) const; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate for 'FloatPropsNativeComponent.js' 1`] = ` -Object { - "EventEmitters.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT FloatPropsNativeComponentViewEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate for 'ImagePropNativeComponent.js' 1`] = ` -Object { - "EventEmitters.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT ImagePropNativeComponentViewEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate for 'IntegerPropNativeComponent.js' 1`] = ` -Object { - "EventEmitters.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT IntegerPropNativeComponentViewEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate for 'InterfaceOnlyNativeComponent.js' 1`] = ` -Object { - "EventEmitters.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT InterfaceOnlyNativeComponentViewEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - struct OnChange { - bool value; - }; - - void onChange(OnChange value) const; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate for 'MultiNativePropNativeComponent.js' 1`] = ` -Object { - "EventEmitters.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT MultiNativePropNativeComponentViewEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate for 'NoPropsNoEventsNativeComponent.js' 1`] = ` -Object { - "EventEmitters.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT NoPropsNoEventsNativeComponentViewEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate for 'ObjectPropsNativeComponent.js' 1`] = ` -Object { - "EventEmitters.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT ObjectPropsNativeComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate for 'PointPropNativeComponent.js' 1`] = ` -Object { - "EventEmitters.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT PointPropNativeComponentViewEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate for 'StringPropNativeComponent.js' 1`] = ` -Object { - "EventEmitters.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT StringPropNativeComponentViewEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; diff --git a/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GeneratePropsCpp-test.js.snap b/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GeneratePropsCpp-test.js.snap deleted file mode 100644 index 6de527c44d34..000000000000 --- a/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GeneratePropsCpp-test.js.snap +++ /dev/null @@ -1,558 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GeneratePropsCpp can generate for 'ArrayPropsNativeComponent.js' 1`] = ` -Object { - "Props.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include -#include - -namespace facebook { -namespace react { - -ArrayPropsNativeComponentViewProps::ArrayPropsNativeComponentViewProps( - const PropsParserContext &context, - const ArrayPropsNativeComponentViewProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - names(convertRawProp(context, rawProps, \\"names\\", sourceProps.names, {})), - disableds(convertRawProp(context, rawProps, \\"disableds\\", sourceProps.disableds, {})), - progress(convertRawProp(context, rawProps, \\"progress\\", sourceProps.progress, {})), - radii(convertRawProp(context, rawProps, \\"radii\\", sourceProps.radii, {})), - colors(convertRawProp(context, rawProps, \\"colors\\", sourceProps.colors, {})), - srcs(convertRawProp(context, rawProps, \\"srcs\\", sourceProps.srcs, {})), - points(convertRawProp(context, rawProps, \\"points\\", sourceProps.points, {})), - sizes(convertRawProp(context, rawProps, \\"sizes\\", sourceProps.sizes, {static_cast(ArrayPropsNativeComponentViewSizes::Small)})), - object(convertRawProp(context, rawProps, \\"object\\", sourceProps.object, {})), - arrayOfObjects(convertRawProp(context, rawProps, \\"arrayOfObjects\\", sourceProps.arrayOfObjects, {})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate for 'BooleanPropNativeComponent.js' 1`] = ` -Object { - "Props.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -BooleanPropNativeComponentViewProps::BooleanPropNativeComponentViewProps( - const PropsParserContext &context, - const BooleanPropNativeComponentViewProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - disabled(convertRawProp(context, rawProps, \\"disabled\\", sourceProps.disabled, {false})), - disabledNullable(convertRawProp(context, rawProps, \\"disabledNullable\\", sourceProps.disabledNullable, {})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate for 'ColorPropNativeComponent.js' 1`] = ` -Object { - "Props.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -ColorPropNativeComponentViewProps::ColorPropNativeComponentViewProps( - const PropsParserContext &context, - const ColorPropNativeComponentViewProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - tintColor(convertRawProp(context, rawProps, \\"tintColor\\", sourceProps.tintColor, {})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate for 'EdgeInsetsPropNativeComponent.js' 1`] = ` -Object { - "Props.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -EdgeInsetsPropNativeComponentViewProps::EdgeInsetsPropNativeComponentViewProps( - const PropsParserContext &context, - const EdgeInsetsPropNativeComponentViewProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps) - - - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate for 'EnumPropNativeComponent.js' 1`] = ` -Object { - "Props.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -EnumPropNativeComponentViewProps::EnumPropNativeComponentViewProps( - const PropsParserContext &context, - const EnumPropNativeComponentViewProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - alignment(convertRawProp(context, rawProps, \\"alignment\\", sourceProps.alignment, {EnumPropNativeComponentViewAlignment::Center})), - intervals(convertRawProp(context, rawProps, \\"intervals\\", sourceProps.intervals, {EnumPropNativeComponentViewIntervals::Intervals0})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate for 'EventNestedObjectPropsNativeComponent.js' 1`] = ` -Object { - "Props.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -EventNestedObjectPropsNativeComponentViewProps::EventNestedObjectPropsNativeComponentViewProps( - const PropsParserContext &context, - const EventNestedObjectPropsNativeComponentViewProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - disabled(convertRawProp(context, rawProps, \\"disabled\\", sourceProps.disabled, {false})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate for 'EventPropsNativeComponent.js' 1`] = ` -Object { - "Props.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -EventPropsNativeComponentViewProps::EventPropsNativeComponentViewProps( - const PropsParserContext &context, - const EventPropsNativeComponentViewProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - disabled(convertRawProp(context, rawProps, \\"disabled\\", sourceProps.disabled, {false})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate for 'FloatPropsNativeComponent.js' 1`] = ` -Object { - "Props.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -FloatPropsNativeComponentViewProps::FloatPropsNativeComponentViewProps( - const PropsParserContext &context, - const FloatPropsNativeComponentViewProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - blurRadius(convertRawProp(context, rawProps, \\"blurRadius\\", sourceProps.blurRadius, {0.0})), - blurRadius2(convertRawProp(context, rawProps, \\"blurRadius2\\", sourceProps.blurRadius2, {0.001})), - blurRadius3(convertRawProp(context, rawProps, \\"blurRadius3\\", sourceProps.blurRadius3, {2.1})), - blurRadius4(convertRawProp(context, rawProps, \\"blurRadius4\\", sourceProps.blurRadius4, {0.0})), - blurRadius5(convertRawProp(context, rawProps, \\"blurRadius5\\", sourceProps.blurRadius5, {1.0})), - blurRadius6(convertRawProp(context, rawProps, \\"blurRadius6\\", sourceProps.blurRadius6, {0.0})), - blurRadiusNullable(convertRawProp(context, rawProps, \\"blurRadiusNullable\\", sourceProps.blurRadiusNullable, {})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate for 'ImagePropNativeComponent.js' 1`] = ` -Object { - "Props.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include -#include - -namespace facebook { -namespace react { - -ImagePropNativeComponentViewProps::ImagePropNativeComponentViewProps( - const PropsParserContext &context, - const ImagePropNativeComponentViewProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - thumbImage(convertRawProp(context, rawProps, \\"thumbImage\\", sourceProps.thumbImage, {})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate for 'IntegerPropNativeComponent.js' 1`] = ` -Object { - "Props.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -IntegerPropNativeComponentViewProps::IntegerPropNativeComponentViewProps( - const PropsParserContext &context, - const IntegerPropNativeComponentViewProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - progress1(convertRawProp(context, rawProps, \\"progress1\\", sourceProps.progress1, {0})), - progress2(convertRawProp(context, rawProps, \\"progress2\\", sourceProps.progress2, {-1})), - progress3(convertRawProp(context, rawProps, \\"progress3\\", sourceProps.progress3, {10})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate for 'InterfaceOnlyNativeComponent.js' 1`] = ` -Object { - "Props.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -InterfaceOnlyNativeComponentViewProps::InterfaceOnlyNativeComponentViewProps( - const PropsParserContext &context, - const InterfaceOnlyNativeComponentViewProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - title(convertRawProp(context, rawProps, \\"title\\", sourceProps.title, {\\"\\"})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate for 'MultiNativePropNativeComponent.js' 1`] = ` -Object { - "Props.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include -#include - -namespace facebook { -namespace react { - -MultiNativePropNativeComponentViewProps::MultiNativePropNativeComponentViewProps( - const PropsParserContext &context, - const MultiNativePropNativeComponentViewProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - thumbImage(convertRawProp(context, rawProps, \\"thumbImage\\", sourceProps.thumbImage, {})), - color(convertRawProp(context, rawProps, \\"color\\", sourceProps.color, {})), - thumbTintColor(convertRawProp(context, rawProps, \\"thumbTintColor\\", sourceProps.thumbTintColor, {})), - point(convertRawProp(context, rawProps, \\"point\\", sourceProps.point, {})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate for 'NoPropsNoEventsNativeComponent.js' 1`] = ` -Object { - "Props.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -NoPropsNoEventsNativeComponentViewProps::NoPropsNoEventsNativeComponentViewProps( - const PropsParserContext &context, - const NoPropsNoEventsNativeComponentViewProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps) - - - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate for 'ObjectPropsNativeComponent.js' 1`] = ` -Object { - "Props.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include -#include - -namespace facebook { -namespace react { - -ObjectPropsNativeComponentProps::ObjectPropsNativeComponentProps( - const PropsParserContext &context, - const ObjectPropsNativeComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - objectProp(convertRawProp(context, rawProps, \\"objectProp\\", sourceProps.objectProp, {})), - objectArrayProp(convertRawProp(context, rawProps, \\"objectArrayProp\\", sourceProps.objectArrayProp, {})), - objectPrimitiveRequiredProp(convertRawProp(context, rawProps, \\"objectPrimitiveRequiredProp\\", sourceProps.objectPrimitiveRequiredProp, {})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate for 'PointPropNativeComponent.js' 1`] = ` -Object { - "Props.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -PointPropNativeComponentViewProps::PointPropNativeComponentViewProps( - const PropsParserContext &context, - const PointPropNativeComponentViewProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - startPoint(convertRawProp(context, rawProps, \\"startPoint\\", sourceProps.startPoint, {})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate for 'StringPropNativeComponent.js' 1`] = ` -Object { - "Props.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -StringPropNativeComponentViewProps::StringPropNativeComponentViewProps( - const PropsParserContext &context, - const StringPropNativeComponentViewProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - placeholder(convertRawProp(context, rawProps, \\"placeholder\\", sourceProps.placeholder, {\\"\\"})), - defaultValue(convertRawProp(context, rawProps, \\"defaultValue\\", sourceProps.defaultValue, {})) - {} - -} // namespace react -} // namespace facebook -", -} -`; diff --git a/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GeneratePropsH-test.js.snap b/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GeneratePropsH-test.js.snap deleted file mode 100644 index 91c0ca90fd83..000000000000 --- a/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GeneratePropsH-test.js.snap +++ /dev/null @@ -1,903 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GeneratePropsH can generate for 'ArrayPropsNativeComponent.js' 1`] = ` -Object { - "Props.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -using ArrayPropsNativeComponentViewSizesMask = uint32_t; - -enum class ArrayPropsNativeComponentViewSizes: ArrayPropsNativeComponentViewSizesMask { - Small = 1 << 0, - Large = 1 << 1 -}; - -constexpr bool operator&( - ArrayPropsNativeComponentViewSizesMask const lhs, - enum ArrayPropsNativeComponentViewSizes const rhs) { - return lhs & static_cast(rhs); -} - -constexpr ArrayPropsNativeComponentViewSizesMask operator|( - ArrayPropsNativeComponentViewSizesMask const lhs, - enum ArrayPropsNativeComponentViewSizes const rhs) { - return lhs | static_cast(rhs); -} - -constexpr void operator|=( - ArrayPropsNativeComponentViewSizesMask &lhs, - enum ArrayPropsNativeComponentViewSizes const rhs) { - lhs = lhs | static_cast(rhs); -} - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ArrayPropsNativeComponentViewSizesMask &result) { - auto items = std::vector{value}; - for (const auto &item : items) { - if (item == \\"small\\") { - result |= ArrayPropsNativeComponentViewSizes::Small; - continue; - } - if (item == \\"large\\") { - result |= ArrayPropsNativeComponentViewSizes::Large; - continue; - } - abort(); - } -} - -static inline std::string toString(const ArrayPropsNativeComponentViewSizesMask &value) { - auto result = std::string{}; - auto separator = std::string{\\", \\"}; - - if (value & ArrayPropsNativeComponentViewSizes::Small) { - result += \\"small\\" + separator; - } - if (value & ArrayPropsNativeComponentViewSizes::Large) { - result += \\"large\\" + separator; - } - if (!result.empty()) { - result.erase(result.length() - separator.length()); - } - return result; -} -struct ArrayPropsNativeComponentViewObjectStruct { - std::string prop; -}; - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ArrayPropsNativeComponentViewObjectStruct &result) { - auto map = (butter::map)value; - - auto tmp_prop = map.find(\\"prop\\"); - if (tmp_prop != map.end()) { - fromRawValue(context, tmp_prop->second, result.prop); - } -} - -static inline std::string toString(const ArrayPropsNativeComponentViewObjectStruct &value) { - return \\"[Object ArrayPropsNativeComponentViewObjectStruct]\\"; -} - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, std::vector &result) { - auto items = (std::vector)value; - for (const auto &item : items) { - ArrayPropsNativeComponentViewObjectStruct newItem; - fromRawValue(context, item, newItem); - result.emplace_back(newItem); - } -} - - -struct ArrayPropsNativeComponentViewArrayOfObjectsStruct { - Float prop1; - int prop2; -}; - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ArrayPropsNativeComponentViewArrayOfObjectsStruct &result) { - auto map = (butter::map)value; - - auto tmp_prop1 = map.find(\\"prop1\\"); - if (tmp_prop1 != map.end()) { - fromRawValue(context, tmp_prop1->second, result.prop1); - } - auto tmp_prop2 = map.find(\\"prop2\\"); - if (tmp_prop2 != map.end()) { - fromRawValue(context, tmp_prop2->second, result.prop2); - } -} - -static inline std::string toString(const ArrayPropsNativeComponentViewArrayOfObjectsStruct &value) { - return \\"[Object ArrayPropsNativeComponentViewArrayOfObjectsStruct]\\"; -} - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, std::vector &result) { - auto items = (std::vector)value; - for (const auto &item : items) { - ArrayPropsNativeComponentViewArrayOfObjectsStruct newItem; - fromRawValue(context, item, newItem); - result.emplace_back(newItem); - } -} - -class JSI_EXPORT ArrayPropsNativeComponentViewProps final : public ViewProps { - public: - ArrayPropsNativeComponentViewProps() = default; - ArrayPropsNativeComponentViewProps(const PropsParserContext& context, const ArrayPropsNativeComponentViewProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - std::vector names{}; - std::vector disableds{}; - std::vector progress{}; - std::vector radii{}; - std::vector colors{}; - std::vector srcs{}; - std::vector points{}; - ArrayPropsNativeComponentViewSizesMask sizes{static_cast(ArrayPropsNativeComponentViewSizes::Small)}; - std::vector object{}; - std::vector arrayOfObjects{}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate for 'BooleanPropNativeComponent.js' 1`] = ` -Object { - "Props.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT BooleanPropNativeComponentViewProps final : public ViewProps { - public: - BooleanPropNativeComponentViewProps() = default; - BooleanPropNativeComponentViewProps(const PropsParserContext& context, const BooleanPropNativeComponentViewProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - bool disabled{false}; - bool disabledNullable{}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate for 'ColorPropNativeComponent.js' 1`] = ` -Object { - "Props.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT ColorPropNativeComponentViewProps final : public ViewProps { - public: - ColorPropNativeComponentViewProps() = default; - ColorPropNativeComponentViewProps(const PropsParserContext& context, const ColorPropNativeComponentViewProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - SharedColor tintColor{}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate for 'EdgeInsetsPropNativeComponent.js' 1`] = ` -Object { - "Props.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT EdgeInsetsPropNativeComponentViewProps final : public ViewProps { - public: - EdgeInsetsPropNativeComponentViewProps() = default; - EdgeInsetsPropNativeComponentViewProps(const PropsParserContext& context, const EdgeInsetsPropNativeComponentViewProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate for 'EnumPropNativeComponent.js' 1`] = ` -Object { - "Props.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -enum class EnumPropNativeComponentViewAlignment { Top, Center, BottomRight }; - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnumPropNativeComponentViewAlignment &result) { - auto string = (std::string)value; - if (string == \\"top\\") { result = EnumPropNativeComponentViewAlignment::Top; return; } - if (string == \\"center\\") { result = EnumPropNativeComponentViewAlignment::Center; return; } - if (string == \\"bottom-right\\") { result = EnumPropNativeComponentViewAlignment::BottomRight; return; } - abort(); -} - -static inline std::string toString(const EnumPropNativeComponentViewAlignment &value) { - switch (value) { - case EnumPropNativeComponentViewAlignment::Top: return \\"top\\"; - case EnumPropNativeComponentViewAlignment::Center: return \\"center\\"; - case EnumPropNativeComponentViewAlignment::BottomRight: return \\"bottom-right\\"; - } -} -enum class EnumPropNativeComponentViewIntervals { Intervals0 = 0, Intervals15 = 15, Intervals30 = 30, Intervals60 = 60 }; - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnumPropNativeComponentViewIntervals &result) { - assert(value.hasType()); - auto integerValue = (int)value; - switch (integerValue) { - case 0: - result = EnumPropNativeComponentViewIntervals::Intervals0; - return; - case 15: - result = EnumPropNativeComponentViewIntervals::Intervals15; - return; - case 30: - result = EnumPropNativeComponentViewIntervals::Intervals30; - return; - case 60: - result = EnumPropNativeComponentViewIntervals::Intervals60; - return; - } - abort(); -} - -static inline std::string toString(const EnumPropNativeComponentViewIntervals &value) { - switch (value) { - case EnumPropNativeComponentViewIntervals::Intervals0: return \\"0\\"; - case EnumPropNativeComponentViewIntervals::Intervals15: return \\"15\\"; - case EnumPropNativeComponentViewIntervals::Intervals30: return \\"30\\"; - case EnumPropNativeComponentViewIntervals::Intervals60: return \\"60\\"; - } -} - -class JSI_EXPORT EnumPropNativeComponentViewProps final : public ViewProps { - public: - EnumPropNativeComponentViewProps() = default; - EnumPropNativeComponentViewProps(const PropsParserContext& context, const EnumPropNativeComponentViewProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - EnumPropNativeComponentViewAlignment alignment{EnumPropNativeComponentViewAlignment::Center}; - EnumPropNativeComponentViewIntervals intervals{EnumPropNativeComponentViewIntervals::Intervals0}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate for 'EventNestedObjectPropsNativeComponent.js' 1`] = ` -Object { - "Props.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT EventNestedObjectPropsNativeComponentViewProps final : public ViewProps { - public: - EventNestedObjectPropsNativeComponentViewProps() = default; - EventNestedObjectPropsNativeComponentViewProps(const PropsParserContext& context, const EventNestedObjectPropsNativeComponentViewProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - bool disabled{false}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate for 'EventPropsNativeComponent.js' 1`] = ` -Object { - "Props.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT EventPropsNativeComponentViewProps final : public ViewProps { - public: - EventPropsNativeComponentViewProps() = default; - EventPropsNativeComponentViewProps(const PropsParserContext& context, const EventPropsNativeComponentViewProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - bool disabled{false}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate for 'FloatPropsNativeComponent.js' 1`] = ` -Object { - "Props.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT FloatPropsNativeComponentViewProps final : public ViewProps { - public: - FloatPropsNativeComponentViewProps() = default; - FloatPropsNativeComponentViewProps(const PropsParserContext& context, const FloatPropsNativeComponentViewProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - Float blurRadius{0.0}; - Float blurRadius2{0.001}; - Float blurRadius3{2.1}; - Float blurRadius4{0.0}; - Float blurRadius5{1.0}; - Float blurRadius6{0.0}; - Float blurRadiusNullable{}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate for 'ImagePropNativeComponent.js' 1`] = ` -Object { - "Props.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT ImagePropNativeComponentViewProps final : public ViewProps { - public: - ImagePropNativeComponentViewProps() = default; - ImagePropNativeComponentViewProps(const PropsParserContext& context, const ImagePropNativeComponentViewProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - ImageSource thumbImage{}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate for 'IntegerPropNativeComponent.js' 1`] = ` -Object { - "Props.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT IntegerPropNativeComponentViewProps final : public ViewProps { - public: - IntegerPropNativeComponentViewProps() = default; - IntegerPropNativeComponentViewProps(const PropsParserContext& context, const IntegerPropNativeComponentViewProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - int progress1{0}; - int progress2{-1}; - int progress3{10}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate for 'InterfaceOnlyNativeComponent.js' 1`] = ` -Object { - "Props.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT InterfaceOnlyNativeComponentViewProps final : public ViewProps { - public: - InterfaceOnlyNativeComponentViewProps() = default; - InterfaceOnlyNativeComponentViewProps(const PropsParserContext& context, const InterfaceOnlyNativeComponentViewProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - std::string title{\\"\\"}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate for 'MultiNativePropNativeComponent.js' 1`] = ` -Object { - "Props.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT MultiNativePropNativeComponentViewProps final : public ViewProps { - public: - MultiNativePropNativeComponentViewProps() = default; - MultiNativePropNativeComponentViewProps(const PropsParserContext& context, const MultiNativePropNativeComponentViewProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - ImageSource thumbImage{}; - SharedColor color{}; - SharedColor thumbTintColor{}; - Point point{}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate for 'NoPropsNoEventsNativeComponent.js' 1`] = ` -Object { - "Props.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT NoPropsNoEventsNativeComponentViewProps final : public ViewProps { - public: - NoPropsNoEventsNativeComponentViewProps() = default; - NoPropsNoEventsNativeComponentViewProps(const PropsParserContext& context, const NoPropsNoEventsNativeComponentViewProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate for 'ObjectPropsNativeComponent.js' 1`] = ` -Object { - "Props.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -enum class ObjectPropsNativeComponentStringEnumProp { Small, Large }; - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ObjectPropsNativeComponentStringEnumProp &result) { - auto string = (std::string)value; - if (string == \\"small\\") { result = ObjectPropsNativeComponentStringEnumProp::Small; return; } - if (string == \\"large\\") { result = ObjectPropsNativeComponentStringEnumProp::Large; return; } - abort(); -} - -static inline std::string toString(const ObjectPropsNativeComponentStringEnumProp &value) { - switch (value) { - case ObjectPropsNativeComponentStringEnumProp::Small: return \\"small\\"; - case ObjectPropsNativeComponentStringEnumProp::Large: return \\"large\\"; - } -} -enum class ObjectPropsNativeComponentIntEnumProp { IntEnumProp0 = 0, IntEnumProp1 = 1 }; - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ObjectPropsNativeComponentIntEnumProp &result) { - assert(value.hasType()); - auto integerValue = (int)value; - switch (integerValue) { - case 0: - result = ObjectPropsNativeComponentIntEnumProp::IntEnumProp0; - return; - case 1: - result = ObjectPropsNativeComponentIntEnumProp::IntEnumProp1; - return; - } - abort(); -} - -static inline std::string toString(const ObjectPropsNativeComponentIntEnumProp &value) { - switch (value) { - case ObjectPropsNativeComponentIntEnumProp::IntEnumProp0: return \\"0\\"; - case ObjectPropsNativeComponentIntEnumProp::IntEnumProp1: return \\"1\\"; - } -} -struct ObjectPropsNativeComponentObjectPropStruct { - std::string stringProp; - bool booleanProp; - Float floatProp; - int intProp; - ObjectPropsNativeComponentStringEnumProp stringEnumProp; - ObjectPropsNativeComponentIntEnumProp intEnumProp; -}; - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ObjectPropsNativeComponentObjectPropStruct &result) { - auto map = (butter::map)value; - - auto tmp_stringProp = map.find(\\"stringProp\\"); - if (tmp_stringProp != map.end()) { - fromRawValue(context, tmp_stringProp->second, result.stringProp); - } - auto tmp_booleanProp = map.find(\\"booleanProp\\"); - if (tmp_booleanProp != map.end()) { - fromRawValue(context, tmp_booleanProp->second, result.booleanProp); - } - auto tmp_floatProp = map.find(\\"floatProp\\"); - if (tmp_floatProp != map.end()) { - fromRawValue(context, tmp_floatProp->second, result.floatProp); - } - auto tmp_intProp = map.find(\\"intProp\\"); - if (tmp_intProp != map.end()) { - fromRawValue(context, tmp_intProp->second, result.intProp); - } - auto tmp_stringEnumProp = map.find(\\"stringEnumProp\\"); - if (tmp_stringEnumProp != map.end()) { - fromRawValue(context, tmp_stringEnumProp->second, result.stringEnumProp); - } - auto tmp_intEnumProp = map.find(\\"intEnumProp\\"); - if (tmp_intEnumProp != map.end()) { - fromRawValue(context, tmp_intEnumProp->second, result.intEnumProp); - } -} - -static inline std::string toString(const ObjectPropsNativeComponentObjectPropStruct &value) { - return \\"[Object ObjectPropsNativeComponentObjectPropStruct]\\"; -} - -struct ObjectPropsNativeComponentObjectArrayPropStruct { - std::vector array; -}; - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ObjectPropsNativeComponentObjectArrayPropStruct &result) { - auto map = (butter::map)value; - - auto tmp_array = map.find(\\"array\\"); - if (tmp_array != map.end()) { - fromRawValue(context, tmp_array->second, result.array); - } -} - -static inline std::string toString(const ObjectPropsNativeComponentObjectArrayPropStruct &value) { - return \\"[Object ObjectPropsNativeComponentObjectArrayPropStruct]\\"; -} - -struct ObjectPropsNativeComponentObjectPrimitiveRequiredPropStruct { - ImageSource image; - SharedColor color; - Point point; -}; - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ObjectPropsNativeComponentObjectPrimitiveRequiredPropStruct &result) { - auto map = (butter::map)value; - - auto tmp_image = map.find(\\"image\\"); - if (tmp_image != map.end()) { - fromRawValue(context, tmp_image->second, result.image); - } - auto tmp_color = map.find(\\"color\\"); - if (tmp_color != map.end()) { - fromRawValue(context, tmp_color->second, result.color); - } - auto tmp_point = map.find(\\"point\\"); - if (tmp_point != map.end()) { - fromRawValue(context, tmp_point->second, result.point); - } -} - -static inline std::string toString(const ObjectPropsNativeComponentObjectPrimitiveRequiredPropStruct &value) { - return \\"[Object ObjectPropsNativeComponentObjectPrimitiveRequiredPropStruct]\\"; -} -class JSI_EXPORT ObjectPropsNativeComponentProps final : public ViewProps { - public: - ObjectPropsNativeComponentProps() = default; - ObjectPropsNativeComponentProps(const PropsParserContext& context, const ObjectPropsNativeComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - ObjectPropsNativeComponentObjectPropStruct objectProp{}; - ObjectPropsNativeComponentObjectArrayPropStruct objectArrayProp{}; - ObjectPropsNativeComponentObjectPrimitiveRequiredPropStruct objectPrimitiveRequiredProp{}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate for 'PointPropNativeComponent.js' 1`] = ` -Object { - "Props.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT PointPropNativeComponentViewProps final : public ViewProps { - public: - PointPropNativeComponentViewProps() = default; - PointPropNativeComponentViewProps(const PropsParserContext& context, const PointPropNativeComponentViewProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - Point startPoint{}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate for 'StringPropNativeComponent.js' 1`] = ` -Object { - "Props.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT StringPropNativeComponentViewProps final : public ViewProps { - public: - StringPropNativeComponentViewProps() = default; - StringPropNativeComponentViewProps(const PropsParserContext& context, const StringPropNativeComponentViewProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - std::string placeholder{\\"\\"}; - std::string defaultValue{}; -}; - -} // namespace react -} // namespace facebook -", -} -`; diff --git a/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GeneratePropsJavaDelegate-test.js.snap b/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GeneratePropsJavaDelegate-test.js.snap deleted file mode 100644 index 461895f3b0d4..000000000000 --- a/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GeneratePropsJavaDelegate-test.js.snap +++ /dev/null @@ -1,663 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GeneratePropsJavaDelegate can generate for 'ArrayPropsNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/ArrayPropsNativeComponentViewManagerDelegate.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.bridge.ReadableArray; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class ArrayPropsNativeComponentViewManagerDelegate & ArrayPropsNativeComponentViewManagerInterface> extends BaseViewManagerDelegate { - public ArrayPropsNativeComponentViewManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"names\\": - mViewManager.setNames(view, (ReadableArray) value); - break; - case \\"disableds\\": - mViewManager.setDisableds(view, (ReadableArray) value); - break; - case \\"progress\\": - mViewManager.setProgress(view, (ReadableArray) value); - break; - case \\"radii\\": - mViewManager.setRadii(view, (ReadableArray) value); - break; - case \\"colors\\": - mViewManager.setColors(view, (ReadableArray) value); - break; - case \\"srcs\\": - mViewManager.setSrcs(view, (ReadableArray) value); - break; - case \\"points\\": - mViewManager.setPoints(view, (ReadableArray) value); - break; - case \\"sizes\\": - mViewManager.setSizes(view, (ReadableArray) value); - break; - case \\"object\\": - mViewManager.setObject(view, (ReadableArray) value); - break; - case \\"arrayOfObjects\\": - mViewManager.setArrayOfObjects(view, (ReadableArray) value); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate for 'BooleanPropNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/BooleanPropNativeComponentViewManagerDelegate.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class BooleanPropNativeComponentViewManagerDelegate & BooleanPropNativeComponentViewManagerInterface> extends BaseViewManagerDelegate { - public BooleanPropNativeComponentViewManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"disabled\\": - mViewManager.setDisabled(view, value == null ? false : (boolean) value); - break; - case \\"disabledNullable\\": - mViewManager.setDisabledNullable(view, value == null ? null : (Boolean) value); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate for 'ColorPropNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/ColorPropNativeComponentViewManagerDelegate.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.bridge.ColorPropConverter; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class ColorPropNativeComponentViewManagerDelegate & ColorPropNativeComponentViewManagerInterface> extends BaseViewManagerDelegate { - public ColorPropNativeComponentViewManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"tintColor\\": - mViewManager.setTintColor(view, ColorPropConverter.getColor(value, view.getContext())); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate for 'EdgeInsetsPropNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/EdgeInsetsPropNativeComponentViewManagerDelegate.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class EdgeInsetsPropNativeComponentViewManagerDelegate & EdgeInsetsPropNativeComponentViewManagerInterface> extends BaseViewManagerDelegate { - public EdgeInsetsPropNativeComponentViewManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - super.setProperty(view, propName, value); - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate for 'EnumPropNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/EnumPropNativeComponentViewManagerDelegate.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class EnumPropNativeComponentViewManagerDelegate & EnumPropNativeComponentViewManagerInterface> extends BaseViewManagerDelegate { - public EnumPropNativeComponentViewManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"alignment\\": - mViewManager.setAlignment(view, (String) value); - break; - case \\"intervals\\": - mViewManager.setIntervals(view, value == null ? 0 : ((Double) value).intValue()); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate for 'EventNestedObjectPropsNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/EventNestedObjectPropsNativeComponentViewManagerDelegate.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class EventNestedObjectPropsNativeComponentViewManagerDelegate & EventNestedObjectPropsNativeComponentViewManagerInterface> extends BaseViewManagerDelegate { - public EventNestedObjectPropsNativeComponentViewManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"disabled\\": - mViewManager.setDisabled(view, value == null ? false : (boolean) value); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate for 'EventPropsNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/EventPropsNativeComponentViewManagerDelegate.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class EventPropsNativeComponentViewManagerDelegate & EventPropsNativeComponentViewManagerInterface> extends BaseViewManagerDelegate { - public EventPropsNativeComponentViewManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"disabled\\": - mViewManager.setDisabled(view, value == null ? false : (boolean) value); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate for 'FloatPropsNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/FloatPropsNativeComponentViewManagerDelegate.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class FloatPropsNativeComponentViewManagerDelegate & FloatPropsNativeComponentViewManagerInterface> extends BaseViewManagerDelegate { - public FloatPropsNativeComponentViewManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"blurRadius\\": - mViewManager.setBlurRadius(view, value == null ? Float.NaN : ((Double) value).floatValue()); - break; - case \\"blurRadius2\\": - mViewManager.setBlurRadius2(view, value == null ? 0.001f : ((Double) value).floatValue()); - break; - case \\"blurRadius3\\": - mViewManager.setBlurRadius3(view, value == null ? 2.1f : ((Double) value).floatValue()); - break; - case \\"blurRadius4\\": - mViewManager.setBlurRadius4(view, value == null ? 0f : ((Double) value).floatValue()); - break; - case \\"blurRadius5\\": - mViewManager.setBlurRadius5(view, value == null ? 1f : ((Double) value).floatValue()); - break; - case \\"blurRadius6\\": - mViewManager.setBlurRadius6(view, value == null ? 0f : ((Double) value).floatValue()); - break; - case \\"blurRadiusNullable\\": - mViewManager.setBlurRadiusNullable(view, value == null ? null : ((Double) value).floatValue()); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate for 'ImagePropNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/ImagePropNativeComponentViewManagerDelegate.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class ImagePropNativeComponentViewManagerDelegate & ImagePropNativeComponentViewManagerInterface> extends BaseViewManagerDelegate { - public ImagePropNativeComponentViewManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"thumbImage\\": - mViewManager.setThumbImage(view, (ReadableMap) value); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate for 'IntegerPropNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/IntegerPropNativeComponentViewManagerDelegate.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class IntegerPropNativeComponentViewManagerDelegate & IntegerPropNativeComponentViewManagerInterface> extends BaseViewManagerDelegate { - public IntegerPropNativeComponentViewManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"progress1\\": - mViewManager.setProgress1(view, value == null ? 0 : ((Double) value).intValue()); - break; - case \\"progress2\\": - mViewManager.setProgress2(view, value == null ? -1 : ((Double) value).intValue()); - break; - case \\"progress3\\": - mViewManager.setProgress3(view, value == null ? 10 : ((Double) value).intValue()); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate for 'InterfaceOnlyNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/InterfaceOnlyNativeComponentViewManagerDelegate.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class InterfaceOnlyNativeComponentViewManagerDelegate & InterfaceOnlyNativeComponentViewManagerInterface> extends BaseViewManagerDelegate { - public InterfaceOnlyNativeComponentViewManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"title\\": - mViewManager.setTitle(view, value == null ? \\"\\" : (String) value); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate for 'MultiNativePropNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/MultiNativePropNativeComponentViewManagerDelegate.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.bridge.ColorPropConverter; -import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class MultiNativePropNativeComponentViewManagerDelegate & MultiNativePropNativeComponentViewManagerInterface> extends BaseViewManagerDelegate { - public MultiNativePropNativeComponentViewManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"thumbImage\\": - mViewManager.setThumbImage(view, (ReadableMap) value); - break; - case \\"color\\": - mViewManager.setColor(view, ColorPropConverter.getColor(value, view.getContext())); - break; - case \\"thumbTintColor\\": - mViewManager.setThumbTintColor(view, ColorPropConverter.getColor(value, view.getContext())); - break; - case \\"point\\": - mViewManager.setPoint(view, (ReadableMap) value); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate for 'NoPropsNoEventsNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/NoPropsNoEventsNativeComponentViewManagerDelegate.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class NoPropsNoEventsNativeComponentViewManagerDelegate & NoPropsNoEventsNativeComponentViewManagerInterface> extends BaseViewManagerDelegate { - public NoPropsNoEventsNativeComponentViewManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - super.setProperty(view, propName, value); - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate for 'ObjectPropsNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/ObjectPropsNativeComponentManagerDelegate.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class ObjectPropsNativeComponentManagerDelegate & ObjectPropsNativeComponentManagerInterface> extends BaseViewManagerDelegate { - public ObjectPropsNativeComponentManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"objectProp\\": - mViewManager.setObjectProp(view, (ReadableMap) value); - break; - case \\"objectArrayProp\\": - mViewManager.setObjectArrayProp(view, (ReadableMap) value); - break; - case \\"objectPrimitiveRequiredProp\\": - mViewManager.setObjectPrimitiveRequiredProp(view, (ReadableMap) value); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate for 'PointPropNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/PointPropNativeComponentViewManagerDelegate.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class PointPropNativeComponentViewManagerDelegate & PointPropNativeComponentViewManagerInterface> extends BaseViewManagerDelegate { - public PointPropNativeComponentViewManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"startPoint\\": - mViewManager.setStartPoint(view, (ReadableMap) value); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate for 'StringPropNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/StringPropNativeComponentViewManagerDelegate.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class StringPropNativeComponentViewManagerDelegate & StringPropNativeComponentViewManagerInterface> extends BaseViewManagerDelegate { - public StringPropNativeComponentViewManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"placeholder\\": - mViewManager.setPlaceholder(view, value == null ? \\"\\" : (String) value); - break; - case \\"defaultValue\\": - mViewManager.setDefaultValue(view, value == null ? null : (String) value); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; diff --git a/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GeneratePropsJavaInterface-test.js.snap b/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GeneratePropsJavaInterface-test.js.snap deleted file mode 100644 index d00d9c9eb372..000000000000 --- a/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GeneratePropsJavaInterface-test.js.snap +++ /dev/null @@ -1,394 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GeneratePropsJavaInterface can generate for 'ArrayPropsNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/ArrayPropsNativeComponentViewManagerInterface.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.bridge.ReadableArray; - -public interface ArrayPropsNativeComponentViewManagerInterface { - void setNames(T view, @Nullable ReadableArray value); - void setDisableds(T view, @Nullable ReadableArray value); - void setProgress(T view, @Nullable ReadableArray value); - void setRadii(T view, @Nullable ReadableArray value); - void setColors(T view, @Nullable ReadableArray value); - void setSrcs(T view, @Nullable ReadableArray value); - void setPoints(T view, @Nullable ReadableArray value); - void setSizes(T view, @Nullable ReadableArray value); - void setObject(T view, @Nullable ReadableArray value); - void setArrayOfObjects(T view, @Nullable ReadableArray value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate for 'BooleanPropNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/BooleanPropNativeComponentViewManagerInterface.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; - -public interface BooleanPropNativeComponentViewManagerInterface { - void setDisabled(T view, boolean value); - void setDisabledNullable(T view, @Nullable Boolean value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate for 'ColorPropNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/ColorPropNativeComponentViewManagerInterface.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; - -public interface ColorPropNativeComponentViewManagerInterface { - void setTintColor(T view, @Nullable Integer value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate for 'EdgeInsetsPropNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/EdgeInsetsPropNativeComponentViewManagerInterface.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; - -public interface EdgeInsetsPropNativeComponentViewManagerInterface { - // No props -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate for 'EnumPropNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/EnumPropNativeComponentViewManagerInterface.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; - -public interface EnumPropNativeComponentViewManagerInterface { - void setAlignment(T view, @Nullable String value); - void setIntervals(T view, @Nullable Integer value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate for 'EventNestedObjectPropsNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/EventNestedObjectPropsNativeComponentViewManagerInterface.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; - -public interface EventNestedObjectPropsNativeComponentViewManagerInterface { - void setDisabled(T view, boolean value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate for 'EventPropsNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/EventPropsNativeComponentViewManagerInterface.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; - -public interface EventPropsNativeComponentViewManagerInterface { - void setDisabled(T view, boolean value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate for 'FloatPropsNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/FloatPropsNativeComponentViewManagerInterface.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; - -public interface FloatPropsNativeComponentViewManagerInterface { - void setBlurRadius(T view, float value); - void setBlurRadius2(T view, float value); - void setBlurRadius3(T view, float value); - void setBlurRadius4(T view, float value); - void setBlurRadius5(T view, float value); - void setBlurRadius6(T view, float value); - void setBlurRadiusNullable(T view, @Nullable Float value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate for 'ImagePropNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/ImagePropNativeComponentViewManagerInterface.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.bridge.ReadableMap; - -public interface ImagePropNativeComponentViewManagerInterface { - void setThumbImage(T view, @Nullable ReadableMap value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate for 'IntegerPropNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/IntegerPropNativeComponentViewManagerInterface.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; - -public interface IntegerPropNativeComponentViewManagerInterface { - void setProgress1(T view, int value); - void setProgress2(T view, int value); - void setProgress3(T view, int value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate for 'InterfaceOnlyNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/InterfaceOnlyNativeComponentViewManagerInterface.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; - -public interface InterfaceOnlyNativeComponentViewManagerInterface { - void setTitle(T view, @Nullable String value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate for 'MultiNativePropNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/MultiNativePropNativeComponentViewManagerInterface.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.bridge.ReadableMap; - -public interface MultiNativePropNativeComponentViewManagerInterface { - void setThumbImage(T view, @Nullable ReadableMap value); - void setColor(T view, @Nullable Integer value); - void setThumbTintColor(T view, @Nullable Integer value); - void setPoint(T view, @Nullable ReadableMap value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate for 'NoPropsNoEventsNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/NoPropsNoEventsNativeComponentViewManagerInterface.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; - -public interface NoPropsNoEventsNativeComponentViewManagerInterface { - // No props -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate for 'ObjectPropsNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/ObjectPropsNativeComponentManagerInterface.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.bridge.ReadableMap; - -public interface ObjectPropsNativeComponentManagerInterface { - void setObjectProp(T view, @Nullable ReadableMap value); - void setObjectArrayProp(T view, @Nullable ReadableMap value); - void setObjectPrimitiveRequiredProp(T view, @Nullable ReadableMap value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate for 'PointPropNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/PointPropNativeComponentViewManagerInterface.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.bridge.ReadableMap; - -public interface PointPropNativeComponentViewManagerInterface { - void setStartPoint(T view, @Nullable ReadableMap value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate for 'StringPropNativeComponent.js' 1`] = ` -Object { - "java/com/facebook/react/viewmanagers/StringPropNativeComponentViewManagerInterface.java": "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; - -public interface StringPropNativeComponentViewManagerInterface { - void setPlaceholder(T view, @Nullable String value); - void setDefaultValue(T view, @Nullable String value); -} -", -} -`; diff --git a/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GenerateShadowNodeCpp-test.js.snap b/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GenerateShadowNodeCpp-test.js.snap deleted file mode 100644 index a37b7ccaf377..000000000000 --- a/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GenerateShadowNodeCpp-test.js.snap +++ /dev/null @@ -1,401 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GenerateShadowNodeCpp can generate for 'ArrayPropsNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char ArrayPropsNativeComponentViewComponentName[] = \\"ArrayPropsNativeComponentView\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate for 'BooleanPropNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char BooleanPropNativeComponentViewComponentName[] = \\"BooleanPropNativeComponentView\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate for 'ColorPropNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char ColorPropNativeComponentViewComponentName[] = \\"ColorPropNativeComponentView\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate for 'EdgeInsetsPropNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char EdgeInsetsPropNativeComponentViewComponentName[] = \\"EdgeInsetsPropNativeComponentView\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate for 'EnumPropNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char EnumPropNativeComponentViewComponentName[] = \\"EnumPropNativeComponentView\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate for 'EventNestedObjectPropsNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char EventNestedObjectPropsNativeComponentViewComponentName[] = \\"EventNestedObjectPropsNativeComponentView\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate for 'EventPropsNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char EventPropsNativeComponentViewComponentName[] = \\"EventPropsNativeComponentView\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate for 'FloatPropsNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char FloatPropsNativeComponentViewComponentName[] = \\"FloatPropsNativeComponentView\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate for 'ImagePropNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char ImagePropNativeComponentViewComponentName[] = \\"ImagePropNativeComponentView\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate for 'IntegerPropNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char IntegerPropNativeComponentViewComponentName[] = \\"IntegerPropNativeComponentView\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate for 'InterfaceOnlyNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate for 'MultiNativePropNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char MultiNativePropNativeComponentViewComponentName[] = \\"MultiNativePropNativeComponentView\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate for 'NoPropsNoEventsNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char NoPropsNoEventsNativeComponentViewComponentName[] = \\"NoPropsNoEventsNativeComponentView\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate for 'ObjectPropsNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char ObjectPropsNativeComponentComponentName[] = \\"ObjectPropsNativeComponent\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate for 'PointPropNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char PointPropNativeComponentViewComponentName[] = \\"PointPropNativeComponentView\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate for 'StringPropNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.cpp": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char StringPropNativeComponentViewComponentName[] = \\"StringPropNativeComponentView\\"; - -} // namespace react -} // namespace facebook -", -} -`; diff --git a/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GenerateShadowNodeH-test.js.snap b/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GenerateShadowNodeH-test.js.snap deleted file mode 100644 index 15357bb25717..000000000000 --- a/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GenerateShadowNodeH-test.js.snap +++ /dev/null @@ -1,632 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GenerateShadowNodeH can generate for 'ArrayPropsNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char ArrayPropsNativeComponentViewComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using ArrayPropsNativeComponentViewShadowNode = ConcreteViewShadowNode< - ArrayPropsNativeComponentViewComponentName, - ArrayPropsNativeComponentViewProps, - ArrayPropsNativeComponentViewEventEmitter, - ArrayPropsNativeComponentViewState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate for 'BooleanPropNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char BooleanPropNativeComponentViewComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using BooleanPropNativeComponentViewShadowNode = ConcreteViewShadowNode< - BooleanPropNativeComponentViewComponentName, - BooleanPropNativeComponentViewProps, - BooleanPropNativeComponentViewEventEmitter, - BooleanPropNativeComponentViewState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate for 'ColorPropNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char ColorPropNativeComponentViewComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using ColorPropNativeComponentViewShadowNode = ConcreteViewShadowNode< - ColorPropNativeComponentViewComponentName, - ColorPropNativeComponentViewProps, - ColorPropNativeComponentViewEventEmitter, - ColorPropNativeComponentViewState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate for 'EdgeInsetsPropNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char EdgeInsetsPropNativeComponentViewComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using EdgeInsetsPropNativeComponentViewShadowNode = ConcreteViewShadowNode< - EdgeInsetsPropNativeComponentViewComponentName, - EdgeInsetsPropNativeComponentViewProps, - EdgeInsetsPropNativeComponentViewEventEmitter, - EdgeInsetsPropNativeComponentViewState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate for 'EnumPropNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char EnumPropNativeComponentViewComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using EnumPropNativeComponentViewShadowNode = ConcreteViewShadowNode< - EnumPropNativeComponentViewComponentName, - EnumPropNativeComponentViewProps, - EnumPropNativeComponentViewEventEmitter, - EnumPropNativeComponentViewState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate for 'EventNestedObjectPropsNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char EventNestedObjectPropsNativeComponentViewComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using EventNestedObjectPropsNativeComponentViewShadowNode = ConcreteViewShadowNode< - EventNestedObjectPropsNativeComponentViewComponentName, - EventNestedObjectPropsNativeComponentViewProps, - EventNestedObjectPropsNativeComponentViewEventEmitter, - EventNestedObjectPropsNativeComponentViewState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate for 'EventPropsNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char EventPropsNativeComponentViewComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using EventPropsNativeComponentViewShadowNode = ConcreteViewShadowNode< - EventPropsNativeComponentViewComponentName, - EventPropsNativeComponentViewProps, - EventPropsNativeComponentViewEventEmitter, - EventPropsNativeComponentViewState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate for 'FloatPropsNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char FloatPropsNativeComponentViewComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using FloatPropsNativeComponentViewShadowNode = ConcreteViewShadowNode< - FloatPropsNativeComponentViewComponentName, - FloatPropsNativeComponentViewProps, - FloatPropsNativeComponentViewEventEmitter, - FloatPropsNativeComponentViewState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate for 'ImagePropNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char ImagePropNativeComponentViewComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using ImagePropNativeComponentViewShadowNode = ConcreteViewShadowNode< - ImagePropNativeComponentViewComponentName, - ImagePropNativeComponentViewProps, - ImagePropNativeComponentViewEventEmitter, - ImagePropNativeComponentViewState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate for 'IntegerPropNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char IntegerPropNativeComponentViewComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using IntegerPropNativeComponentViewShadowNode = ConcreteViewShadowNode< - IntegerPropNativeComponentViewComponentName, - IntegerPropNativeComponentViewProps, - IntegerPropNativeComponentViewEventEmitter, - IntegerPropNativeComponentViewState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate for 'InterfaceOnlyNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate for 'MultiNativePropNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char MultiNativePropNativeComponentViewComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using MultiNativePropNativeComponentViewShadowNode = ConcreteViewShadowNode< - MultiNativePropNativeComponentViewComponentName, - MultiNativePropNativeComponentViewProps, - MultiNativePropNativeComponentViewEventEmitter, - MultiNativePropNativeComponentViewState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate for 'NoPropsNoEventsNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char NoPropsNoEventsNativeComponentViewComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using NoPropsNoEventsNativeComponentViewShadowNode = ConcreteViewShadowNode< - NoPropsNoEventsNativeComponentViewComponentName, - NoPropsNoEventsNativeComponentViewProps, - NoPropsNoEventsNativeComponentViewEventEmitter, - NoPropsNoEventsNativeComponentViewState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate for 'ObjectPropsNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char ObjectPropsNativeComponentComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using ObjectPropsNativeComponentShadowNode = ConcreteViewShadowNode< - ObjectPropsNativeComponentComponentName, - ObjectPropsNativeComponentProps, - ObjectPropsNativeComponentEventEmitter, - ObjectPropsNativeComponentState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate for 'PointPropNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char PointPropNativeComponentViewComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using PointPropNativeComponentViewShadowNode = ConcreteViewShadowNode< - PointPropNativeComponentViewComponentName, - PointPropNativeComponentViewProps, - PointPropNativeComponentViewEventEmitter, - PointPropNativeComponentViewState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate for 'StringPropNativeComponent.js' 1`] = ` -Object { - "ShadowNodes.h": " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char StringPropNativeComponentViewComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using StringPropNativeComponentViewShadowNode = ConcreteViewShadowNode< - StringPropNativeComponentViewComponentName, - StringPropNativeComponentViewProps, - StringPropNativeComponentViewEventEmitter, - StringPropNativeComponentViewState>; - -} // namespace react -} // namespace facebook -", -} -`; diff --git a/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GenerateViewConfigJs-test.js.snap b/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GenerateViewConfigJs-test.js.snap deleted file mode 100644 index 400735e1e9ce..000000000000 --- a/packages/react-native-codegen/e2e/__tests__/components/__snapshots__/GenerateViewConfigJs-test.js.snap +++ /dev/null @@ -1,660 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GenerateViewConfigJs can generate for 'ArrayPropsNativeComponent.js' 1`] = ` -Map { - "RNCodegenModuleFixturesNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'ArrayPropsNativeComponentView'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'ArrayPropsNativeComponentView', - - validAttributes: { - names: true, - disableds: true, - progress: true, - radii: true, - - colors: { - process: require('react-native/Libraries/StyleSheet/processColorArray'), - }, - - srcs: true, - points: true, - sizes: true, - object: true, - arrayOfObjects: true, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate for 'BooleanPropNativeComponent.js' 1`] = ` -Map { - "RNCodegenModuleFixturesNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'BooleanPropNativeComponentView'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'BooleanPropNativeComponentView', - - validAttributes: { - disabled: true, - disabledNullable: true, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate for 'ColorPropNativeComponent.js' 1`] = ` -Map { - "RNCodegenModuleFixturesNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'ColorPropNativeComponentView'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'ColorPropNativeComponentView', - - validAttributes: { - tintColor: { - process: require('react-native/Libraries/StyleSheet/processColor'), - }, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate for 'EdgeInsetsPropNativeComponent.js' 1`] = ` -Map { - "RNCodegenModuleFixturesNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'EdgeInsetsPropNativeComponentView'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'EdgeInsetsPropNativeComponentView', - validAttributes: {}, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate for 'EnumPropNativeComponent.js' 1`] = ` -Map { - "RNCodegenModuleFixturesNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'EnumPropNativeComponentView'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'EnumPropNativeComponentView', - - validAttributes: { - alignment: true, - intervals: true, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate for 'EventNestedObjectPropsNativeComponent.js' 1`] = ` -Map { - "RNCodegenModuleFixturesNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); -const {ConditionallyIgnoredEventHandlers} = require('react-native/Libraries/NativeComponent/ViewConfigIgnore'); - -let nativeComponentName = 'EventNestedObjectPropsNativeComponentView'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'EventNestedObjectPropsNativeComponentView', - - bubblingEventTypes: { - topChange: { - phasedRegistrationNames: { - captured: 'onChangeCapture', - bubbled: 'onChange', - }, - }, - }, - - validAttributes: { - disabled: true, - - ...ConditionallyIgnoredEventHandlers({ - onChange: true, - }), - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate for 'EventPropsNativeComponent.js' 1`] = ` -Map { - "RNCodegenModuleFixturesNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); -const {ConditionallyIgnoredEventHandlers} = require('react-native/Libraries/NativeComponent/ViewConfigIgnore'); - -let nativeComponentName = 'EventPropsNativeComponentView'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'EventPropsNativeComponentView', - - bubblingEventTypes: { - paperDirectName: { - phasedRegistrationNames: { - captured: 'onChangeCapture', - bubbled: 'onChange', - }, - }, - - topEnd: { - phasedRegistrationNames: { - captured: 'onEndCapture', - bubbled: 'onEnd', - }, - }, - - paperBubblingName: { - phasedRegistrationNames: { - captured: 'onEventBubblingWithPaperNameCapture', - bubbled: 'onEventBubblingWithPaperName', - }, - }, - }, - - directEventTypes: { - topEventDirect: { - registrationName: 'onEventDirect', - }, - - paperDirectName: { - registrationName: 'onEventDirectWithPaperName', - }, - - paperBubblingName: { - registrationName: 'onOrientationChange', - }, - }, - - validAttributes: { - disabled: true, - - ...ConditionallyIgnoredEventHandlers({ - onChange: true, - onEventDirect: true, - onEventDirectWithPaperName: true, - onOrientationChange: true, - onEnd: true, - onEventBubblingWithPaperName: true, - }), - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate for 'FloatPropsNativeComponent.js' 1`] = ` -Map { - "RNCodegenModuleFixturesNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'FloatPropsNativeComponentView'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'FloatPropsNativeComponentView', - - validAttributes: { - blurRadius: true, - blurRadius2: true, - blurRadius3: true, - blurRadius4: true, - blurRadius5: true, - blurRadius6: true, - blurRadiusNullable: true, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate for 'ImagePropNativeComponent.js' 1`] = ` -Map { - "RNCodegenModuleFixturesNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'ImagePropNativeComponentView'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'ImagePropNativeComponentView', - - validAttributes: { - thumbImage: { - process: require('react-native/Libraries/Image/resolveAssetSource'), - }, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate for 'IntegerPropNativeComponent.js' 1`] = ` -Map { - "RNCodegenModuleFixturesNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'IntegerPropNativeComponentView'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'IntegerPropNativeComponentView', - - validAttributes: { - progress1: true, - progress2: true, - progress3: true, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate for 'InterfaceOnlyNativeComponent.js' 1`] = ` -Map { - "RNCodegenModuleFixturesNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); -const {ConditionallyIgnoredEventHandlers} = require('react-native/Libraries/NativeComponent/ViewConfigIgnore'); - -let nativeComponentName = 'RCTInterfaceOnlyComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'RCTInterfaceOnlyComponent', - - bubblingEventTypes: { - topChange: { - phasedRegistrationNames: { - captured: 'onChangeCapture', - bubbled: 'onChange', - }, - }, - }, - - validAttributes: { - title: true, - - ...ConditionallyIgnoredEventHandlers({ - onChange: true, - }), - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate for 'MultiNativePropNativeComponent.js' 1`] = ` -Map { - "RNCodegenModuleFixturesNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'MultiNativePropNativeComponentView'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'MultiNativePropNativeComponentView', - - validAttributes: { - thumbImage: { - process: require('react-native/Libraries/Image/resolveAssetSource'), - }, - - color: { - process: require('react-native/Libraries/StyleSheet/processColor'), - }, - - thumbTintColor: { - process: require('react-native/Libraries/StyleSheet/processColor'), - }, - - point: { - diff: require('react-native/Libraries/Utilities/differ/pointsDiffer'), - }, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate for 'NoPropsNoEventsNativeComponent.js' 1`] = ` -Map { - "RNCodegenModuleFixturesNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'NoPropsNoEventsNativeComponentView'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'NoPropsNoEventsNativeComponentView', - validAttributes: {}, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate for 'ObjectPropsNativeComponent.js' 1`] = ` -Map { - "RNCodegenModuleFixturesNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'ObjectPropsNativeComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'ObjectPropsNativeComponent', - - validAttributes: { - objectProp: true, - objectArrayProp: true, - objectPrimitiveRequiredProp: true, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate for 'PointPropNativeComponent.js' 1`] = ` -Map { - "RNCodegenModuleFixturesNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'PointPropNativeComponentView'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'PointPropNativeComponentView', - - validAttributes: { - startPoint: { - diff: require('react-native/Libraries/Utilities/differ/pointsDiffer'), - }, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate for 'StringPropNativeComponent.js' 1`] = ` -Map { - "RNCodegenModuleFixturesNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'StringPropNativeComponentView'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'StringPropNativeComponentView', - - validAttributes: { - placeholder: true, - defaultValue: true, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; diff --git a/packages/react-native-codegen/e2e/__tests__/modules/GenerateModuleObjCpp-test.js b/packages/react-native-codegen/e2e/__tests__/modules/GenerateModuleObjCpp-test.js deleted file mode 100644 index a6bb549d056a..000000000000 --- a/packages/react-native-codegen/e2e/__tests__/modules/GenerateModuleObjCpp-test.js +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const {parseFile} = require('../../../src/parsers/utils'); -const FlowParser = require('../../../src/parsers/flow'); -const generator = require('../../../src/generators/modules/GenerateModuleObjCpp'); -const fs = require('fs'); - -import type {SchemaType} from '../../../src/CodegenSchema'; - -const FIXTURE_DIR = `${__dirname}/../../__test_fixtures__/modules`; - -function getModules(): SchemaType { - const filenames: Array = fs.readdirSync(FIXTURE_DIR); - return filenames.reduce( - (accumulator, file) => { - const schema = parseFile( - `${FIXTURE_DIR}/${file}`, - FlowParser.buildSchema, - ); - return { - modules: { - ...accumulator.modules, - ...schema.modules, - }, - }; - }, - {modules: {}}, - ); -} - -describe('GenerateModuleObjCpp', () => { - it('can generate a header file NativeModule specs', () => { - const libName = 'RNCodegenModuleFixtures'; - const output = generator.generate(libName, getModules(), undefined, false); - expect(output.get(libName + '.h')).toMatchSnapshot(); - }); - - it('can generate a header file NativeModule specs with assume nonnull enabled', () => { - const libName = 'RNCodegenModuleFixtures'; - const output = generator.generate(libName, getModules(), undefined, true); - expect(output.get(libName + '.h')).toMatchSnapshot(); - }); - - it('can generate an implementation file NativeModule specs', () => { - const libName = 'RNCodegenModuleFixtures'; - const output = generator.generate(libName, getModules(), undefined, false); - expect(output.get(libName + '-generated.mm')).toMatchSnapshot(); - }); -}); diff --git a/packages/react-native-codegen/e2e/__tests__/modules/__snapshots__/GenerateModuleObjCpp-test.js.snap b/packages/react-native-codegen/e2e/__tests__/modules/__snapshots__/GenerateModuleObjCpp-test.js.snap deleted file mode 100644 index 13d1139ab9c5..000000000000 --- a/packages/react-native-codegen/e2e/__tests__/modules/__snapshots__/GenerateModuleObjCpp-test.js.snap +++ /dev/null @@ -1,3214 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GenerateModuleObjCpp can generate a header file NativeModule specs 1`] = ` -"/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleObjCpp - * - * We create an umbrella header (and corresponding implementation) here since - * Cxx compilation in BUCK has a limitation: source-code producing genrule()s - * must have a single output. More files => more genrule()s => slower builds. - */ - -#ifndef __cplusplus -#error This file must be compiled as Obj-C++. If you are importing it, you must change your file extension to .mm. -#endif -#import -#import -#import -#import -#import -#import -#import -#import -#import -#import - - -@protocol NativeArrayTurboModuleSpec - -- (NSArray *)getArray:(NSArray *)a; -- (NSArray *)getReadOnlyArray:(NSArray *)a; -- (NSArray *)getArrayWithAlias:(NSArray *)a - b:(NSArray *)b; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeArrayTurboModule' - */ - class JSI_EXPORT NativeArrayTurboModuleSpecJSI : public ObjCTurboModule { - public: - NativeArrayTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook - -@protocol NativeBooleanTurboModuleSpec - -- (NSNumber *)getBoolean:(BOOL)arg; -- (NSNumber *)getBooleanWithAlias:(BOOL)arg; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeBooleanTurboModule' - */ - class JSI_EXPORT NativeBooleanTurboModuleSpecJSI : public ObjCTurboModule { - public: - NativeBooleanTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook - -@protocol NativeCallbackTurboModuleSpec - -- (void)getValueWithCallback:(RCTResponseSenderBlock)callback; -- (void)getValueWithCallbackWithAlias:(RCTResponseSenderBlock)c; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeCallbackTurboModule' - */ - class JSI_EXPORT NativeCallbackTurboModuleSpecJSI : public ObjCTurboModule { - public: - NativeCallbackTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook - -@protocol NativeNullableTurboModuleSpec - -- (NSNumber * _Nullable)getBool:(NSNumber *)a; -- (NSNumber * _Nullable)getNumber:(NSNumber *)a; -- (NSString * _Nullable)getString:(NSNumber *)a; -- (NSArray> * _Nullable)getArray:(NSArray * _Nullable)a; -- (NSDictionary * _Nullable)getObject:(NSDictionary * _Nullable)a; -- (void)getValueWithPromise:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeNullableTurboModule' - */ - class JSI_EXPORT NativeNullableTurboModuleSpecJSI : public ObjCTurboModule { - public: - NativeNullableTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook - -@protocol NativeNumberTurboModuleSpec - -- (NSNumber *)getNumber:(double)arg; -- (NSNumber *)getNumberWithAlias:(double)arg; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeNumberTurboModule' - */ - class JSI_EXPORT NativeNumberTurboModuleSpecJSI : public ObjCTurboModule { - public: - NativeNumberTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook -namespace JS { - namespace NativeObjectTurboModule { - struct SpecDifficultObjectAE { - bool D() const; - double E() const; - NSString *F() const; - - SpecDifficultObjectAE(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (NativeObjectTurboModule_SpecDifficultObjectAE) -+ (RCTManagedPointer *)JS_NativeObjectTurboModule_SpecDifficultObjectAE:(id)json; -@end -namespace JS { - namespace NativeObjectTurboModule { - struct SpecDifficultObjectA { - bool D() const; - JS::NativeObjectTurboModule::SpecDifficultObjectAE E() const; - NSString *F() const; - - SpecDifficultObjectA(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (NativeObjectTurboModule_SpecDifficultObjectA) -+ (RCTManagedPointer *)JS_NativeObjectTurboModule_SpecDifficultObjectA:(id)json; -@end -namespace JS { - namespace NativeObjectTurboModule { - struct ConstantsEEE { - - struct Builder { - struct Input { - RCTRequired D; - RCTRequired E; - RCTRequired F; - }; - - /** Initialize with a set of values */ - Builder(const Input i); - /** Initialize with an existing ConstantsEEE */ - Builder(ConstantsEEE i); - /** Builds the object. Generally used only by the infrastructure. */ - NSDictionary *buildUnsafeRawValue() const { return _factory(); }; - private: - NSDictionary *(^_factory)(void); - }; - - static ConstantsEEE fromUnsafeRawValue(NSDictionary *const v) { return {v}; } - NSDictionary *unsafeRawValue() const { return _v; } - private: - ConstantsEEE(NSDictionary *const v) : _v(v) {} - NSDictionary *_v; - }; - } -} -namespace JS { - namespace NativeObjectTurboModule { - struct ConstantsEE { - - struct Builder { - struct Input { - RCTRequired D; - RCTRequired E; - RCTRequired F; - }; - - /** Initialize with a set of values */ - Builder(const Input i); - /** Initialize with an existing ConstantsEE */ - Builder(ConstantsEE i); - /** Builds the object. Generally used only by the infrastructure. */ - NSDictionary *buildUnsafeRawValue() const { return _factory(); }; - private: - NSDictionary *(^_factory)(void); - }; - - static ConstantsEE fromUnsafeRawValue(NSDictionary *const v) { return {v}; } - NSDictionary *unsafeRawValue() const { return _v; } - private: - ConstantsEE(NSDictionary *const v) : _v(v) {} - NSDictionary *_v; - }; - } -} -namespace JS { - namespace NativeObjectTurboModule { - struct ConstantsE { - - struct Builder { - struct Input { - RCTRequired D; - RCTRequired E; - RCTRequired F; - }; - - /** Initialize with a set of values */ - Builder(const Input i); - /** Initialize with an existing ConstantsE */ - Builder(ConstantsE i); - /** Builds the object. Generally used only by the infrastructure. */ - NSDictionary *buildUnsafeRawValue() const { return _factory(); }; - private: - NSDictionary *(^_factory)(void); - }; - - static ConstantsE fromUnsafeRawValue(NSDictionary *const v) { return {v}; } - NSDictionary *unsafeRawValue() const { return _v; } - private: - ConstantsE(NSDictionary *const v) : _v(v) {} - NSDictionary *_v; - }; - } -} -namespace JS { - namespace NativeObjectTurboModule { - struct Constants { - - struct Builder { - struct Input { - RCTRequired D; - RCTRequired E; - RCTRequired F; - }; - - /** Initialize with a set of values */ - Builder(const Input i); - /** Initialize with an existing Constants */ - Builder(Constants i); - /** Builds the object. Generally used only by the infrastructure. */ - NSDictionary *buildUnsafeRawValue() const { return _factory(); }; - private: - NSDictionary *(^_factory)(void); - }; - - static Constants fromUnsafeRawValue(NSDictionary *const v) { return {v}; } - NSDictionary *unsafeRawValue() const { return _v; } - private: - Constants(NSDictionary *const v) : _v(v) {} - NSDictionary *_v; - }; - } -} -@protocol NativeObjectTurboModuleSpec - -- (NSDictionary *)getGenericObject:(NSDictionary *)arg; -- (NSDictionary *)getGenericObjectReadOnly:(NSDictionary *)arg; -- (NSDictionary *)getGenericObjectWithAlias:(NSDictionary *)arg; -- (NSDictionary *)difficultObject:(JS::NativeObjectTurboModule::SpecDifficultObjectA &)A; -- (facebook::react::ModuleConstants)constantsToExport; -- (facebook::react::ModuleConstants)getConstants; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeObjectTurboModule' - */ - class JSI_EXPORT NativeObjectTurboModuleSpecJSI : public ObjCTurboModule { - public: - NativeObjectTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook -namespace JS { - namespace NativeOptionalObjectTurboModule { - struct ConstantsEEE { - - struct Builder { - struct Input { - std::optional D; - std::optional E; - NSString *F; - }; - - /** Initialize with a set of values */ - Builder(const Input i); - /** Initialize with an existing ConstantsEEE */ - Builder(ConstantsEEE i); - /** Builds the object. Generally used only by the infrastructure. */ - NSDictionary *buildUnsafeRawValue() const { return _factory(); }; - private: - NSDictionary *(^_factory)(void); - }; - - static ConstantsEEE fromUnsafeRawValue(NSDictionary *const v) { return {v}; } - NSDictionary *unsafeRawValue() const { return _v; } - private: - ConstantsEEE(NSDictionary *const v) : _v(v) {} - NSDictionary *_v; - }; - } -} -namespace JS { - namespace NativeOptionalObjectTurboModule { - struct ConstantsEE { - - struct Builder { - struct Input { - std::optional D; - std::optional E; - NSString *F; - }; - - /** Initialize with a set of values */ - Builder(const Input i); - /** Initialize with an existing ConstantsEE */ - Builder(ConstantsEE i); - /** Builds the object. Generally used only by the infrastructure. */ - NSDictionary *buildUnsafeRawValue() const { return _factory(); }; - private: - NSDictionary *(^_factory)(void); - }; - - static ConstantsEE fromUnsafeRawValue(NSDictionary *const v) { return {v}; } - NSDictionary *unsafeRawValue() const { return _v; } - private: - ConstantsEE(NSDictionary *const v) : _v(v) {} - NSDictionary *_v; - }; - } -} -namespace JS { - namespace NativeOptionalObjectTurboModule { - struct ConstantsE { - - struct Builder { - struct Input { - std::optional D; - std::optional E; - NSString *F; - }; - - /** Initialize with a set of values */ - Builder(const Input i); - /** Initialize with an existing ConstantsE */ - Builder(ConstantsE i); - /** Builds the object. Generally used only by the infrastructure. */ - NSDictionary *buildUnsafeRawValue() const { return _factory(); }; - private: - NSDictionary *(^_factory)(void); - }; - - static ConstantsE fromUnsafeRawValue(NSDictionary *const v) { return {v}; } - NSDictionary *unsafeRawValue() const { return _v; } - private: - ConstantsE(NSDictionary *const v) : _v(v) {} - NSDictionary *_v; - }; - } -} -namespace JS { - namespace NativeOptionalObjectTurboModule { - struct Constants { - - struct Builder { - struct Input { - std::optional D; - id _Nullable A; - std::optional E; - NSString *F; - }; - - /** Initialize with a set of values */ - Builder(const Input i); - /** Initialize with an existing Constants */ - Builder(Constants i); - /** Builds the object. Generally used only by the infrastructure. */ - NSDictionary *buildUnsafeRawValue() const { return _factory(); }; - private: - NSDictionary *(^_factory)(void); - }; - - static Constants fromUnsafeRawValue(NSDictionary *const v) { return {v}; } - NSDictionary *unsafeRawValue() const { return _v; } - private: - Constants(NSDictionary *const v) : _v(v) {} - NSDictionary *_v; - }; - } -} -@protocol NativeOptionalObjectTurboModuleSpec - -- (facebook::react::ModuleConstants)constantsToExport; -- (facebook::react::ModuleConstants)getConstants; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeOptionalObjectTurboModule' - */ - class JSI_EXPORT NativeOptionalObjectTurboModuleSpecJSI : public ObjCTurboModule { - public: - NativeOptionalObjectTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook - -@protocol NativePromiseTurboModuleSpec - -- (void)getValueWithPromise:(BOOL)error - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject; -- (void)getValueWithPromiseWithAlias:(NSString *)arg - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativePromiseTurboModule' - */ - class JSI_EXPORT NativePromiseTurboModuleSpecJSI : public ObjCTurboModule { - public: - NativePromiseTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook -namespace JS { - namespace NativeSampleTurboModule { - struct SpecGetObjectShapeArg { - double prop() const; - - SpecGetObjectShapeArg(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (NativeSampleTurboModule_SpecGetObjectShapeArg) -+ (RCTManagedPointer *)JS_NativeSampleTurboModule_SpecGetObjectShapeArg:(id)json; -@end -namespace JS { - namespace NativeSampleTurboModule { - struct Animal { - NSString *name() const; - - Animal(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (NativeSampleTurboModule_Animal) -+ (RCTManagedPointer *)JS_NativeSampleTurboModule_Animal:(id)json; -@end -namespace JS { - namespace NativeSampleTurboModule { - struct Constants { - - struct Builder { - struct Input { - RCTRequired const1; - RCTRequired const2; - RCTRequired const3; - }; - - /** Initialize with a set of values */ - Builder(const Input i); - /** Initialize with an existing Constants */ - Builder(Constants i); - /** Builds the object. Generally used only by the infrastructure. */ - NSDictionary *buildUnsafeRawValue() const { return _factory(); }; - private: - NSDictionary *(^_factory)(void); - }; - - static Constants fromUnsafeRawValue(NSDictionary *const v) { return {v}; } - NSDictionary *unsafeRawValue() const { return _v; } - private: - Constants(NSDictionary *const v) : _v(v) {} - NSDictionary *_v; - }; - } -} -@protocol NativeSampleTurboModuleSpec - -- (void)voidFunc; -- (NSNumber *)getBool:(BOOL)arg; -- (NSNumber *)getNumber:(double)arg; -- (NSString *)getString:(NSString *)arg; -- (NSArray> *)getArray:(NSArray *)arg; -- (NSDictionary *)getObject:(NSDictionary *)arg; -- (NSDictionary *)getObjectShape:(JS::NativeSampleTurboModule::SpecGetObjectShapeArg &)arg; -- (NSDictionary *)getAlias:(JS::NativeSampleTurboModule::Animal &)arg; -- (NSNumber *)getRootTag:(double)arg; -- (NSDictionary *)getValue:(double)x -getValuegetValuegetValuegetValuegetValuey:(NSString *)getValuegetValuegetValuegetValuegetValuey - z:(NSDictionary *)z; -- (void)getValueWithCallback:(RCTResponseSenderBlock)callback; -- (void)getValueWithPromise:(BOOL)error - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject; -- (facebook::react::ModuleConstants)constantsToExport; -- (facebook::react::ModuleConstants)getConstants; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeSampleTurboModule' - */ - class JSI_EXPORT NativeSampleTurboModuleSpecJSI : public ObjCTurboModule { - public: - NativeSampleTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook -namespace JS { - namespace NativeSampleTurboModuleArrays { - struct ConstantsIdElement { - - struct Builder { - struct Input { - RCTRequired prop; - }; - - /** Initialize with a set of values */ - Builder(const Input i); - /** Initialize with an existing ConstantsIdElement */ - Builder(ConstantsIdElement i); - /** Builds the object. Generally used only by the infrastructure. */ - NSDictionary *buildUnsafeRawValue() const { return _factory(); }; - private: - NSDictionary *(^_factory)(void); - }; - - static ConstantsIdElement fromUnsafeRawValue(NSDictionary *const v) { return {v}; } - NSDictionary *unsafeRawValue() const { return _v; } - private: - ConstantsIdElement(NSDictionary *const v) : _v(v) {} - NSDictionary *_v; - }; - } -} -namespace JS { - namespace NativeSampleTurboModuleArrays { - struct Constants { - - struct Builder { - struct Input { - RCTRequired> const1; - RCTRequired> const2; - RCTRequired> const3; - std::optional>> id_; - }; - - /** Initialize with a set of values */ - Builder(const Input i); - /** Initialize with an existing Constants */ - Builder(Constants i); - /** Builds the object. Generally used only by the infrastructure. */ - NSDictionary *buildUnsafeRawValue() const { return _factory(); }; - private: - NSDictionary *(^_factory)(void); - }; - - static Constants fromUnsafeRawValue(NSDictionary *const v) { return {v}; } - NSDictionary *unsafeRawValue() const { return _v; } - private: - Constants(NSDictionary *const v) : _v(v) {} - NSDictionary *_v; - }; - } -} -@protocol NativeSampleTurboModuleArraysSpec - -- (void)voidFunc; -- (NSArray *)getBool:(NSArray *)id; -- (NSArray *)getNumber:(NSArray *)arg; -- (NSArray *)getString:(NSArray *)arg; -- (NSArray> *> *)getArray:(NSArray *)arg; -- (NSArray *)getObject:(NSArray *)arg; -- (NSArray *)getObjectShape:(NSArray *)arg; -- (NSArray *)getAlias:(NSArray *)arg; -- (NSArray *)getRootTag:(NSArray *)arg; -- (NSArray *)getValue:(NSArray *)x - y:(NSArray *)y - z:(NSArray *)z; -- (void)getValueWithCallback:(RCTResponseSenderBlock)callback; -- (void)getValueWithPromise:(NSArray *)error - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject; -- (facebook::react::ModuleConstants)constantsToExport; -- (facebook::react::ModuleConstants)getConstants; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeSampleTurboModuleArrays' - */ - class JSI_EXPORT NativeSampleTurboModuleArraysSpecJSI : public ObjCTurboModule { - public: - NativeSampleTurboModuleArraysSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook -namespace JS { - namespace NativeSampleTurboModuleNullable { - struct SpecGetObjectShapeArg { - std::optional prop() const; - - SpecGetObjectShapeArg(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (NativeSampleTurboModuleNullable_SpecGetObjectShapeArg) -+ (RCTManagedPointer *)JS_NativeSampleTurboModuleNullable_SpecGetObjectShapeArg:(id)json; -@end -namespace JS { - namespace NativeSampleTurboModuleNullable { - struct Animal { - NSString *name() const; - - Animal(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (NativeSampleTurboModuleNullable_Animal) -+ (RCTManagedPointer *)JS_NativeSampleTurboModuleNullable_Animal:(id)json; -@end -namespace JS { - namespace NativeSampleTurboModuleNullable { - struct Constants { - - struct Builder { - struct Input { - RCTRequired> const1; - RCTRequired> const2; - RCTRequired const3; - }; - - /** Initialize with a set of values */ - Builder(const Input i); - /** Initialize with an existing Constants */ - Builder(Constants i); - /** Builds the object. Generally used only by the infrastructure. */ - NSDictionary *buildUnsafeRawValue() const { return _factory(); }; - private: - NSDictionary *(^_factory)(void); - }; - - static Constants fromUnsafeRawValue(NSDictionary *const v) { return {v}; } - NSDictionary *unsafeRawValue() const { return _v; } - private: - Constants(NSDictionary *const v) : _v(v) {} - NSDictionary *_v; - }; - } -} -@protocol NativeSampleTurboModuleNullableSpec - -- (void)voidFunc; -- (NSNumber * _Nullable)getBool:(NSNumber *)arg; -- (NSNumber * _Nullable)getNumber:(NSNumber *)arg; -- (NSString * _Nullable)getString:(NSString * _Nullable)arg; -- (NSArray> * _Nullable)getArray:(NSArray * _Nullable)arg; -- (NSDictionary * _Nullable)getObject:(NSDictionary * _Nullable)arg; -- (NSDictionary * _Nullable)getObjectShape:(JS::NativeSampleTurboModuleNullable::SpecGetObjectShapeArg &)arg; -- (NSDictionary * _Nullable)getAlias:(JS::NativeSampleTurboModuleNullable::Animal &)arg; -- (NSNumber * _Nullable)getRootTag:(NSNumber *)arg; -- (NSDictionary * _Nullable)getValue:(NSNumber *)x - y:(NSString * _Nullable)y - z:(NSDictionary * _Nullable)z; -- (void)getValueWithCallback:(RCTResponseSenderBlock)callback; -- (void)getValueWithPromise:(NSNumber *)error - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject; -- (facebook::react::ModuleConstants)constantsToExport; -- (facebook::react::ModuleConstants)getConstants; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeSampleTurboModuleNullable' - */ - class JSI_EXPORT NativeSampleTurboModuleNullableSpecJSI : public ObjCTurboModule { - public: - NativeSampleTurboModuleNullableSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook -namespace JS { - namespace NativeSampleTurboModuleNullableAndOptional { - struct SpecGetObjectShapeArg { - std::optional prop() const; - - SpecGetObjectShapeArg(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (NativeSampleTurboModuleNullableAndOptional_SpecGetObjectShapeArg) -+ (RCTManagedPointer *)JS_NativeSampleTurboModuleNullableAndOptional_SpecGetObjectShapeArg:(id)json; -@end -namespace JS { - namespace NativeSampleTurboModuleNullableAndOptional { - struct Animal { - NSString *name() const; - - Animal(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (NativeSampleTurboModuleNullableAndOptional_Animal) -+ (RCTManagedPointer *)JS_NativeSampleTurboModuleNullableAndOptional_Animal:(id)json; -@end -namespace JS { - namespace NativeSampleTurboModuleNullableAndOptional { - struct Constants { - - struct Builder { - struct Input { - std::optional const1; - std::optional const2; - NSString *const3; - }; - - /** Initialize with a set of values */ - Builder(const Input i); - /** Initialize with an existing Constants */ - Builder(Constants i); - /** Builds the object. Generally used only by the infrastructure. */ - NSDictionary *buildUnsafeRawValue() const { return _factory(); }; - private: - NSDictionary *(^_factory)(void); - }; - - static Constants fromUnsafeRawValue(NSDictionary *const v) { return {v}; } - NSDictionary *unsafeRawValue() const { return _v; } - private: - Constants(NSDictionary *const v) : _v(v) {} - NSDictionary *_v; - }; - } -} -@protocol NativeSampleTurboModuleNullableAndOptionalSpec - -- (void)voidFunc; -- (NSNumber * _Nullable)getBool:(NSNumber *)arg; -- (NSNumber * _Nullable)getNumber:(NSNumber *)arg; -- (NSString * _Nullable)getString:(NSString * _Nullable)arg; -- (NSArray> * _Nullable)getArray:(NSArray * _Nullable)arg; -- (NSDictionary * _Nullable)getObject:(NSDictionary * _Nullable)arg; -- (NSDictionary *)getObjectShape:(JS::NativeSampleTurboModuleNullableAndOptional::SpecGetObjectShapeArg &)arg; -- (NSDictionary * _Nullable)getAlias:(JS::NativeSampleTurboModuleNullableAndOptional::Animal &)arg; -- (NSNumber * _Nullable)getRootTag:(NSNumber *)arg; -- (NSDictionary * _Nullable)getValue:(NSNumber *)x - y:(NSString * _Nullable)y - z:(NSDictionary * _Nullable)z; -- (void)getValueWithCallback:(RCTResponseSenderBlock)callback; -- (void)getValueWithPromise:(NSNumber *)error - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject; -- (facebook::react::ModuleConstants)constantsToExport; -- (facebook::react::ModuleConstants)getConstants; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeSampleTurboModuleNullableAndOptional' - */ - class JSI_EXPORT NativeSampleTurboModuleNullableAndOptionalSpecJSI : public ObjCTurboModule { - public: - NativeSampleTurboModuleNullableAndOptionalSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook -namespace JS { - namespace NativeSampleTurboModuleOptional { - struct SpecGetObjectShapeArg { - std::optional prop() const; - - SpecGetObjectShapeArg(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (NativeSampleTurboModuleOptional_SpecGetObjectShapeArg) -+ (RCTManagedPointer *)JS_NativeSampleTurboModuleOptional_SpecGetObjectShapeArg:(id)json; -@end -namespace JS { - namespace NativeSampleTurboModuleOptional { - struct Animal { - NSString *name() const; - - Animal(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (NativeSampleTurboModuleOptional_Animal) -+ (RCTManagedPointer *)JS_NativeSampleTurboModuleOptional_Animal:(id)json; -@end -namespace JS { - namespace NativeSampleTurboModuleOptional { - struct Constants { - - struct Builder { - struct Input { - std::optional const1; - std::optional const2; - NSString *const3; - }; - - /** Initialize with a set of values */ - Builder(const Input i); - /** Initialize with an existing Constants */ - Builder(Constants i); - /** Builds the object. Generally used only by the infrastructure. */ - NSDictionary *buildUnsafeRawValue() const { return _factory(); }; - private: - NSDictionary *(^_factory)(void); - }; - - static Constants fromUnsafeRawValue(NSDictionary *const v) { return {v}; } - NSDictionary *unsafeRawValue() const { return _v; } - private: - Constants(NSDictionary *const v) : _v(v) {} - NSDictionary *_v; - }; - } -} -@protocol NativeSampleTurboModuleOptionalSpec - -- (void)voidFunc; -- (NSNumber *)getBool:(NSNumber *)arg; -- (NSNumber *)getNumber:(NSNumber *)arg; -- (NSString *)getString:(NSString *)arg; -- (NSArray> *)getArray:(NSArray *)arg; -- (NSDictionary *)getObject:(NSDictionary *)arg; -- (NSDictionary *)getObjectShape:(JS::NativeSampleTurboModuleOptional::SpecGetObjectShapeArg &)arg; -- (NSDictionary *)getAlias:(JS::NativeSampleTurboModuleOptional::Animal &)arg; -- (NSNumber *)getRootTag:(NSNumber *)arg; -- (NSDictionary *)getValue:(NSNumber *)x - y:(NSString *)y - z:(NSDictionary *)z; -- (void)getValueWithCallback:(RCTResponseSenderBlock)callback; -- (void)getValueWithPromise:(NSNumber *)error - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject; -- (facebook::react::ModuleConstants)constantsToExport; -- (facebook::react::ModuleConstants)getConstants; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeSampleTurboModuleOptional' - */ - class JSI_EXPORT NativeSampleTurboModuleOptionalSpecJSI : public ObjCTurboModule { - public: - NativeSampleTurboModuleOptionalSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook - -@protocol NativeStringTurboModuleSpec - -- (NSString *)getString:(NSString *)arg; -- (NSString *)getStringWithAlias:(NSString *)arg; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeStringTurboModule' - */ - class JSI_EXPORT NativeStringTurboModuleSpecJSI : public ObjCTurboModule { - public: - NativeStringTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook - - - - - -inline bool JS::NativeObjectTurboModule::SpecDifficultObjectAE::D() const -{ - id const p = _v[@\\"D\\"]; - return RCTBridgingToBool(p); -} -inline double JS::NativeObjectTurboModule::SpecDifficultObjectAE::E() const -{ - id const p = _v[@\\"E\\"]; - return RCTBridgingToDouble(p); -} -inline NSString *JS::NativeObjectTurboModule::SpecDifficultObjectAE::F() const -{ - id const p = _v[@\\"F\\"]; - return RCTBridgingToString(p); -} -inline bool JS::NativeObjectTurboModule::SpecDifficultObjectA::D() const -{ - id const p = _v[@\\"D\\"]; - return RCTBridgingToBool(p); -} -inline JS::NativeObjectTurboModule::SpecDifficultObjectAE JS::NativeObjectTurboModule::SpecDifficultObjectA::E() const -{ - id const p = _v[@\\"E\\"]; - return JS::NativeObjectTurboModule::SpecDifficultObjectAE(p); -} -inline NSString *JS::NativeObjectTurboModule::SpecDifficultObjectA::F() const -{ - id const p = _v[@\\"F\\"]; - return RCTBridgingToString(p); -} -inline JS::NativeObjectTurboModule::ConstantsEEE::Builder::Builder(const Input i) : _factory(^{ - NSMutableDictionary *d = [NSMutableDictionary new]; - auto D = i.D.get(); - d[@\\"D\\"] = @(D); - auto E = i.E.get(); - d[@\\"E\\"] = @(E); - auto F = i.F.get(); - d[@\\"F\\"] = F; - return d; -}) {} -inline JS::NativeObjectTurboModule::ConstantsEEE::Builder::Builder(ConstantsEEE i) : _factory(^{ - return i.unsafeRawValue(); -}) {} -inline JS::NativeObjectTurboModule::ConstantsEE::Builder::Builder(const Input i) : _factory(^{ - NSMutableDictionary *d = [NSMutableDictionary new]; - auto D = i.D.get(); - d[@\\"D\\"] = @(D); - auto E = i.E.get(); - d[@\\"E\\"] = E.buildUnsafeRawValue(); - auto F = i.F.get(); - d[@\\"F\\"] = F; - return d; -}) {} -inline JS::NativeObjectTurboModule::ConstantsEE::Builder::Builder(ConstantsEE i) : _factory(^{ - return i.unsafeRawValue(); -}) {} -inline JS::NativeObjectTurboModule::ConstantsE::Builder::Builder(const Input i) : _factory(^{ - NSMutableDictionary *d = [NSMutableDictionary new]; - auto D = i.D.get(); - d[@\\"D\\"] = @(D); - auto E = i.E.get(); - d[@\\"E\\"] = E.buildUnsafeRawValue(); - auto F = i.F.get(); - d[@\\"F\\"] = F; - return d; -}) {} -inline JS::NativeObjectTurboModule::ConstantsE::Builder::Builder(ConstantsE i) : _factory(^{ - return i.unsafeRawValue(); -}) {} -inline JS::NativeObjectTurboModule::Constants::Builder::Builder(const Input i) : _factory(^{ - NSMutableDictionary *d = [NSMutableDictionary new]; - auto D = i.D.get(); - d[@\\"D\\"] = @(D); - auto E = i.E.get(); - d[@\\"E\\"] = E.buildUnsafeRawValue(); - auto F = i.F.get(); - d[@\\"F\\"] = F; - return d; -}) {} -inline JS::NativeObjectTurboModule::Constants::Builder::Builder(Constants i) : _factory(^{ - return i.unsafeRawValue(); -}) {} -inline JS::NativeOptionalObjectTurboModule::ConstantsEEE::Builder::Builder(const Input i) : _factory(^{ - NSMutableDictionary *d = [NSMutableDictionary new]; - auto D = i.D; - d[@\\"D\\"] = D.has_value() ? @((BOOL)D.value()) : nil; - auto E = i.E; - d[@\\"E\\"] = E.has_value() ? @((double)E.value()) : nil; - auto F = i.F; - d[@\\"F\\"] = F; - return d; -}) {} -inline JS::NativeOptionalObjectTurboModule::ConstantsEEE::Builder::Builder(ConstantsEEE i) : _factory(^{ - return i.unsafeRawValue(); -}) {} -inline JS::NativeOptionalObjectTurboModule::ConstantsEE::Builder::Builder(const Input i) : _factory(^{ - NSMutableDictionary *d = [NSMutableDictionary new]; - auto D = i.D; - d[@\\"D\\"] = D.has_value() ? @((BOOL)D.value()) : nil; - auto E = i.E; - d[@\\"E\\"] = E.has_value() ? E.value().buildUnsafeRawValue() : nil; - auto F = i.F; - d[@\\"F\\"] = F; - return d; -}) {} -inline JS::NativeOptionalObjectTurboModule::ConstantsEE::Builder::Builder(ConstantsEE i) : _factory(^{ - return i.unsafeRawValue(); -}) {} -inline JS::NativeOptionalObjectTurboModule::ConstantsE::Builder::Builder(const Input i) : _factory(^{ - NSMutableDictionary *d = [NSMutableDictionary new]; - auto D = i.D; - d[@\\"D\\"] = D.has_value() ? @((BOOL)D.value()) : nil; - auto E = i.E; - d[@\\"E\\"] = E.has_value() ? E.value().buildUnsafeRawValue() : nil; - auto F = i.F; - d[@\\"F\\"] = F; - return d; -}) {} -inline JS::NativeOptionalObjectTurboModule::ConstantsE::Builder::Builder(ConstantsE i) : _factory(^{ - return i.unsafeRawValue(); -}) {} -inline JS::NativeOptionalObjectTurboModule::Constants::Builder::Builder(const Input i) : _factory(^{ - NSMutableDictionary *d = [NSMutableDictionary new]; - auto D = i.D; - d[@\\"D\\"] = D.has_value() ? @((BOOL)D.value()) : nil; - auto A = i.A; - d[@\\"A\\"] = A; - auto E = i.E; - d[@\\"E\\"] = E.has_value() ? E.value().buildUnsafeRawValue() : nil; - auto F = i.F; - d[@\\"F\\"] = F; - return d; -}) {} -inline JS::NativeOptionalObjectTurboModule::Constants::Builder::Builder(Constants i) : _factory(^{ - return i.unsafeRawValue(); -}) {} - -inline double JS::NativeSampleTurboModule::SpecGetObjectShapeArg::prop() const -{ - id const p = _v[@\\"prop\\"]; - return RCTBridgingToDouble(p); -} -inline NSString *JS::NativeSampleTurboModule::Animal::name() const -{ - id const p = _v[@\\"name\\"]; - return RCTBridgingToString(p); -} -inline JS::NativeSampleTurboModule::Constants::Builder::Builder(const Input i) : _factory(^{ - NSMutableDictionary *d = [NSMutableDictionary new]; - auto const1 = i.const1.get(); - d[@\\"const1\\"] = @(const1); - auto const2 = i.const2.get(); - d[@\\"const2\\"] = @(const2); - auto const3 = i.const3.get(); - d[@\\"const3\\"] = const3; - return d; -}) {} -inline JS::NativeSampleTurboModule::Constants::Builder::Builder(Constants i) : _factory(^{ - return i.unsafeRawValue(); -}) {} -inline JS::NativeSampleTurboModuleArrays::ConstantsIdElement::Builder::Builder(const Input i) : _factory(^{ - NSMutableDictionary *d = [NSMutableDictionary new]; - auto prop = i.prop.get(); - d[@\\"prop\\"] = @(prop); - return d; -}) {} -inline JS::NativeSampleTurboModuleArrays::ConstantsIdElement::Builder::Builder(ConstantsIdElement i) : _factory(^{ - return i.unsafeRawValue(); -}) {} -inline JS::NativeSampleTurboModuleArrays::Constants::Builder::Builder(const Input i) : _factory(^{ - NSMutableDictionary *d = [NSMutableDictionary new]; - auto const1 = i.const1.get(); - d[@\\"const1\\"] = RCTConvertVecToArray(const1, ^id(bool el_) { return @(el_); }); - auto const2 = i.const2.get(); - d[@\\"const2\\"] = RCTConvertVecToArray(const2, ^id(double el_) { return @(el_); }); - auto const3 = i.const3.get(); - d[@\\"const3\\"] = RCTConvertVecToArray(const3, ^id(NSString * el_) { return el_; }); - auto id_ = i.id_; - d[@\\"id\\"] = RCTConvertOptionalVecToArray(id_, ^id(std::optional el_) { return el_.has_value() ? el_.value().buildUnsafeRawValue() : nil; }); - return d; -}) {} -inline JS::NativeSampleTurboModuleArrays::Constants::Builder::Builder(Constants i) : _factory(^{ - return i.unsafeRawValue(); -}) {} -inline std::optional JS::NativeSampleTurboModuleNullable::SpecGetObjectShapeArg::prop() const -{ - id const p = _v[@\\"prop\\"]; - return RCTBridgingToOptionalDouble(p); -} -inline NSString *JS::NativeSampleTurboModuleNullable::Animal::name() const -{ - id const p = _v[@\\"name\\"]; - return RCTBridgingToOptionalString(p); -} -inline JS::NativeSampleTurboModuleNullable::Constants::Builder::Builder(const Input i) : _factory(^{ - NSMutableDictionary *d = [NSMutableDictionary new]; - auto const1 = i.const1.get(); - d[@\\"const1\\"] = const1.has_value() ? @((BOOL)const1.value()) : nil; - auto const2 = i.const2.get(); - d[@\\"const2\\"] = const2.has_value() ? @((double)const2.value()) : nil; - auto const3 = i.const3.get(); - d[@\\"const3\\"] = const3; - return d; -}) {} -inline JS::NativeSampleTurboModuleNullable::Constants::Builder::Builder(Constants i) : _factory(^{ - return i.unsafeRawValue(); -}) {} -inline std::optional JS::NativeSampleTurboModuleNullableAndOptional::SpecGetObjectShapeArg::prop() const -{ - id const p = _v[@\\"prop\\"]; - return RCTBridgingToOptionalDouble(p); -} -inline NSString *JS::NativeSampleTurboModuleNullableAndOptional::Animal::name() const -{ - id const p = _v[@\\"name\\"]; - return RCTBridgingToOptionalString(p); -} -inline JS::NativeSampleTurboModuleNullableAndOptional::Constants::Builder::Builder(const Input i) : _factory(^{ - NSMutableDictionary *d = [NSMutableDictionary new]; - auto const1 = i.const1; - d[@\\"const1\\"] = const1.has_value() ? @((BOOL)const1.value()) : nil; - auto const2 = i.const2; - d[@\\"const2\\"] = const2.has_value() ? @((double)const2.value()) : nil; - auto const3 = i.const3; - d[@\\"const3\\"] = const3; - return d; -}) {} -inline JS::NativeSampleTurboModuleNullableAndOptional::Constants::Builder::Builder(Constants i) : _factory(^{ - return i.unsafeRawValue(); -}) {} -inline std::optional JS::NativeSampleTurboModuleOptional::SpecGetObjectShapeArg::prop() const -{ - id const p = _v[@\\"prop\\"]; - return RCTBridgingToOptionalDouble(p); -} -inline NSString *JS::NativeSampleTurboModuleOptional::Animal::name() const -{ - id const p = _v[@\\"name\\"]; - return RCTBridgingToOptionalString(p); -} -inline JS::NativeSampleTurboModuleOptional::Constants::Builder::Builder(const Input i) : _factory(^{ - NSMutableDictionary *d = [NSMutableDictionary new]; - auto const1 = i.const1; - d[@\\"const1\\"] = const1.has_value() ? @((BOOL)const1.value()) : nil; - auto const2 = i.const2; - d[@\\"const2\\"] = const2.has_value() ? @((double)const2.value()) : nil; - auto const3 = i.const3; - d[@\\"const3\\"] = const3; - return d; -}) {} -inline JS::NativeSampleTurboModuleOptional::Constants::Builder::Builder(Constants i) : _factory(^{ - return i.unsafeRawValue(); -}) {} - -" -`; - -exports[`GenerateModuleObjCpp can generate a header file NativeModule specs with assume nonnull enabled 1`] = ` -"/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleObjCpp - * - * We create an umbrella header (and corresponding implementation) here since - * Cxx compilation in BUCK has a limitation: source-code producing genrule()s - * must have a single output. More files => more genrule()s => slower builds. - */ - -#ifndef __cplusplus -#error This file must be compiled as Obj-C++. If you are importing it, you must change your file extension to .mm. -#endif -#import -#import -#import -#import -#import -#import -#import -#import -#import -#import - - -NS_ASSUME_NONNULL_BEGIN - -@protocol NativeArrayTurboModuleSpec - -- (NSArray *)getArray:(NSArray *)a; -- (NSArray *)getReadOnlyArray:(NSArray *)a; -- (NSArray *)getArrayWithAlias:(NSArray *)a - b:(NSArray *)b; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeArrayTurboModule' - */ - class JSI_EXPORT NativeArrayTurboModuleSpecJSI : public ObjCTurboModule { - public: - NativeArrayTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook - -@protocol NativeBooleanTurboModuleSpec - -- (NSNumber *)getBoolean:(BOOL)arg; -- (NSNumber *)getBooleanWithAlias:(BOOL)arg; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeBooleanTurboModule' - */ - class JSI_EXPORT NativeBooleanTurboModuleSpecJSI : public ObjCTurboModule { - public: - NativeBooleanTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook - -@protocol NativeCallbackTurboModuleSpec - -- (void)getValueWithCallback:(RCTResponseSenderBlock)callback; -- (void)getValueWithCallbackWithAlias:(RCTResponseSenderBlock)c; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeCallbackTurboModule' - */ - class JSI_EXPORT NativeCallbackTurboModuleSpecJSI : public ObjCTurboModule { - public: - NativeCallbackTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook - -@protocol NativeNullableTurboModuleSpec - -- (NSNumber * _Nullable)getBool:(NSNumber *)a; -- (NSNumber * _Nullable)getNumber:(NSNumber *)a; -- (NSString * _Nullable)getString:(NSNumber *)a; -- (NSArray> * _Nullable)getArray:(NSArray * _Nullable)a; -- (NSDictionary * _Nullable)getObject:(NSDictionary * _Nullable)a; -- (void)getValueWithPromise:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeNullableTurboModule' - */ - class JSI_EXPORT NativeNullableTurboModuleSpecJSI : public ObjCTurboModule { - public: - NativeNullableTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook - -@protocol NativeNumberTurboModuleSpec - -- (NSNumber *)getNumber:(double)arg; -- (NSNumber *)getNumberWithAlias:(double)arg; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeNumberTurboModule' - */ - class JSI_EXPORT NativeNumberTurboModuleSpecJSI : public ObjCTurboModule { - public: - NativeNumberTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook -namespace JS { - namespace NativeObjectTurboModule { - struct SpecDifficultObjectAE { - bool D() const; - double E() const; - NSString *F() const; - - SpecDifficultObjectAE(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (NativeObjectTurboModule_SpecDifficultObjectAE) -+ (RCTManagedPointer *)JS_NativeObjectTurboModule_SpecDifficultObjectAE:(id)json; -@end -namespace JS { - namespace NativeObjectTurboModule { - struct SpecDifficultObjectA { - bool D() const; - JS::NativeObjectTurboModule::SpecDifficultObjectAE E() const; - NSString *F() const; - - SpecDifficultObjectA(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (NativeObjectTurboModule_SpecDifficultObjectA) -+ (RCTManagedPointer *)JS_NativeObjectTurboModule_SpecDifficultObjectA:(id)json; -@end -namespace JS { - namespace NativeObjectTurboModule { - struct ConstantsEEE { - - struct Builder { - struct Input { - RCTRequired D; - RCTRequired E; - RCTRequired F; - }; - - /** Initialize with a set of values */ - Builder(const Input i); - /** Initialize with an existing ConstantsEEE */ - Builder(ConstantsEEE i); - /** Builds the object. Generally used only by the infrastructure. */ - NSDictionary *buildUnsafeRawValue() const { return _factory(); }; - private: - NSDictionary *(^_factory)(void); - }; - - static ConstantsEEE fromUnsafeRawValue(NSDictionary *const v) { return {v}; } - NSDictionary *unsafeRawValue() const { return _v; } - private: - ConstantsEEE(NSDictionary *const v) : _v(v) {} - NSDictionary *_v; - }; - } -} -namespace JS { - namespace NativeObjectTurboModule { - struct ConstantsEE { - - struct Builder { - struct Input { - RCTRequired D; - RCTRequired E; - RCTRequired F; - }; - - /** Initialize with a set of values */ - Builder(const Input i); - /** Initialize with an existing ConstantsEE */ - Builder(ConstantsEE i); - /** Builds the object. Generally used only by the infrastructure. */ - NSDictionary *buildUnsafeRawValue() const { return _factory(); }; - private: - NSDictionary *(^_factory)(void); - }; - - static ConstantsEE fromUnsafeRawValue(NSDictionary *const v) { return {v}; } - NSDictionary *unsafeRawValue() const { return _v; } - private: - ConstantsEE(NSDictionary *const v) : _v(v) {} - NSDictionary *_v; - }; - } -} -namespace JS { - namespace NativeObjectTurboModule { - struct ConstantsE { - - struct Builder { - struct Input { - RCTRequired D; - RCTRequired E; - RCTRequired F; - }; - - /** Initialize with a set of values */ - Builder(const Input i); - /** Initialize with an existing ConstantsE */ - Builder(ConstantsE i); - /** Builds the object. Generally used only by the infrastructure. */ - NSDictionary *buildUnsafeRawValue() const { return _factory(); }; - private: - NSDictionary *(^_factory)(void); - }; - - static ConstantsE fromUnsafeRawValue(NSDictionary *const v) { return {v}; } - NSDictionary *unsafeRawValue() const { return _v; } - private: - ConstantsE(NSDictionary *const v) : _v(v) {} - NSDictionary *_v; - }; - } -} -namespace JS { - namespace NativeObjectTurboModule { - struct Constants { - - struct Builder { - struct Input { - RCTRequired D; - RCTRequired E; - RCTRequired F; - }; - - /** Initialize with a set of values */ - Builder(const Input i); - /** Initialize with an existing Constants */ - Builder(Constants i); - /** Builds the object. Generally used only by the infrastructure. */ - NSDictionary *buildUnsafeRawValue() const { return _factory(); }; - private: - NSDictionary *(^_factory)(void); - }; - - static Constants fromUnsafeRawValue(NSDictionary *const v) { return {v}; } - NSDictionary *unsafeRawValue() const { return _v; } - private: - Constants(NSDictionary *const v) : _v(v) {} - NSDictionary *_v; - }; - } -} -@protocol NativeObjectTurboModuleSpec - -- (NSDictionary *)getGenericObject:(NSDictionary *)arg; -- (NSDictionary *)getGenericObjectReadOnly:(NSDictionary *)arg; -- (NSDictionary *)getGenericObjectWithAlias:(NSDictionary *)arg; -- (NSDictionary *)difficultObject:(JS::NativeObjectTurboModule::SpecDifficultObjectA &)A; -- (facebook::react::ModuleConstants)constantsToExport; -- (facebook::react::ModuleConstants)getConstants; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeObjectTurboModule' - */ - class JSI_EXPORT NativeObjectTurboModuleSpecJSI : public ObjCTurboModule { - public: - NativeObjectTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook -namespace JS { - namespace NativeOptionalObjectTurboModule { - struct ConstantsEEE { - - struct Builder { - struct Input { - std::optional D; - std::optional E; - NSString *F; - }; - - /** Initialize with a set of values */ - Builder(const Input i); - /** Initialize with an existing ConstantsEEE */ - Builder(ConstantsEEE i); - /** Builds the object. Generally used only by the infrastructure. */ - NSDictionary *buildUnsafeRawValue() const { return _factory(); }; - private: - NSDictionary *(^_factory)(void); - }; - - static ConstantsEEE fromUnsafeRawValue(NSDictionary *const v) { return {v}; } - NSDictionary *unsafeRawValue() const { return _v; } - private: - ConstantsEEE(NSDictionary *const v) : _v(v) {} - NSDictionary *_v; - }; - } -} -namespace JS { - namespace NativeOptionalObjectTurboModule { - struct ConstantsEE { - - struct Builder { - struct Input { - std::optional D; - std::optional E; - NSString *F; - }; - - /** Initialize with a set of values */ - Builder(const Input i); - /** Initialize with an existing ConstantsEE */ - Builder(ConstantsEE i); - /** Builds the object. Generally used only by the infrastructure. */ - NSDictionary *buildUnsafeRawValue() const { return _factory(); }; - private: - NSDictionary *(^_factory)(void); - }; - - static ConstantsEE fromUnsafeRawValue(NSDictionary *const v) { return {v}; } - NSDictionary *unsafeRawValue() const { return _v; } - private: - ConstantsEE(NSDictionary *const v) : _v(v) {} - NSDictionary *_v; - }; - } -} -namespace JS { - namespace NativeOptionalObjectTurboModule { - struct ConstantsE { - - struct Builder { - struct Input { - std::optional D; - std::optional E; - NSString *F; - }; - - /** Initialize with a set of values */ - Builder(const Input i); - /** Initialize with an existing ConstantsE */ - Builder(ConstantsE i); - /** Builds the object. Generally used only by the infrastructure. */ - NSDictionary *buildUnsafeRawValue() const { return _factory(); }; - private: - NSDictionary *(^_factory)(void); - }; - - static ConstantsE fromUnsafeRawValue(NSDictionary *const v) { return {v}; } - NSDictionary *unsafeRawValue() const { return _v; } - private: - ConstantsE(NSDictionary *const v) : _v(v) {} - NSDictionary *_v; - }; - } -} -namespace JS { - namespace NativeOptionalObjectTurboModule { - struct Constants { - - struct Builder { - struct Input { - std::optional D; - id _Nullable A; - std::optional E; - NSString *F; - }; - - /** Initialize with a set of values */ - Builder(const Input i); - /** Initialize with an existing Constants */ - Builder(Constants i); - /** Builds the object. Generally used only by the infrastructure. */ - NSDictionary *buildUnsafeRawValue() const { return _factory(); }; - private: - NSDictionary *(^_factory)(void); - }; - - static Constants fromUnsafeRawValue(NSDictionary *const v) { return {v}; } - NSDictionary *unsafeRawValue() const { return _v; } - private: - Constants(NSDictionary *const v) : _v(v) {} - NSDictionary *_v; - }; - } -} -@protocol NativeOptionalObjectTurboModuleSpec - -- (facebook::react::ModuleConstants)constantsToExport; -- (facebook::react::ModuleConstants)getConstants; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeOptionalObjectTurboModule' - */ - class JSI_EXPORT NativeOptionalObjectTurboModuleSpecJSI : public ObjCTurboModule { - public: - NativeOptionalObjectTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook - -@protocol NativePromiseTurboModuleSpec - -- (void)getValueWithPromise:(BOOL)error - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject; -- (void)getValueWithPromiseWithAlias:(NSString *)arg - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativePromiseTurboModule' - */ - class JSI_EXPORT NativePromiseTurboModuleSpecJSI : public ObjCTurboModule { - public: - NativePromiseTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook -namespace JS { - namespace NativeSampleTurboModule { - struct SpecGetObjectShapeArg { - double prop() const; - - SpecGetObjectShapeArg(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (NativeSampleTurboModule_SpecGetObjectShapeArg) -+ (RCTManagedPointer *)JS_NativeSampleTurboModule_SpecGetObjectShapeArg:(id)json; -@end -namespace JS { - namespace NativeSampleTurboModule { - struct Animal { - NSString *name() const; - - Animal(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (NativeSampleTurboModule_Animal) -+ (RCTManagedPointer *)JS_NativeSampleTurboModule_Animal:(id)json; -@end -namespace JS { - namespace NativeSampleTurboModule { - struct Constants { - - struct Builder { - struct Input { - RCTRequired const1; - RCTRequired const2; - RCTRequired const3; - }; - - /** Initialize with a set of values */ - Builder(const Input i); - /** Initialize with an existing Constants */ - Builder(Constants i); - /** Builds the object. Generally used only by the infrastructure. */ - NSDictionary *buildUnsafeRawValue() const { return _factory(); }; - private: - NSDictionary *(^_factory)(void); - }; - - static Constants fromUnsafeRawValue(NSDictionary *const v) { return {v}; } - NSDictionary *unsafeRawValue() const { return _v; } - private: - Constants(NSDictionary *const v) : _v(v) {} - NSDictionary *_v; - }; - } -} -@protocol NativeSampleTurboModuleSpec - -- (void)voidFunc; -- (NSNumber *)getBool:(BOOL)arg; -- (NSNumber *)getNumber:(double)arg; -- (NSString *)getString:(NSString *)arg; -- (NSArray> *)getArray:(NSArray *)arg; -- (NSDictionary *)getObject:(NSDictionary *)arg; -- (NSDictionary *)getObjectShape:(JS::NativeSampleTurboModule::SpecGetObjectShapeArg &)arg; -- (NSDictionary *)getAlias:(JS::NativeSampleTurboModule::Animal &)arg; -- (NSNumber *)getRootTag:(double)arg; -- (NSDictionary *)getValue:(double)x -getValuegetValuegetValuegetValuegetValuey:(NSString *)getValuegetValuegetValuegetValuegetValuey - z:(NSDictionary *)z; -- (void)getValueWithCallback:(RCTResponseSenderBlock)callback; -- (void)getValueWithPromise:(BOOL)error - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject; -- (facebook::react::ModuleConstants)constantsToExport; -- (facebook::react::ModuleConstants)getConstants; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeSampleTurboModule' - */ - class JSI_EXPORT NativeSampleTurboModuleSpecJSI : public ObjCTurboModule { - public: - NativeSampleTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook -namespace JS { - namespace NativeSampleTurboModuleArrays { - struct ConstantsIdElement { - - struct Builder { - struct Input { - RCTRequired prop; - }; - - /** Initialize with a set of values */ - Builder(const Input i); - /** Initialize with an existing ConstantsIdElement */ - Builder(ConstantsIdElement i); - /** Builds the object. Generally used only by the infrastructure. */ - NSDictionary *buildUnsafeRawValue() const { return _factory(); }; - private: - NSDictionary *(^_factory)(void); - }; - - static ConstantsIdElement fromUnsafeRawValue(NSDictionary *const v) { return {v}; } - NSDictionary *unsafeRawValue() const { return _v; } - private: - ConstantsIdElement(NSDictionary *const v) : _v(v) {} - NSDictionary *_v; - }; - } -} -namespace JS { - namespace NativeSampleTurboModuleArrays { - struct Constants { - - struct Builder { - struct Input { - RCTRequired> const1; - RCTRequired> const2; - RCTRequired> const3; - std::optional>> id_; - }; - - /** Initialize with a set of values */ - Builder(const Input i); - /** Initialize with an existing Constants */ - Builder(Constants i); - /** Builds the object. Generally used only by the infrastructure. */ - NSDictionary *buildUnsafeRawValue() const { return _factory(); }; - private: - NSDictionary *(^_factory)(void); - }; - - static Constants fromUnsafeRawValue(NSDictionary *const v) { return {v}; } - NSDictionary *unsafeRawValue() const { return _v; } - private: - Constants(NSDictionary *const v) : _v(v) {} - NSDictionary *_v; - }; - } -} -@protocol NativeSampleTurboModuleArraysSpec - -- (void)voidFunc; -- (NSArray *)getBool:(NSArray *)id; -- (NSArray *)getNumber:(NSArray *)arg; -- (NSArray *)getString:(NSArray *)arg; -- (NSArray> *> *)getArray:(NSArray *)arg; -- (NSArray *)getObject:(NSArray *)arg; -- (NSArray *)getObjectShape:(NSArray *)arg; -- (NSArray *)getAlias:(NSArray *)arg; -- (NSArray *)getRootTag:(NSArray *)arg; -- (NSArray *)getValue:(NSArray *)x - y:(NSArray *)y - z:(NSArray *)z; -- (void)getValueWithCallback:(RCTResponseSenderBlock)callback; -- (void)getValueWithPromise:(NSArray *)error - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject; -- (facebook::react::ModuleConstants)constantsToExport; -- (facebook::react::ModuleConstants)getConstants; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeSampleTurboModuleArrays' - */ - class JSI_EXPORT NativeSampleTurboModuleArraysSpecJSI : public ObjCTurboModule { - public: - NativeSampleTurboModuleArraysSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook -namespace JS { - namespace NativeSampleTurboModuleNullable { - struct SpecGetObjectShapeArg { - std::optional prop() const; - - SpecGetObjectShapeArg(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (NativeSampleTurboModuleNullable_SpecGetObjectShapeArg) -+ (RCTManagedPointer *)JS_NativeSampleTurboModuleNullable_SpecGetObjectShapeArg:(id)json; -@end -namespace JS { - namespace NativeSampleTurboModuleNullable { - struct Animal { - NSString *name() const; - - Animal(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (NativeSampleTurboModuleNullable_Animal) -+ (RCTManagedPointer *)JS_NativeSampleTurboModuleNullable_Animal:(id)json; -@end -namespace JS { - namespace NativeSampleTurboModuleNullable { - struct Constants { - - struct Builder { - struct Input { - RCTRequired> const1; - RCTRequired> const2; - RCTRequired const3; - }; - - /** Initialize with a set of values */ - Builder(const Input i); - /** Initialize with an existing Constants */ - Builder(Constants i); - /** Builds the object. Generally used only by the infrastructure. */ - NSDictionary *buildUnsafeRawValue() const { return _factory(); }; - private: - NSDictionary *(^_factory)(void); - }; - - static Constants fromUnsafeRawValue(NSDictionary *const v) { return {v}; } - NSDictionary *unsafeRawValue() const { return _v; } - private: - Constants(NSDictionary *const v) : _v(v) {} - NSDictionary *_v; - }; - } -} -@protocol NativeSampleTurboModuleNullableSpec - -- (void)voidFunc; -- (NSNumber * _Nullable)getBool:(NSNumber *)arg; -- (NSNumber * _Nullable)getNumber:(NSNumber *)arg; -- (NSString * _Nullable)getString:(NSString * _Nullable)arg; -- (NSArray> * _Nullable)getArray:(NSArray * _Nullable)arg; -- (NSDictionary * _Nullable)getObject:(NSDictionary * _Nullable)arg; -- (NSDictionary * _Nullable)getObjectShape:(JS::NativeSampleTurboModuleNullable::SpecGetObjectShapeArg &)arg; -- (NSDictionary * _Nullable)getAlias:(JS::NativeSampleTurboModuleNullable::Animal &)arg; -- (NSNumber * _Nullable)getRootTag:(NSNumber *)arg; -- (NSDictionary * _Nullable)getValue:(NSNumber *)x - y:(NSString * _Nullable)y - z:(NSDictionary * _Nullable)z; -- (void)getValueWithCallback:(RCTResponseSenderBlock)callback; -- (void)getValueWithPromise:(NSNumber *)error - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject; -- (facebook::react::ModuleConstants)constantsToExport; -- (facebook::react::ModuleConstants)getConstants; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeSampleTurboModuleNullable' - */ - class JSI_EXPORT NativeSampleTurboModuleNullableSpecJSI : public ObjCTurboModule { - public: - NativeSampleTurboModuleNullableSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook -namespace JS { - namespace NativeSampleTurboModuleNullableAndOptional { - struct SpecGetObjectShapeArg { - std::optional prop() const; - - SpecGetObjectShapeArg(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (NativeSampleTurboModuleNullableAndOptional_SpecGetObjectShapeArg) -+ (RCTManagedPointer *)JS_NativeSampleTurboModuleNullableAndOptional_SpecGetObjectShapeArg:(id)json; -@end -namespace JS { - namespace NativeSampleTurboModuleNullableAndOptional { - struct Animal { - NSString *name() const; - - Animal(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (NativeSampleTurboModuleNullableAndOptional_Animal) -+ (RCTManagedPointer *)JS_NativeSampleTurboModuleNullableAndOptional_Animal:(id)json; -@end -namespace JS { - namespace NativeSampleTurboModuleNullableAndOptional { - struct Constants { - - struct Builder { - struct Input { - std::optional const1; - std::optional const2; - NSString *const3; - }; - - /** Initialize with a set of values */ - Builder(const Input i); - /** Initialize with an existing Constants */ - Builder(Constants i); - /** Builds the object. Generally used only by the infrastructure. */ - NSDictionary *buildUnsafeRawValue() const { return _factory(); }; - private: - NSDictionary *(^_factory)(void); - }; - - static Constants fromUnsafeRawValue(NSDictionary *const v) { return {v}; } - NSDictionary *unsafeRawValue() const { return _v; } - private: - Constants(NSDictionary *const v) : _v(v) {} - NSDictionary *_v; - }; - } -} -@protocol NativeSampleTurboModuleNullableAndOptionalSpec - -- (void)voidFunc; -- (NSNumber * _Nullable)getBool:(NSNumber *)arg; -- (NSNumber * _Nullable)getNumber:(NSNumber *)arg; -- (NSString * _Nullable)getString:(NSString * _Nullable)arg; -- (NSArray> * _Nullable)getArray:(NSArray * _Nullable)arg; -- (NSDictionary * _Nullable)getObject:(NSDictionary * _Nullable)arg; -- (NSDictionary *)getObjectShape:(JS::NativeSampleTurboModuleNullableAndOptional::SpecGetObjectShapeArg &)arg; -- (NSDictionary * _Nullable)getAlias:(JS::NativeSampleTurboModuleNullableAndOptional::Animal &)arg; -- (NSNumber * _Nullable)getRootTag:(NSNumber *)arg; -- (NSDictionary * _Nullable)getValue:(NSNumber *)x - y:(NSString * _Nullable)y - z:(NSDictionary * _Nullable)z; -- (void)getValueWithCallback:(RCTResponseSenderBlock)callback; -- (void)getValueWithPromise:(NSNumber *)error - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject; -- (facebook::react::ModuleConstants)constantsToExport; -- (facebook::react::ModuleConstants)getConstants; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeSampleTurboModuleNullableAndOptional' - */ - class JSI_EXPORT NativeSampleTurboModuleNullableAndOptionalSpecJSI : public ObjCTurboModule { - public: - NativeSampleTurboModuleNullableAndOptionalSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook -namespace JS { - namespace NativeSampleTurboModuleOptional { - struct SpecGetObjectShapeArg { - std::optional prop() const; - - SpecGetObjectShapeArg(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (NativeSampleTurboModuleOptional_SpecGetObjectShapeArg) -+ (RCTManagedPointer *)JS_NativeSampleTurboModuleOptional_SpecGetObjectShapeArg:(id)json; -@end -namespace JS { - namespace NativeSampleTurboModuleOptional { - struct Animal { - NSString *name() const; - - Animal(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (NativeSampleTurboModuleOptional_Animal) -+ (RCTManagedPointer *)JS_NativeSampleTurboModuleOptional_Animal:(id)json; -@end -namespace JS { - namespace NativeSampleTurboModuleOptional { - struct Constants { - - struct Builder { - struct Input { - std::optional const1; - std::optional const2; - NSString *const3; - }; - - /** Initialize with a set of values */ - Builder(const Input i); - /** Initialize with an existing Constants */ - Builder(Constants i); - /** Builds the object. Generally used only by the infrastructure. */ - NSDictionary *buildUnsafeRawValue() const { return _factory(); }; - private: - NSDictionary *(^_factory)(void); - }; - - static Constants fromUnsafeRawValue(NSDictionary *const v) { return {v}; } - NSDictionary *unsafeRawValue() const { return _v; } - private: - Constants(NSDictionary *const v) : _v(v) {} - NSDictionary *_v; - }; - } -} -@protocol NativeSampleTurboModuleOptionalSpec - -- (void)voidFunc; -- (NSNumber *)getBool:(NSNumber *)arg; -- (NSNumber *)getNumber:(NSNumber *)arg; -- (NSString *)getString:(NSString *)arg; -- (NSArray> *)getArray:(NSArray *)arg; -- (NSDictionary *)getObject:(NSDictionary *)arg; -- (NSDictionary *)getObjectShape:(JS::NativeSampleTurboModuleOptional::SpecGetObjectShapeArg &)arg; -- (NSDictionary *)getAlias:(JS::NativeSampleTurboModuleOptional::Animal &)arg; -- (NSNumber *)getRootTag:(NSNumber *)arg; -- (NSDictionary *)getValue:(NSNumber *)x - y:(NSString *)y - z:(NSDictionary *)z; -- (void)getValueWithCallback:(RCTResponseSenderBlock)callback; -- (void)getValueWithPromise:(NSNumber *)error - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject; -- (facebook::react::ModuleConstants)constantsToExport; -- (facebook::react::ModuleConstants)getConstants; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeSampleTurboModuleOptional' - */ - class JSI_EXPORT NativeSampleTurboModuleOptionalSpecJSI : public ObjCTurboModule { - public: - NativeSampleTurboModuleOptionalSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook - -@protocol NativeStringTurboModuleSpec - -- (NSString *)getString:(NSString *)arg; -- (NSString *)getStringWithAlias:(NSString *)arg; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeStringTurboModule' - */ - class JSI_EXPORT NativeStringTurboModuleSpecJSI : public ObjCTurboModule { - public: - NativeStringTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook - - - - - -inline bool JS::NativeObjectTurboModule::SpecDifficultObjectAE::D() const -{ - id const p = _v[@\\"D\\"]; - return RCTBridgingToBool(p); -} -inline double JS::NativeObjectTurboModule::SpecDifficultObjectAE::E() const -{ - id const p = _v[@\\"E\\"]; - return RCTBridgingToDouble(p); -} -inline NSString *JS::NativeObjectTurboModule::SpecDifficultObjectAE::F() const -{ - id const p = _v[@\\"F\\"]; - return RCTBridgingToString(p); -} -inline bool JS::NativeObjectTurboModule::SpecDifficultObjectA::D() const -{ - id const p = _v[@\\"D\\"]; - return RCTBridgingToBool(p); -} -inline JS::NativeObjectTurboModule::SpecDifficultObjectAE JS::NativeObjectTurboModule::SpecDifficultObjectA::E() const -{ - id const p = _v[@\\"E\\"]; - return JS::NativeObjectTurboModule::SpecDifficultObjectAE(p); -} -inline NSString *JS::NativeObjectTurboModule::SpecDifficultObjectA::F() const -{ - id const p = _v[@\\"F\\"]; - return RCTBridgingToString(p); -} -inline JS::NativeObjectTurboModule::ConstantsEEE::Builder::Builder(const Input i) : _factory(^{ - NSMutableDictionary *d = [NSMutableDictionary new]; - auto D = i.D.get(); - d[@\\"D\\"] = @(D); - auto E = i.E.get(); - d[@\\"E\\"] = @(E); - auto F = i.F.get(); - d[@\\"F\\"] = F; - return d; -}) {} -inline JS::NativeObjectTurboModule::ConstantsEEE::Builder::Builder(ConstantsEEE i) : _factory(^{ - return i.unsafeRawValue(); -}) {} -inline JS::NativeObjectTurboModule::ConstantsEE::Builder::Builder(const Input i) : _factory(^{ - NSMutableDictionary *d = [NSMutableDictionary new]; - auto D = i.D.get(); - d[@\\"D\\"] = @(D); - auto E = i.E.get(); - d[@\\"E\\"] = E.buildUnsafeRawValue(); - auto F = i.F.get(); - d[@\\"F\\"] = F; - return d; -}) {} -inline JS::NativeObjectTurboModule::ConstantsEE::Builder::Builder(ConstantsEE i) : _factory(^{ - return i.unsafeRawValue(); -}) {} -inline JS::NativeObjectTurboModule::ConstantsE::Builder::Builder(const Input i) : _factory(^{ - NSMutableDictionary *d = [NSMutableDictionary new]; - auto D = i.D.get(); - d[@\\"D\\"] = @(D); - auto E = i.E.get(); - d[@\\"E\\"] = E.buildUnsafeRawValue(); - auto F = i.F.get(); - d[@\\"F\\"] = F; - return d; -}) {} -inline JS::NativeObjectTurboModule::ConstantsE::Builder::Builder(ConstantsE i) : _factory(^{ - return i.unsafeRawValue(); -}) {} -inline JS::NativeObjectTurboModule::Constants::Builder::Builder(const Input i) : _factory(^{ - NSMutableDictionary *d = [NSMutableDictionary new]; - auto D = i.D.get(); - d[@\\"D\\"] = @(D); - auto E = i.E.get(); - d[@\\"E\\"] = E.buildUnsafeRawValue(); - auto F = i.F.get(); - d[@\\"F\\"] = F; - return d; -}) {} -inline JS::NativeObjectTurboModule::Constants::Builder::Builder(Constants i) : _factory(^{ - return i.unsafeRawValue(); -}) {} -inline JS::NativeOptionalObjectTurboModule::ConstantsEEE::Builder::Builder(const Input i) : _factory(^{ - NSMutableDictionary *d = [NSMutableDictionary new]; - auto D = i.D; - d[@\\"D\\"] = D.has_value() ? @((BOOL)D.value()) : nil; - auto E = i.E; - d[@\\"E\\"] = E.has_value() ? @((double)E.value()) : nil; - auto F = i.F; - d[@\\"F\\"] = F; - return d; -}) {} -inline JS::NativeOptionalObjectTurboModule::ConstantsEEE::Builder::Builder(ConstantsEEE i) : _factory(^{ - return i.unsafeRawValue(); -}) {} -inline JS::NativeOptionalObjectTurboModule::ConstantsEE::Builder::Builder(const Input i) : _factory(^{ - NSMutableDictionary *d = [NSMutableDictionary new]; - auto D = i.D; - d[@\\"D\\"] = D.has_value() ? @((BOOL)D.value()) : nil; - auto E = i.E; - d[@\\"E\\"] = E.has_value() ? E.value().buildUnsafeRawValue() : nil; - auto F = i.F; - d[@\\"F\\"] = F; - return d; -}) {} -inline JS::NativeOptionalObjectTurboModule::ConstantsEE::Builder::Builder(ConstantsEE i) : _factory(^{ - return i.unsafeRawValue(); -}) {} -inline JS::NativeOptionalObjectTurboModule::ConstantsE::Builder::Builder(const Input i) : _factory(^{ - NSMutableDictionary *d = [NSMutableDictionary new]; - auto D = i.D; - d[@\\"D\\"] = D.has_value() ? @((BOOL)D.value()) : nil; - auto E = i.E; - d[@\\"E\\"] = E.has_value() ? E.value().buildUnsafeRawValue() : nil; - auto F = i.F; - d[@\\"F\\"] = F; - return d; -}) {} -inline JS::NativeOptionalObjectTurboModule::ConstantsE::Builder::Builder(ConstantsE i) : _factory(^{ - return i.unsafeRawValue(); -}) {} -inline JS::NativeOptionalObjectTurboModule::Constants::Builder::Builder(const Input i) : _factory(^{ - NSMutableDictionary *d = [NSMutableDictionary new]; - auto D = i.D; - d[@\\"D\\"] = D.has_value() ? @((BOOL)D.value()) : nil; - auto A = i.A; - d[@\\"A\\"] = A; - auto E = i.E; - d[@\\"E\\"] = E.has_value() ? E.value().buildUnsafeRawValue() : nil; - auto F = i.F; - d[@\\"F\\"] = F; - return d; -}) {} -inline JS::NativeOptionalObjectTurboModule::Constants::Builder::Builder(Constants i) : _factory(^{ - return i.unsafeRawValue(); -}) {} - -inline double JS::NativeSampleTurboModule::SpecGetObjectShapeArg::prop() const -{ - id const p = _v[@\\"prop\\"]; - return RCTBridgingToDouble(p); -} -inline NSString *JS::NativeSampleTurboModule::Animal::name() const -{ - id const p = _v[@\\"name\\"]; - return RCTBridgingToString(p); -} -inline JS::NativeSampleTurboModule::Constants::Builder::Builder(const Input i) : _factory(^{ - NSMutableDictionary *d = [NSMutableDictionary new]; - auto const1 = i.const1.get(); - d[@\\"const1\\"] = @(const1); - auto const2 = i.const2.get(); - d[@\\"const2\\"] = @(const2); - auto const3 = i.const3.get(); - d[@\\"const3\\"] = const3; - return d; -}) {} -inline JS::NativeSampleTurboModule::Constants::Builder::Builder(Constants i) : _factory(^{ - return i.unsafeRawValue(); -}) {} -inline JS::NativeSampleTurboModuleArrays::ConstantsIdElement::Builder::Builder(const Input i) : _factory(^{ - NSMutableDictionary *d = [NSMutableDictionary new]; - auto prop = i.prop.get(); - d[@\\"prop\\"] = @(prop); - return d; -}) {} -inline JS::NativeSampleTurboModuleArrays::ConstantsIdElement::Builder::Builder(ConstantsIdElement i) : _factory(^{ - return i.unsafeRawValue(); -}) {} -inline JS::NativeSampleTurboModuleArrays::Constants::Builder::Builder(const Input i) : _factory(^{ - NSMutableDictionary *d = [NSMutableDictionary new]; - auto const1 = i.const1.get(); - d[@\\"const1\\"] = RCTConvertVecToArray(const1, ^id(bool el_) { return @(el_); }); - auto const2 = i.const2.get(); - d[@\\"const2\\"] = RCTConvertVecToArray(const2, ^id(double el_) { return @(el_); }); - auto const3 = i.const3.get(); - d[@\\"const3\\"] = RCTConvertVecToArray(const3, ^id(NSString * el_) { return el_; }); - auto id_ = i.id_; - d[@\\"id\\"] = RCTConvertOptionalVecToArray(id_, ^id(std::optional el_) { return el_.has_value() ? el_.value().buildUnsafeRawValue() : nil; }); - return d; -}) {} -inline JS::NativeSampleTurboModuleArrays::Constants::Builder::Builder(Constants i) : _factory(^{ - return i.unsafeRawValue(); -}) {} -inline std::optional JS::NativeSampleTurboModuleNullable::SpecGetObjectShapeArg::prop() const -{ - id const p = _v[@\\"prop\\"]; - return RCTBridgingToOptionalDouble(p); -} -inline NSString *JS::NativeSampleTurboModuleNullable::Animal::name() const -{ - id const p = _v[@\\"name\\"]; - return RCTBridgingToOptionalString(p); -} -inline JS::NativeSampleTurboModuleNullable::Constants::Builder::Builder(const Input i) : _factory(^{ - NSMutableDictionary *d = [NSMutableDictionary new]; - auto const1 = i.const1.get(); - d[@\\"const1\\"] = const1.has_value() ? @((BOOL)const1.value()) : nil; - auto const2 = i.const2.get(); - d[@\\"const2\\"] = const2.has_value() ? @((double)const2.value()) : nil; - auto const3 = i.const3.get(); - d[@\\"const3\\"] = const3; - return d; -}) {} -inline JS::NativeSampleTurboModuleNullable::Constants::Builder::Builder(Constants i) : _factory(^{ - return i.unsafeRawValue(); -}) {} -inline std::optional JS::NativeSampleTurboModuleNullableAndOptional::SpecGetObjectShapeArg::prop() const -{ - id const p = _v[@\\"prop\\"]; - return RCTBridgingToOptionalDouble(p); -} -inline NSString *JS::NativeSampleTurboModuleNullableAndOptional::Animal::name() const -{ - id const p = _v[@\\"name\\"]; - return RCTBridgingToOptionalString(p); -} -inline JS::NativeSampleTurboModuleNullableAndOptional::Constants::Builder::Builder(const Input i) : _factory(^{ - NSMutableDictionary *d = [NSMutableDictionary new]; - auto const1 = i.const1; - d[@\\"const1\\"] = const1.has_value() ? @((BOOL)const1.value()) : nil; - auto const2 = i.const2; - d[@\\"const2\\"] = const2.has_value() ? @((double)const2.value()) : nil; - auto const3 = i.const3; - d[@\\"const3\\"] = const3; - return d; -}) {} -inline JS::NativeSampleTurboModuleNullableAndOptional::Constants::Builder::Builder(Constants i) : _factory(^{ - return i.unsafeRawValue(); -}) {} -inline std::optional JS::NativeSampleTurboModuleOptional::SpecGetObjectShapeArg::prop() const -{ - id const p = _v[@\\"prop\\"]; - return RCTBridgingToOptionalDouble(p); -} -inline NSString *JS::NativeSampleTurboModuleOptional::Animal::name() const -{ - id const p = _v[@\\"name\\"]; - return RCTBridgingToOptionalString(p); -} -inline JS::NativeSampleTurboModuleOptional::Constants::Builder::Builder(const Input i) : _factory(^{ - NSMutableDictionary *d = [NSMutableDictionary new]; - auto const1 = i.const1; - d[@\\"const1\\"] = const1.has_value() ? @((BOOL)const1.value()) : nil; - auto const2 = i.const2; - d[@\\"const2\\"] = const2.has_value() ? @((double)const2.value()) : nil; - auto const3 = i.const3; - d[@\\"const3\\"] = const3; - return d; -}) {} -inline JS::NativeSampleTurboModuleOptional::Constants::Builder::Builder(Constants i) : _factory(^{ - return i.unsafeRawValue(); -}) {} - -NS_ASSUME_NONNULL_END -" -`; - -exports[`GenerateModuleObjCpp can generate an implementation file NativeModule specs 1`] = ` -"/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleObjCpp - * - * We create an umbrella header (and corresponding implementation) here since - * Cxx compilation in BUCK has a limitation: source-code producing genrule()s - * must have a single output. More files => more genrule()s => slower builds. - */ - -#import \\"RNCodegenModuleFixtures.h\\" - - -namespace facebook { - namespace react { - - static facebook::jsi::Value __hostFunction_NativeArrayTurboModuleSpecJSI_getArray(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ArrayKind, \\"getArray\\", @selector(getArray:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeArrayTurboModuleSpecJSI_getReadOnlyArray(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ArrayKind, \\"getReadOnlyArray\\", @selector(getReadOnlyArray:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeArrayTurboModuleSpecJSI_getArrayWithAlias(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ArrayKind, \\"getArrayWithAlias\\", @selector(getArrayWithAlias:b:), args, count); - } - - NativeArrayTurboModuleSpecJSI::NativeArrayTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms) - : ObjCTurboModule(params) { - - methodMap_[\\"getArray\\"] = MethodMetadata {1, __hostFunction_NativeArrayTurboModuleSpecJSI_getArray}; - - - methodMap_[\\"getReadOnlyArray\\"] = MethodMetadata {1, __hostFunction_NativeArrayTurboModuleSpecJSI_getReadOnlyArray}; - - - methodMap_[\\"getArrayWithAlias\\"] = MethodMetadata {2, __hostFunction_NativeArrayTurboModuleSpecJSI_getArrayWithAlias}; - - } - } // namespace react -} // namespace facebook - -namespace facebook { - namespace react { - - static facebook::jsi::Value __hostFunction_NativeBooleanTurboModuleSpecJSI_getBoolean(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, BooleanKind, \\"getBoolean\\", @selector(getBoolean:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeBooleanTurboModuleSpecJSI_getBooleanWithAlias(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, BooleanKind, \\"getBooleanWithAlias\\", @selector(getBooleanWithAlias:), args, count); - } - - NativeBooleanTurboModuleSpecJSI::NativeBooleanTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms) - : ObjCTurboModule(params) { - - methodMap_[\\"getBoolean\\"] = MethodMetadata {1, __hostFunction_NativeBooleanTurboModuleSpecJSI_getBoolean}; - - - methodMap_[\\"getBooleanWithAlias\\"] = MethodMetadata {1, __hostFunction_NativeBooleanTurboModuleSpecJSI_getBooleanWithAlias}; - - } - } // namespace react -} // namespace facebook - -namespace facebook { - namespace react { - - static facebook::jsi::Value __hostFunction_NativeCallbackTurboModuleSpecJSI_getValueWithCallback(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, VoidKind, \\"getValueWithCallback\\", @selector(getValueWithCallback:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeCallbackTurboModuleSpecJSI_getValueWithCallbackWithAlias(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, VoidKind, \\"getValueWithCallbackWithAlias\\", @selector(getValueWithCallbackWithAlias:), args, count); - } - - NativeCallbackTurboModuleSpecJSI::NativeCallbackTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms) - : ObjCTurboModule(params) { - - methodMap_[\\"getValueWithCallback\\"] = MethodMetadata {1, __hostFunction_NativeCallbackTurboModuleSpecJSI_getValueWithCallback}; - - - methodMap_[\\"getValueWithCallbackWithAlias\\"] = MethodMetadata {1, __hostFunction_NativeCallbackTurboModuleSpecJSI_getValueWithCallbackWithAlias}; - - } - } // namespace react -} // namespace facebook - -namespace facebook { - namespace react { - - static facebook::jsi::Value __hostFunction_NativeNullableTurboModuleSpecJSI_getBool(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, BooleanKind, \\"getBool\\", @selector(getBool:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeNullableTurboModuleSpecJSI_getNumber(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, NumberKind, \\"getNumber\\", @selector(getNumber:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeNullableTurboModuleSpecJSI_getString(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, StringKind, \\"getString\\", @selector(getString:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeNullableTurboModuleSpecJSI_getArray(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ArrayKind, \\"getArray\\", @selector(getArray:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeNullableTurboModuleSpecJSI_getObject(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getObject\\", @selector(getObject:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeNullableTurboModuleSpecJSI_getValueWithPromise(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, PromiseKind, \\"getValueWithPromise\\", @selector(getValueWithPromise:reject:), args, count); - } - - NativeNullableTurboModuleSpecJSI::NativeNullableTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms) - : ObjCTurboModule(params) { - - methodMap_[\\"getBool\\"] = MethodMetadata {1, __hostFunction_NativeNullableTurboModuleSpecJSI_getBool}; - - - methodMap_[\\"getNumber\\"] = MethodMetadata {1, __hostFunction_NativeNullableTurboModuleSpecJSI_getNumber}; - - - methodMap_[\\"getString\\"] = MethodMetadata {1, __hostFunction_NativeNullableTurboModuleSpecJSI_getString}; - - - methodMap_[\\"getArray\\"] = MethodMetadata {1, __hostFunction_NativeNullableTurboModuleSpecJSI_getArray}; - - - methodMap_[\\"getObject\\"] = MethodMetadata {1, __hostFunction_NativeNullableTurboModuleSpecJSI_getObject}; - - - methodMap_[\\"getValueWithPromise\\"] = MethodMetadata {0, __hostFunction_NativeNullableTurboModuleSpecJSI_getValueWithPromise}; - - } - } // namespace react -} // namespace facebook - -namespace facebook { - namespace react { - - static facebook::jsi::Value __hostFunction_NativeNumberTurboModuleSpecJSI_getNumber(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, NumberKind, \\"getNumber\\", @selector(getNumber:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeNumberTurboModuleSpecJSI_getNumberWithAlias(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, NumberKind, \\"getNumberWithAlias\\", @selector(getNumberWithAlias:), args, count); - } - - NativeNumberTurboModuleSpecJSI::NativeNumberTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms) - : ObjCTurboModule(params) { - - methodMap_[\\"getNumber\\"] = MethodMetadata {1, __hostFunction_NativeNumberTurboModuleSpecJSI_getNumber}; - - - methodMap_[\\"getNumberWithAlias\\"] = MethodMetadata {1, __hostFunction_NativeNumberTurboModuleSpecJSI_getNumberWithAlias}; - - } - } // namespace react -} // namespace facebook -@implementation RCTCxxConvert (NativeObjectTurboModule_SpecDifficultObjectAE) -+ (RCTManagedPointer *)JS_NativeObjectTurboModule_SpecDifficultObjectAE:(id)json -{ - return facebook::react::managedPointer(json); -} -@end -@implementation RCTCxxConvert (NativeObjectTurboModule_SpecDifficultObjectA) -+ (RCTManagedPointer *)JS_NativeObjectTurboModule_SpecDifficultObjectA:(id)json -{ - return facebook::react::managedPointer(json); -} -@end -namespace facebook { - namespace react { - - static facebook::jsi::Value __hostFunction_NativeObjectTurboModuleSpecJSI_getGenericObject(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getGenericObject\\", @selector(getGenericObject:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeObjectTurboModuleSpecJSI_getGenericObjectReadOnly(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getGenericObjectReadOnly\\", @selector(getGenericObjectReadOnly:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeObjectTurboModuleSpecJSI_getGenericObjectWithAlias(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getGenericObjectWithAlias\\", @selector(getGenericObjectWithAlias:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeObjectTurboModuleSpecJSI_difficultObject(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"difficultObject\\", @selector(difficultObject:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeObjectTurboModuleSpecJSI_getConstants(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getConstants\\", @selector(getConstants), args, count); - } - - NativeObjectTurboModuleSpecJSI::NativeObjectTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms) - : ObjCTurboModule(params) { - - methodMap_[\\"getGenericObject\\"] = MethodMetadata {1, __hostFunction_NativeObjectTurboModuleSpecJSI_getGenericObject}; - - - methodMap_[\\"getGenericObjectReadOnly\\"] = MethodMetadata {1, __hostFunction_NativeObjectTurboModuleSpecJSI_getGenericObjectReadOnly}; - - - methodMap_[\\"getGenericObjectWithAlias\\"] = MethodMetadata {1, __hostFunction_NativeObjectTurboModuleSpecJSI_getGenericObjectWithAlias}; - - - methodMap_[\\"difficultObject\\"] = MethodMetadata {1, __hostFunction_NativeObjectTurboModuleSpecJSI_difficultObject}; - setMethodArgConversionSelector(@\\"difficultObject\\", 0, @\\"JS_NativeObjectTurboModule_SpecDifficultObjectA:\\"); - - methodMap_[\\"getConstants\\"] = MethodMetadata {0, __hostFunction_NativeObjectTurboModuleSpecJSI_getConstants}; - - } - } // namespace react -} // namespace facebook - -namespace facebook { - namespace react { - - static facebook::jsi::Value __hostFunction_NativeOptionalObjectTurboModuleSpecJSI_getConstants(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getConstants\\", @selector(getConstants), args, count); - } - - NativeOptionalObjectTurboModuleSpecJSI::NativeOptionalObjectTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms) - : ObjCTurboModule(params) { - - methodMap_[\\"getConstants\\"] = MethodMetadata {0, __hostFunction_NativeOptionalObjectTurboModuleSpecJSI_getConstants}; - - } - } // namespace react -} // namespace facebook - -namespace facebook { - namespace react { - - static facebook::jsi::Value __hostFunction_NativePromiseTurboModuleSpecJSI_getValueWithPromise(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, PromiseKind, \\"getValueWithPromise\\", @selector(getValueWithPromise:resolve:reject:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativePromiseTurboModuleSpecJSI_getValueWithPromiseWithAlias(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, PromiseKind, \\"getValueWithPromiseWithAlias\\", @selector(getValueWithPromiseWithAlias:resolve:reject:), args, count); - } - - NativePromiseTurboModuleSpecJSI::NativePromiseTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms) - : ObjCTurboModule(params) { - - methodMap_[\\"getValueWithPromise\\"] = MethodMetadata {1, __hostFunction_NativePromiseTurboModuleSpecJSI_getValueWithPromise}; - - - methodMap_[\\"getValueWithPromiseWithAlias\\"] = MethodMetadata {1, __hostFunction_NativePromiseTurboModuleSpecJSI_getValueWithPromiseWithAlias}; - - } - } // namespace react -} // namespace facebook -@implementation RCTCxxConvert (NativeSampleTurboModule_SpecGetObjectShapeArg) -+ (RCTManagedPointer *)JS_NativeSampleTurboModule_SpecGetObjectShapeArg:(id)json -{ - return facebook::react::managedPointer(json); -} -@end -@implementation RCTCxxConvert (NativeSampleTurboModule_Animal) -+ (RCTManagedPointer *)JS_NativeSampleTurboModule_Animal:(id)json -{ - return facebook::react::managedPointer(json); -} -@end -namespace facebook { - namespace react { - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_voidFunc(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, VoidKind, \\"voidFunc\\", @selector(voidFunc), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getBool(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, BooleanKind, \\"getBool\\", @selector(getBool:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getNumber(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, NumberKind, \\"getNumber\\", @selector(getNumber:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getString(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, StringKind, \\"getString\\", @selector(getString:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getArray(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ArrayKind, \\"getArray\\", @selector(getArray:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getObject(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getObject\\", @selector(getObject:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getObjectShape(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getObjectShape\\", @selector(getObjectShape:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getAlias(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getAlias\\", @selector(getAlias:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getRootTag(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, NumberKind, \\"getRootTag\\", @selector(getRootTag:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getValue(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getValue\\", @selector(getValue:getValuegetValuegetValuegetValuegetValuey:z:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getValueWithCallback(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, VoidKind, \\"getValueWithCallback\\", @selector(getValueWithCallback:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getValueWithPromise(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, PromiseKind, \\"getValueWithPromise\\", @selector(getValueWithPromise:resolve:reject:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getConstants(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getConstants\\", @selector(getConstants), args, count); - } - - NativeSampleTurboModuleSpecJSI::NativeSampleTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms) - : ObjCTurboModule(params) { - - methodMap_[\\"voidFunc\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleSpecJSI_voidFunc}; - - - methodMap_[\\"getBool\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getBool}; - - - methodMap_[\\"getNumber\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getNumber}; - - - methodMap_[\\"getString\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getString}; - - - methodMap_[\\"getArray\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getArray}; - - - methodMap_[\\"getObject\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getObject}; - - - methodMap_[\\"getObjectShape\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getObjectShape}; - setMethodArgConversionSelector(@\\"getObjectShape\\", 0, @\\"JS_NativeSampleTurboModule_SpecGetObjectShapeArg:\\"); - - methodMap_[\\"getAlias\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getAlias}; - setMethodArgConversionSelector(@\\"getAlias\\", 0, @\\"JS_NativeSampleTurboModule_Animal:\\"); - - methodMap_[\\"getRootTag\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getRootTag}; - - - methodMap_[\\"getValue\\"] = MethodMetadata {3, __hostFunction_NativeSampleTurboModuleSpecJSI_getValue}; - - - methodMap_[\\"getValueWithCallback\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getValueWithCallback}; - - - methodMap_[\\"getValueWithPromise\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getValueWithPromise}; - - - methodMap_[\\"getConstants\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleSpecJSI_getConstants}; - - } - } // namespace react -} // namespace facebook - -namespace facebook { - namespace react { - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleArraysSpecJSI_voidFunc(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, VoidKind, \\"voidFunc\\", @selector(voidFunc), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleArraysSpecJSI_getBool(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ArrayKind, \\"getBool\\", @selector(getBool:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleArraysSpecJSI_getNumber(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ArrayKind, \\"getNumber\\", @selector(getNumber:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleArraysSpecJSI_getString(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ArrayKind, \\"getString\\", @selector(getString:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleArraysSpecJSI_getArray(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ArrayKind, \\"getArray\\", @selector(getArray:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleArraysSpecJSI_getObject(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ArrayKind, \\"getObject\\", @selector(getObject:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleArraysSpecJSI_getObjectShape(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ArrayKind, \\"getObjectShape\\", @selector(getObjectShape:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleArraysSpecJSI_getAlias(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ArrayKind, \\"getAlias\\", @selector(getAlias:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleArraysSpecJSI_getRootTag(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ArrayKind, \\"getRootTag\\", @selector(getRootTag:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleArraysSpecJSI_getValue(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ArrayKind, \\"getValue\\", @selector(getValue:y:z:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleArraysSpecJSI_getValueWithCallback(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, VoidKind, \\"getValueWithCallback\\", @selector(getValueWithCallback:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleArraysSpecJSI_getValueWithPromise(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, PromiseKind, \\"getValueWithPromise\\", @selector(getValueWithPromise:resolve:reject:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleArraysSpecJSI_getConstants(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getConstants\\", @selector(getConstants), args, count); - } - - NativeSampleTurboModuleArraysSpecJSI::NativeSampleTurboModuleArraysSpecJSI(const ObjCTurboModule::InitParams ¶ms) - : ObjCTurboModule(params) { - - methodMap_[\\"voidFunc\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleArraysSpecJSI_voidFunc}; - - - methodMap_[\\"getBool\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleArraysSpecJSI_getBool}; - - - methodMap_[\\"getNumber\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleArraysSpecJSI_getNumber}; - - - methodMap_[\\"getString\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleArraysSpecJSI_getString}; - - - methodMap_[\\"getArray\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleArraysSpecJSI_getArray}; - - - methodMap_[\\"getObject\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleArraysSpecJSI_getObject}; - - - methodMap_[\\"getObjectShape\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleArraysSpecJSI_getObjectShape}; - - - methodMap_[\\"getAlias\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleArraysSpecJSI_getAlias}; - - - methodMap_[\\"getRootTag\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleArraysSpecJSI_getRootTag}; - - - methodMap_[\\"getValue\\"] = MethodMetadata {3, __hostFunction_NativeSampleTurboModuleArraysSpecJSI_getValue}; - - - methodMap_[\\"getValueWithCallback\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleArraysSpecJSI_getValueWithCallback}; - - - methodMap_[\\"getValueWithPromise\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleArraysSpecJSI_getValueWithPromise}; - - - methodMap_[\\"getConstants\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleArraysSpecJSI_getConstants}; - - } - } // namespace react -} // namespace facebook -@implementation RCTCxxConvert (NativeSampleTurboModuleNullable_SpecGetObjectShapeArg) -+ (RCTManagedPointer *)JS_NativeSampleTurboModuleNullable_SpecGetObjectShapeArg:(id)json -{ - return facebook::react::managedPointer(json); -} -@end -@implementation RCTCxxConvert (NativeSampleTurboModuleNullable_Animal) -+ (RCTManagedPointer *)JS_NativeSampleTurboModuleNullable_Animal:(id)json -{ - return facebook::react::managedPointer(json); -} -@end -namespace facebook { - namespace react { - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleNullableSpecJSI_voidFunc(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, VoidKind, \\"voidFunc\\", @selector(voidFunc), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleNullableSpecJSI_getBool(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, BooleanKind, \\"getBool\\", @selector(getBool:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleNullableSpecJSI_getNumber(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, NumberKind, \\"getNumber\\", @selector(getNumber:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleNullableSpecJSI_getString(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, StringKind, \\"getString\\", @selector(getString:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleNullableSpecJSI_getArray(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ArrayKind, \\"getArray\\", @selector(getArray:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleNullableSpecJSI_getObject(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getObject\\", @selector(getObject:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleNullableSpecJSI_getObjectShape(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getObjectShape\\", @selector(getObjectShape:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleNullableSpecJSI_getAlias(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getAlias\\", @selector(getAlias:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleNullableSpecJSI_getRootTag(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, NumberKind, \\"getRootTag\\", @selector(getRootTag:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleNullableSpecJSI_getValue(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getValue\\", @selector(getValue:y:z:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleNullableSpecJSI_getValueWithCallback(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, VoidKind, \\"getValueWithCallback\\", @selector(getValueWithCallback:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleNullableSpecJSI_getValueWithPromise(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, PromiseKind, \\"getValueWithPromise\\", @selector(getValueWithPromise:resolve:reject:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleNullableSpecJSI_getConstants(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getConstants\\", @selector(getConstants), args, count); - } - - NativeSampleTurboModuleNullableSpecJSI::NativeSampleTurboModuleNullableSpecJSI(const ObjCTurboModule::InitParams ¶ms) - : ObjCTurboModule(params) { - - methodMap_[\\"voidFunc\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleNullableSpecJSI_voidFunc}; - - - methodMap_[\\"getBool\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleNullableSpecJSI_getBool}; - - - methodMap_[\\"getNumber\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleNullableSpecJSI_getNumber}; - - - methodMap_[\\"getString\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleNullableSpecJSI_getString}; - - - methodMap_[\\"getArray\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleNullableSpecJSI_getArray}; - - - methodMap_[\\"getObject\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleNullableSpecJSI_getObject}; - - - methodMap_[\\"getObjectShape\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleNullableSpecJSI_getObjectShape}; - setMethodArgConversionSelector(@\\"getObjectShape\\", 0, @\\"JS_NativeSampleTurboModuleNullable_SpecGetObjectShapeArg:\\"); - - methodMap_[\\"getAlias\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleNullableSpecJSI_getAlias}; - setMethodArgConversionSelector(@\\"getAlias\\", 0, @\\"JS_NativeSampleTurboModuleNullable_Animal:\\"); - - methodMap_[\\"getRootTag\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleNullableSpecJSI_getRootTag}; - - - methodMap_[\\"getValue\\"] = MethodMetadata {3, __hostFunction_NativeSampleTurboModuleNullableSpecJSI_getValue}; - - - methodMap_[\\"getValueWithCallback\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleNullableSpecJSI_getValueWithCallback}; - - - methodMap_[\\"getValueWithPromise\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleNullableSpecJSI_getValueWithPromise}; - - - methodMap_[\\"getConstants\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleNullableSpecJSI_getConstants}; - - } - } // namespace react -} // namespace facebook -@implementation RCTCxxConvert (NativeSampleTurboModuleNullableAndOptional_SpecGetObjectShapeArg) -+ (RCTManagedPointer *)JS_NativeSampleTurboModuleNullableAndOptional_SpecGetObjectShapeArg:(id)json -{ - return facebook::react::managedPointer(json); -} -@end -@implementation RCTCxxConvert (NativeSampleTurboModuleNullableAndOptional_Animal) -+ (RCTManagedPointer *)JS_NativeSampleTurboModuleNullableAndOptional_Animal:(id)json -{ - return facebook::react::managedPointer(json); -} -@end -namespace facebook { - namespace react { - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleNullableAndOptionalSpecJSI_voidFunc(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, VoidKind, \\"voidFunc\\", @selector(voidFunc), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleNullableAndOptionalSpecJSI_getBool(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, BooleanKind, \\"getBool\\", @selector(getBool:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleNullableAndOptionalSpecJSI_getNumber(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, NumberKind, \\"getNumber\\", @selector(getNumber:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleNullableAndOptionalSpecJSI_getString(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, StringKind, \\"getString\\", @selector(getString:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleNullableAndOptionalSpecJSI_getArray(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ArrayKind, \\"getArray\\", @selector(getArray:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleNullableAndOptionalSpecJSI_getObject(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getObject\\", @selector(getObject:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleNullableAndOptionalSpecJSI_getObjectShape(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getObjectShape\\", @selector(getObjectShape:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleNullableAndOptionalSpecJSI_getAlias(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getAlias\\", @selector(getAlias:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleNullableAndOptionalSpecJSI_getRootTag(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, NumberKind, \\"getRootTag\\", @selector(getRootTag:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleNullableAndOptionalSpecJSI_getValue(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getValue\\", @selector(getValue:y:z:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleNullableAndOptionalSpecJSI_getValueWithCallback(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, VoidKind, \\"getValueWithCallback\\", @selector(getValueWithCallback:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleNullableAndOptionalSpecJSI_getValueWithPromise(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, PromiseKind, \\"getValueWithPromise\\", @selector(getValueWithPromise:resolve:reject:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleNullableAndOptionalSpecJSI_getConstants(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getConstants\\", @selector(getConstants), args, count); - } - - NativeSampleTurboModuleNullableAndOptionalSpecJSI::NativeSampleTurboModuleNullableAndOptionalSpecJSI(const ObjCTurboModule::InitParams ¶ms) - : ObjCTurboModule(params) { - - methodMap_[\\"voidFunc\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleNullableAndOptionalSpecJSI_voidFunc}; - - - methodMap_[\\"getBool\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleNullableAndOptionalSpecJSI_getBool}; - - - methodMap_[\\"getNumber\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleNullableAndOptionalSpecJSI_getNumber}; - - - methodMap_[\\"getString\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleNullableAndOptionalSpecJSI_getString}; - - - methodMap_[\\"getArray\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleNullableAndOptionalSpecJSI_getArray}; - - - methodMap_[\\"getObject\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleNullableAndOptionalSpecJSI_getObject}; - - - methodMap_[\\"getObjectShape\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleNullableAndOptionalSpecJSI_getObjectShape}; - setMethodArgConversionSelector(@\\"getObjectShape\\", 0, @\\"JS_NativeSampleTurboModuleNullableAndOptional_SpecGetObjectShapeArg:\\"); - - methodMap_[\\"getAlias\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleNullableAndOptionalSpecJSI_getAlias}; - setMethodArgConversionSelector(@\\"getAlias\\", 0, @\\"JS_NativeSampleTurboModuleNullableAndOptional_Animal:\\"); - - methodMap_[\\"getRootTag\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleNullableAndOptionalSpecJSI_getRootTag}; - - - methodMap_[\\"getValue\\"] = MethodMetadata {3, __hostFunction_NativeSampleTurboModuleNullableAndOptionalSpecJSI_getValue}; - - - methodMap_[\\"getValueWithCallback\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleNullableAndOptionalSpecJSI_getValueWithCallback}; - - - methodMap_[\\"getValueWithPromise\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleNullableAndOptionalSpecJSI_getValueWithPromise}; - - - methodMap_[\\"getConstants\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleNullableAndOptionalSpecJSI_getConstants}; - - } - } // namespace react -} // namespace facebook -@implementation RCTCxxConvert (NativeSampleTurboModuleOptional_SpecGetObjectShapeArg) -+ (RCTManagedPointer *)JS_NativeSampleTurboModuleOptional_SpecGetObjectShapeArg:(id)json -{ - return facebook::react::managedPointer(json); -} -@end -@implementation RCTCxxConvert (NativeSampleTurboModuleOptional_Animal) -+ (RCTManagedPointer *)JS_NativeSampleTurboModuleOptional_Animal:(id)json -{ - return facebook::react::managedPointer(json); -} -@end -namespace facebook { - namespace react { - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleOptionalSpecJSI_voidFunc(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, VoidKind, \\"voidFunc\\", @selector(voidFunc), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleOptionalSpecJSI_getBool(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, BooleanKind, \\"getBool\\", @selector(getBool:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleOptionalSpecJSI_getNumber(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, NumberKind, \\"getNumber\\", @selector(getNumber:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleOptionalSpecJSI_getString(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, StringKind, \\"getString\\", @selector(getString:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleOptionalSpecJSI_getArray(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ArrayKind, \\"getArray\\", @selector(getArray:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleOptionalSpecJSI_getObject(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getObject\\", @selector(getObject:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleOptionalSpecJSI_getObjectShape(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getObjectShape\\", @selector(getObjectShape:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleOptionalSpecJSI_getAlias(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getAlias\\", @selector(getAlias:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleOptionalSpecJSI_getRootTag(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, NumberKind, \\"getRootTag\\", @selector(getRootTag:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleOptionalSpecJSI_getValue(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getValue\\", @selector(getValue:y:z:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleOptionalSpecJSI_getValueWithCallback(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, VoidKind, \\"getValueWithCallback\\", @selector(getValueWithCallback:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleOptionalSpecJSI_getValueWithPromise(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, PromiseKind, \\"getValueWithPromise\\", @selector(getValueWithPromise:resolve:reject:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleOptionalSpecJSI_getConstants(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getConstants\\", @selector(getConstants), args, count); - } - - NativeSampleTurboModuleOptionalSpecJSI::NativeSampleTurboModuleOptionalSpecJSI(const ObjCTurboModule::InitParams ¶ms) - : ObjCTurboModule(params) { - - methodMap_[\\"voidFunc\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleOptionalSpecJSI_voidFunc}; - - - methodMap_[\\"getBool\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleOptionalSpecJSI_getBool}; - - - methodMap_[\\"getNumber\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleOptionalSpecJSI_getNumber}; - - - methodMap_[\\"getString\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleOptionalSpecJSI_getString}; - - - methodMap_[\\"getArray\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleOptionalSpecJSI_getArray}; - - - methodMap_[\\"getObject\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleOptionalSpecJSI_getObject}; - - - methodMap_[\\"getObjectShape\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleOptionalSpecJSI_getObjectShape}; - setMethodArgConversionSelector(@\\"getObjectShape\\", 0, @\\"JS_NativeSampleTurboModuleOptional_SpecGetObjectShapeArg:\\"); - - methodMap_[\\"getAlias\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleOptionalSpecJSI_getAlias}; - setMethodArgConversionSelector(@\\"getAlias\\", 0, @\\"JS_NativeSampleTurboModuleOptional_Animal:\\"); - - methodMap_[\\"getRootTag\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleOptionalSpecJSI_getRootTag}; - - - methodMap_[\\"getValue\\"] = MethodMetadata {3, __hostFunction_NativeSampleTurboModuleOptionalSpecJSI_getValue}; - - - methodMap_[\\"getValueWithCallback\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleOptionalSpecJSI_getValueWithCallback}; - - - methodMap_[\\"getValueWithPromise\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleOptionalSpecJSI_getValueWithPromise}; - - - methodMap_[\\"getConstants\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleOptionalSpecJSI_getConstants}; - - } - } // namespace react -} // namespace facebook - -namespace facebook { - namespace react { - - static facebook::jsi::Value __hostFunction_NativeStringTurboModuleSpecJSI_getString(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, StringKind, \\"getString\\", @selector(getString:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeStringTurboModuleSpecJSI_getStringWithAlias(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, StringKind, \\"getStringWithAlias\\", @selector(getStringWithAlias:), args, count); - } - - NativeStringTurboModuleSpecJSI::NativeStringTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms) - : ObjCTurboModule(params) { - - methodMap_[\\"getString\\"] = MethodMetadata {1, __hostFunction_NativeStringTurboModuleSpecJSI_getString}; - - - methodMap_[\\"getStringWithAlias\\"] = MethodMetadata {1, __hostFunction_NativeStringTurboModuleSpecJSI_getStringWithAlias}; - - } - } // namespace react -} // namespace facebook -" -`; diff --git a/packages/react-native-codegen/package.json b/packages/react-native-codegen/package.json deleted file mode 100644 index c482a60fd9f3..000000000000 --- a/packages/react-native-codegen/package.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "name": "react-native-codegen", - "version": "0.71.5", - "description": "⚛️ Code generation tools for React Native", - "homepage": "https://github.com/facebook/react-native/tree/HEAD/packages/react-native-codegen", - "repository": { - "type": "git", - "url": "git@github.com:facebook/react-native.git", - "directory": "packages/react-native-codegen" - }, - "scripts": { - "build": "yarn clean && node scripts/build.js --verbose", - "clean": "rimraf lib", - "prepare": "yarn run build" - }, - "license": "MIT", - "files": [ - "lib" - ], - "dependencies": { - "@babel/parser": "^7.14.0", - "flow-parser": "^0.185.0", - "jscodeshift": "^0.13.1", - "nullthrows": "^1.1.1" - }, - "devDependencies": { - "@babel/core": "^7.14.0", - "@babel/plugin-proposal-class-properties": "^7.0.0", - "@babel/plugin-proposal-nullish-coalescing-operator": "^7.0.0", - "@babel/plugin-proposal-object-rest-spread": "^7.0.0", - "@babel/plugin-proposal-optional-chaining": "^7.0.0", - "@babel/plugin-syntax-dynamic-import": "^7.0.0", - "@babel/plugin-transform-async-to-generator": "^7.0.0", - "@babel/plugin-transform-destructuring": "^7.0.0", - "@babel/plugin-transform-flow-strip-types": "^7.0.0", - "@babel/preset-env": "^7.14.0", - "chalk": "^4.0.0", - "glob": "^7.1.1", - "invariant": "^2.2.4", - "micromatch": "^4.0.4", - "mkdirp": "^0.5.1", - "prettier": "^2.4.1", - "rimraf": "^3.0.2" - } -} diff --git a/packages/react-native-codegen/scripts/buck-oss/combine_js_to_schema.sh b/packages/react-native-codegen/scripts/buck-oss/combine_js_to_schema.sh deleted file mode 100755 index 6c837aa334d6..000000000000 --- a/packages/react-native-codegen/scripts/buck-oss/combine_js_to_schema.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/bash -# 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. - -# Note: To be invoked by Buck sh_binary() in OSS environment. -# DO NOT USE outside of Buck! - -set -e -set -u - -pushd "$BUCK_DEFAULT_RUNTIME_RESOURCES" >/dev/null -node "build/lib/cli/combine/combine-js-to-schema-cli.js" "$@" -popd >/dev/null diff --git a/packages/react-native-codegen/scripts/buck-oss/generate-all.sh b/packages/react-native-codegen/scripts/buck-oss/generate-all.sh deleted file mode 100755 index 9391bf80f254..000000000000 --- a/packages/react-native-codegen/scripts/buck-oss/generate-all.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/bash -# 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. - -# Note: To be invoked by Buck sh_binary() in OSS environment. -# DO NOT USE outside of Buck! - -set -e -set -u - -pushd "$BUCK_DEFAULT_RUNTIME_RESOURCES" >/dev/null -node "build/lib/cli/generators/generate-all.js" "$@" -popd >/dev/null diff --git a/packages/react-native-codegen/scripts/build.js b/packages/react-native-codegen/scripts/build.js deleted file mode 100644 index a8a34a61fbaf..000000000000 --- a/packages/react-native-codegen/scripts/build.js +++ /dev/null @@ -1,114 +0,0 @@ -/** - * 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 - */ - -/** - * script to build (transpile) files. - * - * Based off of the build script from Metro, and tweaked to run in just one - * package instead of in a monorepo. Just run `build.js` and the JS files in - * `src/` will be built in `lib/`, and the original source files will be copied - * over as `Example.js.flow`, so consumers of this module can still make use of - * type checking. - * - * Call this script with the `--verbose` flag to show the full output of this - * script. - */ - -'use strict'; - -const babel = require('@babel/core'); -const chalk = require('chalk'); -const fs = require('fs'); -const glob = require('glob'); -const micromatch = require('micromatch'); -const mkdirp = require('mkdirp'); -const path = require('path'); -const prettier = require('prettier'); -const prettierConfig = JSON.parse( - fs.readFileSync(path.resolve(__dirname, '..', '.prettierrc'), 'utf8'), -); - -const SRC_DIR = 'src'; -const BUILD_DIR = 'lib'; -const JS_FILES_PATTERN = '**/*.js'; -const IGNORE_PATTERN = '**/__tests__/**'; -const PACKAGE_DIR = path.resolve(__dirname, '../'); - -const fixedWidth = str => { - const WIDTH = 80; - const strs = str.match(new RegExp(`(.{1,${WIDTH}})`, 'g')) || [str]; - let lastString = strs[strs.length - 1]; - if (lastString.length < WIDTH) { - lastString += Array(WIDTH - lastString.length).join(chalk.dim('.')); - } - return strs.slice(0, -1).concat(lastString).join('\n'); -}; - -function getBuildPath(file, buildFolder) { - const pkgSrcPath = path.resolve(PACKAGE_DIR, SRC_DIR); - const pkgBuildPath = path.resolve(PACKAGE_DIR, BUILD_DIR); - const relativeToSrcPath = path.relative(pkgSrcPath, file); - return path.resolve(pkgBuildPath, relativeToSrcPath); -} - -function buildFile(file, silent) { - const destPath = getBuildPath(file, BUILD_DIR); - - mkdirp.sync(path.dirname(destPath)); - if (micromatch.isMatch(file, IGNORE_PATTERN)) { - silent || - process.stdout.write( - chalk.dim(' \u2022 ') + - path.relative(PACKAGE_DIR, file) + - ' (ignore)\n', - ); - } else if (!micromatch.isMatch(file, JS_FILES_PATTERN)) { - fs.createReadStream(file).pipe(fs.createWriteStream(destPath)); - silent || - process.stdout.write( - chalk.red(' \u2022 ') + - path.relative(PACKAGE_DIR, file) + - chalk.red(' \u21D2 ') + - path.relative(PACKAGE_DIR, destPath) + - ' (copy)' + - '\n', - ); - } else { - const transformed = prettier.format( - babel.transformFileSync(file, {}).code, - { - ...prettierConfig, - parser: 'babel', - }, - ); - fs.writeFileSync(destPath, transformed); - const source = fs.readFileSync(file).toString('utf-8'); - if (/@flow/.test(source)) { - fs.createReadStream(file).pipe(fs.createWriteStream(destPath + '.flow')); - } - silent || - process.stdout.write( - chalk.green(' \u2022 ') + - path.relative(PACKAGE_DIR, file) + - chalk.green(' \u21D2 ') + - path.relative(PACKAGE_DIR, destPath) + - '\n', - ); - } -} - -const srcDir = path.resolve(__dirname, '..', SRC_DIR); -const pattern = path.resolve(srcDir, '**/*'); -const files = glob.sync(pattern, {nodir: true}); - -process.stdout.write(fixedWidth(`${path.basename(PACKAGE_DIR)}\n`)); - -files.forEach(file => buildFile(file, !process.argv.includes('--verbose'))); - -process.stdout.write(`[ ${chalk.green('OK')} ]\n`); diff --git a/packages/react-native-codegen/scripts/oss/build.sh b/packages/react-native-codegen/scripts/oss/build.sh deleted file mode 100755 index 5822ffb7cf3b..000000000000 --- a/packages/react-native-codegen/scripts/oss/build.sh +++ /dev/null @@ -1,61 +0,0 @@ -#!/bin/bash -# 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. - -# This script assumes yarn is already installed. - -THIS_DIR=$(cd -P "$(dirname "$(realpath "${BASH_SOURCE[0]}" || echo "${BASH_SOURCE[0]}")")" && pwd) - -set -e -set -u - -CODEGEN_DIR="$THIS_DIR/../.." - -rm -rf "${CODEGEN_DIR:?}/lib" "${CODEGEN_DIR:?}/node_modules" - -# Fallback to npm if yarn is not available -if [ -x "$(command -v yarn)" ]; then - YARN_OR_NPM=$(command -v yarn) -else - YARN_OR_NPM=$(command -v npm) -fi -YARN_BINARY="${YARN_BINARY:-$YARN_OR_NPM}" - -if [[ ${FBSOURCE_ENV:-0} -eq 1 ]]; then - # Custom FB-specific setup - pushd "$CODEGEN_DIR" >/dev/null - - "$YARN_BINARY" install 2> >(grep -v '^warning' 1>&2) - # Note: Within FBSOURCE_ENV, this has to explicitly run build. - "$YARN_BINARY" run build - - popd >/dev/null - -else - # Run yarn install in a separate tmp dir to avoid conflict with the rest of the repo. - # Note: OSS-only. - TMP_DIR=$(mktemp -d) - - # On Windows this script gets run by a seprate Git Bash instance, which cannot perform the copy - # due to file locks created by the host process. Need to exclude .lock files while copying. - # Using in-memory tar operation because piping `find` and `grep` doesn't preserve folder structure - # during recursive copying, and `rsync` is not installed by default in Git Bash. - # As an added benefit, blob copy is faster. - if [ "$OSTYPE" = "msys" ] || [ "$OSTYPE" = "cygwin" ]; then - tar cf - --exclude='*.lock' "$CODEGEN_DIR" | (cd "$TMP_DIR" && tar xvf - ); - else - cp -R "$CODEGEN_DIR/." "$TMP_DIR"; - fi - - pushd "$TMP_DIR" >/dev/null - - # Note: this automatically runs build as well. - "$YARN_BINARY" install 2> >(grep -v '^warning' 1>&2) - - popd >/dev/null - - mv "$TMP_DIR/lib" "$TMP_DIR/node_modules" "$CODEGEN_DIR" - rm -rf "$TMP_DIR" -fi diff --git a/packages/react-native-codegen/src/CodegenSchema.js b/packages/react-native-codegen/src/CodegenSchema.js deleted file mode 100644 index 6884ca30710b..000000000000 --- a/packages/react-native-codegen/src/CodegenSchema.js +++ /dev/null @@ -1,350 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -export type PlatformType = 'iOS' | 'android'; - -export type SchemaType = $ReadOnly<{ - modules: $ReadOnly<{ - [hasteModuleName: string]: ComponentSchema | NativeModuleSchema, - }>, -}>; - -/** - * Component Type Annotations - */ -export type DoubleTypeAnnotation = $ReadOnly<{ - type: 'DoubleTypeAnnotation', -}>; - -export type FloatTypeAnnotation = $ReadOnly<{ - type: 'FloatTypeAnnotation', -}>; - -export type BooleanTypeAnnotation = $ReadOnly<{ - type: 'BooleanTypeAnnotation', -}>; - -export type Int32TypeAnnotation = $ReadOnly<{ - type: 'Int32TypeAnnotation', -}>; - -export type StringTypeAnnotation = $ReadOnly<{ - type: 'StringTypeAnnotation', -}>; - -export type StringEnumTypeAnnotation = $ReadOnly<{ - type: 'StringEnumTypeAnnotation', - options: $ReadOnlyArray, -}>; - -export type VoidTypeAnnotation = $ReadOnly<{ - type: 'VoidTypeAnnotation', -}>; - -export type ObjectTypeAnnotation<+T> = $ReadOnly<{ - type: 'ObjectTypeAnnotation', - properties: $ReadOnlyArray>, -}>; - -type FunctionTypeAnnotation<+P, +R> = $ReadOnly<{ - type: 'FunctionTypeAnnotation', - params: $ReadOnlyArray>, - returnTypeAnnotation: R, -}>; - -export type NamedShape<+T> = $ReadOnly<{ - name: string, - optional: boolean, - typeAnnotation: T, -}>; - -export type ComponentSchema = $ReadOnly<{ - type: 'Component', - components: $ReadOnly<{ - [componentName: string]: ComponentShape, - }>, -}>; - -export type ComponentShape = $ReadOnly<{ - ...OptionsShape, - extendsProps: $ReadOnlyArray, - events: $ReadOnlyArray, - props: $ReadOnlyArray>, - commands: $ReadOnlyArray>, -}>; - -export type OptionsShape = $ReadOnly<{ - interfaceOnly?: boolean, - - // Use for components with no current paper rename in progress - // Does not check for new name - paperComponentName?: string, - - // Use for components that are not used on other platforms. - excludedPlatforms?: $ReadOnlyArray, - - // Use for components currently being renamed in paper - // Will use new name if it is available and fallback to this name - paperComponentNameDeprecated?: string, -}>; - -export type ExtendsPropsShape = $ReadOnly<{ - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', -}>; - -export type EventTypeShape = $ReadOnly<{ - name: string, - bubblingType: 'direct' | 'bubble', - optional: boolean, - paperTopLevelNameDeprecated?: string, - typeAnnotation: $ReadOnly<{ - type: 'EventTypeAnnotation', - argument?: ObjectTypeAnnotation, - }>, -}>; - -export type EventTypeAnnotation = - | BooleanTypeAnnotation - | StringTypeAnnotation - | DoubleTypeAnnotation - | FloatTypeAnnotation - | Int32TypeAnnotation - | StringEnumTypeAnnotation - | ObjectTypeAnnotation; - -export type PropTypeAnnotation = - | $ReadOnly<{ - type: 'BooleanTypeAnnotation', - default: boolean | null, - }> - | $ReadOnly<{ - type: 'StringTypeAnnotation', - default: string | null, - }> - | $ReadOnly<{ - type: 'DoubleTypeAnnotation', - default: number, - }> - | $ReadOnly<{ - type: 'FloatTypeAnnotation', - default: number | null, - }> - | $ReadOnly<{ - type: 'Int32TypeAnnotation', - default: number, - }> - | $ReadOnly<{ - type: 'StringEnumTypeAnnotation', - default: string, - options: $ReadOnlyArray, - }> - | $ReadOnly<{ - type: 'Int32EnumTypeAnnotation', - default: number, - options: $ReadOnlyArray, - }> - | ReservedPropTypeAnnotation - | ObjectTypeAnnotation - | $ReadOnly<{ - type: 'ArrayTypeAnnotation', - elementType: - | BooleanTypeAnnotation - | StringTypeAnnotation - | DoubleTypeAnnotation - | FloatTypeAnnotation - | Int32TypeAnnotation - | $ReadOnly<{ - type: 'StringEnumTypeAnnotation', - default: string, - options: $ReadOnlyArray, - }> - | ObjectTypeAnnotation - | ReservedPropTypeAnnotation - | $ReadOnly<{ - type: 'ArrayTypeAnnotation', - elementType: ObjectTypeAnnotation, - }>, - }>; - -export type ReservedPropTypeAnnotation = $ReadOnly<{ - type: 'ReservedPropTypeAnnotation', - name: - | 'ColorPrimitive' - | 'ImageSourcePrimitive' - | 'PointPrimitive' - | 'EdgeInsetsPrimitive' - | 'ImageRequestPrimitive', -}>; - -export type CommandTypeAnnotation = FunctionTypeAnnotation< - CommandParamTypeAnnotation, - VoidTypeAnnotation, ->; - -export type CommandParamTypeAnnotation = - | ReservedTypeAnnotation - | BooleanTypeAnnotation - | Int32TypeAnnotation - | DoubleTypeAnnotation - | FloatTypeAnnotation - | StringTypeAnnotation; - -export type ReservedTypeAnnotation = $ReadOnly<{ - type: 'ReservedTypeAnnotation', - name: 'RootTag', // Union with more custom types. -}>; - -/** - * NativeModule Types - */ -export type Nullable<+T: NativeModuleTypeAnnotation> = - | NullableTypeAnnotation - | T; - -export type NullableTypeAnnotation<+T: NativeModuleTypeAnnotation> = $ReadOnly<{ - type: 'NullableTypeAnnotation', - typeAnnotation: T, -}>; - -export type NativeModuleSchema = $ReadOnly<{ - type: 'NativeModule', - aliases: NativeModuleAliasMap, - spec: NativeModuleSpec, - moduleNames: $ReadOnlyArray, - // 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. - excludedPlatforms?: $ReadOnlyArray, -}>; - -type NativeModuleSpec = $ReadOnly<{ - properties: $ReadOnlyArray, -}>; - -export type NativeModulePropertyShape = NamedShape< - Nullable, ->; - -export type NativeModuleAliasMap = $ReadOnly<{ - [aliasName: string]: NativeModuleObjectTypeAnnotation, -}>; - -export type NativeModuleFunctionTypeAnnotation = FunctionTypeAnnotation< - Nullable, - Nullable, ->; - -export type NativeModuleObjectTypeAnnotation = ObjectTypeAnnotation< - Nullable, ->; - -export type NativeModuleArrayTypeAnnotation< - +T: Nullable, -> = $ReadOnly<{ - type: 'ArrayTypeAnnotation', - /** - * TODO(T72031674): Migrate all our NativeModule specs to not use - * invalid Array ElementTypes. Then, make the elementType required. - */ - elementType?: T, -}>; - -export type NativeModuleStringTypeAnnotation = $ReadOnly<{ - type: 'StringTypeAnnotation', -}>; - -export type NativeModuleNumberTypeAnnotation = $ReadOnly<{ - type: 'NumberTypeAnnotation', -}>; - -export type NativeModuleInt32TypeAnnotation = $ReadOnly<{ - type: 'Int32TypeAnnotation', -}>; - -export type NativeModuleDoubleTypeAnnotation = $ReadOnly<{ - type: 'DoubleTypeAnnotation', -}>; - -export type NativeModuleFloatTypeAnnotation = $ReadOnly<{ - type: 'FloatTypeAnnotation', -}>; - -export type NativeModuleBooleanTypeAnnotation = $ReadOnly<{ - type: 'BooleanTypeAnnotation', -}>; - -export type NativeModuleEnumDeclaration = $ReadOnly<{ - type: 'EnumDeclaration', - memberType: 'NumberTypeAnnotation' | 'StringTypeAnnotation', -}>; - -export type NativeModuleGenericObjectTypeAnnotation = $ReadOnly<{ - type: 'GenericObjectTypeAnnotation', -}>; - -export type NativeModuleTypeAliasTypeAnnotation = $ReadOnly<{ - type: 'TypeAliasTypeAnnotation', - name: string, -}>; - -export type NativeModulePromiseTypeAnnotation = $ReadOnly<{ - type: 'PromiseTypeAnnotation', -}>; - -export type UnionTypeAnnotationMemberType = - | 'NumberTypeAnnotation' - | 'ObjectTypeAnnotation' - | 'StringTypeAnnotation'; - -export type NativeModuleUnionTypeAnnotation = $ReadOnly<{ - type: 'UnionTypeAnnotation', - memberType: UnionTypeAnnotationMemberType, -}>; - -export type NativeModuleMixedTypeAnnotation = $ReadOnly<{ - type: 'MixedTypeAnnotation', -}>; - -export type NativeModuleBaseTypeAnnotation = - | NativeModuleStringTypeAnnotation - | NativeModuleNumberTypeAnnotation - | NativeModuleInt32TypeAnnotation - | NativeModuleDoubleTypeAnnotation - | NativeModuleFloatTypeAnnotation - | NativeModuleBooleanTypeAnnotation - | NativeModuleEnumDeclaration - | NativeModuleGenericObjectTypeAnnotation - | ReservedTypeAnnotation - | NativeModuleTypeAliasTypeAnnotation - | NativeModuleArrayTypeAnnotation> - | NativeModuleObjectTypeAnnotation - | NativeModuleUnionTypeAnnotation - | NativeModuleMixedTypeAnnotation; - -export type NativeModuleParamTypeAnnotation = - | NativeModuleBaseTypeAnnotation - | NativeModuleParamOnlyTypeAnnotation; - -export type NativeModuleReturnTypeAnnotation = - | NativeModuleBaseTypeAnnotation - | NativeModuleReturnOnlyTypeAnnotation; - -export type NativeModuleTypeAnnotation = - | NativeModuleBaseTypeAnnotation - | NativeModuleParamOnlyTypeAnnotation - | NativeModuleReturnOnlyTypeAnnotation; - -type NativeModuleParamOnlyTypeAnnotation = NativeModuleFunctionTypeAnnotation; -type NativeModuleReturnOnlyTypeAnnotation = - | NativeModulePromiseTypeAnnotation - | VoidTypeAnnotation; diff --git a/packages/react-native-codegen/src/SchemaValidator.js b/packages/react-native-codegen/src/SchemaValidator.js deleted file mode 100644 index 87ded8848457..000000000000 --- a/packages/react-native-codegen/src/SchemaValidator.js +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -const nullthrows = require('nullthrows'); - -import type {SchemaType} from './CodegenSchema'; - -function getErrors(schema: SchemaType): $ReadOnlyArray { - const errors = new Set(); - - // Map of component name -> Array of module names - const componentModules: Map> = new Map(); - - Object.keys(schema.modules).forEach(moduleName => { - const module = schema.modules[moduleName]; - - if (module.components == null) { - return; - } - - Object.keys(module.components).forEach(componentName => { - if (module.components == null) { - return; - } - - if (!componentModules.has(componentName)) { - componentModules.set(componentName, []); - } - - nullthrows(componentModules.get(componentName)).push(moduleName); - }); - }); - - componentModules.forEach((modules, componentName) => { - if (modules.length > 1) { - errors.add( - `Duplicate components found with name ${componentName}. Found in modules ${modules.join( - ', ', - )}`, - ); - } - }); - - return Array.from(errors).sort(); -} - -function validate(schema: SchemaType) { - const errors = getErrors(schema); - - if (errors.length !== 0) { - throw new Error('Errors found validating schema:\n' + errors.join('\n')); - } -} - -module.exports = { - getErrors, - validate, -}; diff --git a/packages/react-native-codegen/src/__tests__/SchemaValidator-test.js b/packages/react-native-codegen/src/__tests__/SchemaValidator-test.js deleted file mode 100644 index 4d18b80c4d8d..000000000000 --- a/packages/react-native-codegen/src/__tests__/SchemaValidator-test.js +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const fixtures = require('../generators/components/__test_fixtures__/fixtures.js'); -const schemaValidator = require('../SchemaValidator.js'); - -import type {SchemaType} from '../CodegenSchema.js'; - -const simpleProp = { - name: 'disabled', - optional: true, - typeAnnotation: { - type: 'BooleanTypeAnnotation', - default: false, - }, -}; - -describe('SchemaValidator', () => { - it('fails on components across modules with same name', () => { - const fixture: SchemaType = { - modules: { - Module1: { - type: 'Component', - components: { - Component1: { - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [], - props: [simpleProp], - commands: [], - }, - }, - }, - Module2: { - type: 'Component', - components: { - Component1: { - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [], - props: [simpleProp], - commands: [], - }, - }, - }, - }, - }; - - expect(schemaValidator.getErrors(fixture)).toMatchSnapshot(); - }); - - describe('fixture', () => { - Object.keys(fixtures) - .sort() - .forEach(fixtureName => { - const fixture = fixtures[fixtureName]; - - it(`${fixtureName} has no errors`, () => { - expect(schemaValidator.getErrors(fixture)).toHaveLength(0); - }); - }); - }); -}); diff --git a/packages/react-native-codegen/src/__tests__/__snapshots__/SchemaValidator-test.js.snap b/packages/react-native-codegen/src/__tests__/__snapshots__/SchemaValidator-test.js.snap deleted file mode 100644 index 43044e364abf..000000000000 --- a/packages/react-native-codegen/src/__tests__/__snapshots__/SchemaValidator-test.js.snap +++ /dev/null @@ -1,7 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`SchemaValidator fails on components across modules with same name 1`] = ` -Array [ - "Duplicate components found with name Component1. Found in modules Module1, Module2", -] -`; diff --git a/packages/react-native-codegen/src/cli/combine/__tests__/combine-utils-test.js b/packages/react-native-codegen/src/cli/combine/__tests__/combine-utils-test.js deleted file mode 100644 index 84acd9ee5562..000000000000 --- a/packages/react-native-codegen/src/cli/combine/__tests__/combine-utils-test.js +++ /dev/null @@ -1,208 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use-strict'; - -const {parseArgs, filterJSFile} = require('../combine-utils.js'); - -describe('parseArgs', () => { - const nodeBin = 'node'; - const combineApp = 'app'; - const schemaJson = 'schema.json'; - const specFile1 = 'NativeSpec.js'; - const specFile2 = 'SpecNativeComponent.js'; - - describe('when no platform provided', () => { - it('returns null platform, schema and fileList', () => { - const {platform, outfile, fileList} = parseArgs([ - nodeBin, - combineApp, - schemaJson, - specFile1, - specFile2, - ]); - - expect(platform).toBeNull(); - expect(outfile).toBe(schemaJson); - expect(fileList).toStrictEqual([specFile1, specFile2]); - }); - }); - - describe('when platform passed with --platform', () => { - it('returns the platform, the schema and the fileList', () => { - const {platform, outfile, fileList} = parseArgs([ - nodeBin, - combineApp, - '--platform', - 'ios', - schemaJson, - specFile1, - specFile2, - ]); - - expect(platform).toBe('ios'); - expect(outfile).toBe(schemaJson); - expect(fileList).toStrictEqual([specFile1, specFile2]); - }); - }); - - describe('when platform passed with -p', () => { - it('returns the platform, the schema and the fileList', () => { - const {platform, outfile, fileList} = parseArgs([ - nodeBin, - combineApp, - '-p', - 'android', - schemaJson, - specFile1, - specFile2, - ]); - - expect(platform).toBe('android'); - expect(outfile).toBe(schemaJson); - expect(fileList).toStrictEqual([specFile1, specFile2]); - }); - }); -}); - -describe('filterJSFile', () => { - describe('When the file is not a Spec file', () => { - it('when no platform is passed, return false', () => { - const file = 'anyJSFile.js'; - const result = filterJSFile(file); - expect(result).toBeFalsy(); - }); - - it('when ios is passed and the file is iOS specific, return false', () => { - const file = 'anyJSFile.ios.js'; - const result = filterJSFile(file); - expect(result).toBeFalsy(); - }); - - it('when android is passed and the file is android specific, return false', () => { - const file = 'anyJSFile.android.js'; - const result = filterJSFile(file); - expect(result).toBeFalsy(); - }); - }); - - describe('When the file is NativeUIManager', () => { - it('returns false', () => { - const file = 'NativeUIManager.js'; - const result = filterJSFile(file); - expect(result).toBeFalsy(); - }); - }); - - describe('When the file is NativeSampleTurboModule', () => { - it('returns false', () => { - const file = 'NativeSampleTurboModule.js'; - const result = filterJSFile(file); - expect(result).toBeFalsy(); - }); - }); - - describe('When the file is a test file', () => { - it('returns false', () => { - const file = '__tests__/NativeModule-test.js'; - const result = filterJSFile(file); - expect(result).toBeFalsy(); - }); - }); - - describe('When the file is a TS type def', () => { - it('returns false', () => { - const file = 'NativeModule.d.ts'; - const result = filterJSFile(file); - expect(result).toBeFalsy(); - }); - }); - - describe('When the file is valid and it is platform agnostic', () => { - const file = 'NativeModule.js'; - it('if the platform is null, returns true', () => { - const result = filterJSFile(file); - expect(result).toBeTruthy(); - }); - it('if the platform is ios, returns true', () => { - const result = filterJSFile(file, 'ios'); - expect(result).toBeTruthy(); - }); - it('if the platform is android, returns true', () => { - const result = filterJSFile(file, 'android'); - expect(result).toBeTruthy(); - }); - it('if the platform is windows, returns false', () => { - const result = filterJSFile(file, 'windows'); - expect(result).toBeTruthy(); - }); - }); - - describe('When the file is valid and it is iOS specific', () => { - const file = 'MySampleNativeComponent.ios.js'; - it('if the platform is null, returns false', () => { - const result = filterJSFile(file); - expect(result).toBeFalsy(); - }); - it('if the platform is ios, returns true', () => { - const result = filterJSFile(file, 'ios'); - expect(result).toBeTruthy(); - }); - it('if the platform is android, returns false', () => { - const result = filterJSFile(file, 'android'); - expect(result).toBeFalsy(); - }); - it('if the platform is windows, returns false', () => { - const result = filterJSFile(file, 'windows'); - expect(result).toBeFalsy(); - }); - }); - - describe('When the file is valid and it is Android specific', () => { - const file = 'MySampleNativeComponent.android.js'; - it('if the platform is null, returns false', () => { - const result = filterJSFile(file); - expect(result).toBeFalsy(); - }); - it('if the platform is ios, returns false', () => { - const result = filterJSFile(file, 'ios'); - expect(result).toBeFalsy(); - }); - it('if the platform is android, returns true', () => { - const result = filterJSFile(file, 'android'); - expect(result).toBeTruthy(); - }); - it('if the platform is windows, returns false', () => { - const result = filterJSFile(file, 'windows'); - expect(result).toBeFalsy(); - }); - }); - - describe('When the file is valid and it is Windows specific', () => { - const file = 'MySampleNativeComponent.windows.js'; - it('if the platform is null, returns false', () => { - const result = filterJSFile(file); - expect(result).toBeFalsy(); - }); - it('if the platform is ios, returns false', () => { - const result = filterJSFile(file, 'ios'); - expect(result).toBeFalsy(); - }); - it('if the platform is android, returns false', () => { - const result = filterJSFile(file, 'android'); - expect(result).toBeFalsy(); - }); - it('if the platform is windows, returns true', () => { - const result = filterJSFile(file, 'windows'); - expect(result).toBeTruthy(); - }); - }); -}); diff --git a/packages/react-native-codegen/src/cli/combine/combine-js-to-schema-cli.js b/packages/react-native-codegen/src/cli/combine/combine-js-to-schema-cli.js deleted file mode 100644 index 00fadf3dd661..000000000000 --- a/packages/react-native-codegen/src/cli/combine/combine-js-to-schema-cli.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const combine = require('./combine-js-to-schema'); -const fs = require('fs'); -const glob = require('glob'); -const {parseArgs, filterJSFile} = require('./combine-utils'); - -const {platform, outfile, fileList} = parseArgs(process.argv); - -const allFiles = []; -fileList.forEach(file => { - if (fs.lstatSync(file).isDirectory()) { - const dirFiles = glob - .sync(`${file}/**/*.{js,ts,tsx}`, { - nodir: true, - }) - .filter(element => filterJSFile(element, platform)); - allFiles.push(...dirFiles); - } else if (filterJSFile(file)) { - allFiles.push(file); - } -}); - -const combined = combine(allFiles); - -// Warn users if there is no modules to process -if (Object.keys(combined.modules).length === 0) { - console.error( - 'No modules to process in combine-js-to-schema-cli. If this is unexpected, please check if you set up your NativeComponent correctly. See combine-js-to-schema.js for how codegen finds modules.', - ); -} -const formattedSchema = JSON.stringify(combined, null, 2); - -if (outfile != null) { - fs.writeFileSync(outfile, formattedSchema); -} else { - console.log(formattedSchema); -} diff --git a/packages/react-native-codegen/src/cli/combine/combine-js-to-schema.js b/packages/react-native-codegen/src/cli/combine/combine-js-to-schema.js deleted file mode 100644 index e4bc8780db67..000000000000 --- a/packages/react-native-codegen/src/cli/combine/combine-js-to-schema.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; -import type {SchemaType} from '../../CodegenSchema.js'; - -const {parseFile} = require('../../parsers/utils'); -const FlowParser = require('../../parsers/flow'); -const TypeScriptParser = require('../../parsers/typescript'); -const fs = require('fs'); -const path = require('path'); - -function combineSchemas(files: Array): SchemaType { - return files.reduce( - (merged, filename) => { - const contents = fs.readFileSync(filename, 'utf8'); - - if ( - contents && - (/export\s+default\s+\(?codegenNativeComponent 2 && ['-p', '--platform'].indexOf(args[2]) >= 0) { - const [outfile, ...fileList] = args.slice(4); - return { - platform: args[3], - outfile, - fileList, - }; - } - - const [outfile, ...fileList] = args.slice(2); - return { - platform: null, - outfile, - fileList, - }; -} - -/** - * This function is used by the CLI to decide whether a JS/TS file has to be processed or not by the Codegen. - * Parameters: - * - file: the path to the file - * - currentPlatform: the current platform for which we are creating the specs - * Returns: `true` if the file can be used to generate some code; `false` otherwise - * - */ -function filterJSFile(file: string, currentPlatform: ?string): boolean { - const isSpecFile = /^(Native.+|.+NativeComponent)/.test(path.basename(file)); - const isNotNativeUIManager = !file.endsWith('NativeUIManager.js'); - const isNotNativeSampleTurboModule = !file.endsWith( - 'NativeSampleTurboModule.js', - ); - const isNotTest = !file.includes('__tests'); - const isNotTSTypeDefinition = !file.endsWith('.d.ts'); - - const isValidCandidate = - isSpecFile && - isNotNativeUIManager && - isNotNativeSampleTurboModule && - isNotTest && - isNotTSTypeDefinition; - - const filenameComponents = path.basename(file).split('.'); - const isPlatformAgnostic = filenameComponents.length === 2; - - if (currentPlatform == null) { - // need to accept only files that are platform agnostic - return isValidCandidate && isPlatformAgnostic; - } - - // If a platform is passed, accept both platform agnostic specs... - if (isPlatformAgnostic) { - return isValidCandidate; - } - - // ...and specs that share the same platform as the one passed. - // specfiles must follow the pattern: [.].(js|ts|tsx) - const filePlatform = - filenameComponents.length > 2 ? filenameComponents[1] : 'unknown'; - return isValidCandidate && currentPlatform === filePlatform; -} - -module.exports = { - parseArgs, - filterJSFile, -}; diff --git a/packages/react-native-codegen/src/cli/generators/generate-all.js b/packages/react-native-codegen/src/cli/generators/generate-all.js deleted file mode 100644 index 46d207510208..000000000000 --- a/packages/react-native-codegen/src/cli/generators/generate-all.js +++ /dev/null @@ -1,66 +0,0 @@ -/** - * 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 - */ - -/** - * This generates all possible outputs by executing all available generators. - */ - -'use strict'; - -const RNCodegen = require('../../generators/RNCodegen.js'); -const fs = require('fs'); -const mkdirp = require('mkdirp'); - -const args = process.argv.slice(2); -if (args.length < 3) { - throw new Error( - `Expected to receive path to schema, library name, output directory and module spec name. Received ${args.join( - ', ', - )}`, - ); -} - -const schemaPath = args[0]; -const libraryName = args[1]; -const outputDirectory = args[2]; -const packageName = args[3]; -const assumeNonnull = args[4] === 'true' || args[4] === 'True'; - -const schemaText = fs.readFileSync(schemaPath, 'utf-8'); - -if (schemaText == null) { - throw new Error(`Can't find schema at ${schemaPath}`); -} - -mkdirp.sync(outputDirectory); - -let schema; -try { - schema = JSON.parse(schemaText); -} catch (err) { - throw new Error(`Can't parse schema to JSON. ${schemaPath}`); -} - -RNCodegen.generate( - {libraryName, schema, outputDirectory, packageName, assumeNonnull}, - { - generators: [ - 'descriptors', - 'events', - 'props', - 'states', - 'tests', - 'shadow-nodes', - 'modulesAndroid', - 'modulesCxx', - 'modulesIOS', - ], - }, -); diff --git a/packages/react-native-codegen/src/cli/parser/parser-cli.js b/packages/react-native-codegen/src/cli/parser/parser-cli.js deleted file mode 100644 index 084b11c7adec..000000000000 --- a/packages/react-native-codegen/src/cli/parser/parser-cli.js +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const parseFiles = require('./parser.js'); - -const [...fileList] = process.argv.slice(2); - -parseFiles(fileList); diff --git a/packages/react-native-codegen/src/cli/parser/parser.js b/packages/react-native-codegen/src/cli/parser/parser.js deleted file mode 100644 index 1afc70035bc0..000000000000 --- a/packages/react-native-codegen/src/cli/parser/parser.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -const path = require('path'); -const {parseFile} = require('../../parsers/utils'); -const FlowParser = require('../../parsers/flow'); -const TypeScriptParser = require('../../parsers/typescript'); - -function parseFiles(files: Array) { - files.forEach(filename => { - const isTypeScript = - path.extname(filename) === '.ts' || path.extname(filename) === '.tsx'; - - console.log( - filename, - JSON.stringify( - parseFile( - filename, - isTypeScript ? TypeScriptParser.buildSchema : FlowParser.buildSchema, - ), - null, - 2, - ), - ); - }); -} - -module.exports = parseFiles; diff --git a/packages/react-native-codegen/src/cli/parser/parser.sh b/packages/react-native-codegen/src/cli/parser/parser.sh deleted file mode 100755 index 8d130f250017..000000000000 --- a/packages/react-native-codegen/src/cli/parser/parser.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/bash -# 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. - -set -e -set -u - -THIS_DIR=$(cd -P "$(dirname "$(realpath "${BASH_SOURCE[0]}" || echo "${BASH_SOURCE[0]}")")" && pwd) - -# shellcheck source=xplat/js/env-utils/setup_env_vars.sh -source "$THIS_DIR/../../../../../../env-utils/setup_env_vars.sh" - -exec "$FLOW_NODE_BINARY" "$THIS_DIR/parser.js" "$@" diff --git a/packages/react-native-codegen/src/generators/RNCodegen.js b/packages/react-native-codegen/src/generators/RNCodegen.js deleted file mode 100644 index b2648c626c1a..000000000000 --- a/packages/react-native-codegen/src/generators/RNCodegen.js +++ /dev/null @@ -1,284 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -/* -TODO: - -- ViewConfigs should spread in View's valid attributes -*/ - -const fs = require('fs'); -const generateComponentDescriptorH = require('./components/GenerateComponentDescriptorH.js'); -const generateComponentHObjCpp = require('./components/GenerateComponentHObjCpp.js'); -const generateEventEmitterCpp = require('./components/GenerateEventEmitterCpp.js'); -const generateEventEmitterH = require('./components/GenerateEventEmitterH.js'); -const generatePropsCpp = require('./components/GeneratePropsCpp.js'); -const generatePropsH = require('./components/GeneratePropsH.js'); -const generateStateCpp = require('./components/GenerateStateCpp.js'); -const generateStateH = require('./components/GenerateStateH.js'); -const generateModuleH = require('./modules/GenerateModuleH.js'); -const generateModuleCpp = require('./modules/GenerateModuleCpp.js'); -const generateModuleObjCpp = require('./modules/GenerateModuleObjCpp'); -const generateModuleJavaSpec = require('./modules/GenerateModuleJavaSpec.js'); -const GenerateModuleJniCpp = require('./modules/GenerateModuleJniCpp.js'); -const GenerateModuleJniH = require('./modules/GenerateModuleJniH.js'); -const generatePropsJavaInterface = require('./components/GeneratePropsJavaInterface.js'); -const generatePropsJavaDelegate = require('./components/GeneratePropsJavaDelegate.js'); -const generateTests = require('./components/GenerateTests.js'); -const generateShadowNodeCpp = require('./components/GenerateShadowNodeCpp.js'); -const generateShadowNodeH = require('./components/GenerateShadowNodeH.js'); -const generateThirdPartyFabricComponentsProviderObjCpp = require('./components/GenerateThirdPartyFabricComponentsProviderObjCpp.js'); -const generateThirdPartyFabricComponentsProviderH = require('./components/GenerateThirdPartyFabricComponentsProviderH.js'); -const generateViewConfigJs = require('./components/GenerateViewConfigJs.js'); -const path = require('path'); -const schemaValidator = require('../SchemaValidator.js'); - -import type {SchemaType} from '../CodegenSchema'; - -type LibraryOptions = $ReadOnly<{ - libraryName: string, - schema: SchemaType, - outputDirectory: string, - packageName?: string, // Some platforms have a notion of package, which should be configurable. - assumeNonnull: boolean, -}>; - -type SchemasOptions = $ReadOnly<{ - schemas: {[string]: SchemaType}, - outputDirectory: string, -}>; - -type LibraryGenerators = - | 'componentsAndroid' - | 'componentsIOS' - | 'descriptors' - | 'events' - | 'props' - | 'states' - | 'tests' - | 'shadow-nodes' - | 'modulesAndroid' - | 'modulesCxx' - | 'modulesIOS'; - -type SchemasGenerators = 'providerIOS'; - -type LibraryConfig = $ReadOnly<{ - generators: Array, - test?: boolean, -}>; - -type SchemasConfig = $ReadOnly<{ - generators: Array, - test?: boolean, -}>; - -const LIBRARY_GENERATORS = { - descriptors: [generateComponentDescriptorH.generate], - events: [generateEventEmitterCpp.generate, generateEventEmitterH.generate], - states: [generateStateCpp.generate, generateStateH.generate], - props: [ - generateComponentHObjCpp.generate, - generatePropsCpp.generate, - generatePropsH.generate, - generatePropsJavaInterface.generate, - generatePropsJavaDelegate.generate, - ], - // TODO: Refactor this to consolidate various C++ output variation instead of forking per platform. - componentsAndroid: [ - // JNI/C++ files - generateComponentDescriptorH.generate, - generateEventEmitterCpp.generate, - generateEventEmitterH.generate, - generatePropsCpp.generate, - generatePropsH.generate, - generateStateCpp.generate, - generateStateH.generate, - generateShadowNodeCpp.generate, - generateShadowNodeH.generate, - // Java files - generatePropsJavaInterface.generate, - generatePropsJavaDelegate.generate, - ], - componentsIOS: [ - generateComponentDescriptorH.generate, - generateEventEmitterCpp.generate, - generateEventEmitterH.generate, - generateComponentHObjCpp.generate, - generatePropsCpp.generate, - generatePropsH.generate, - generateStateCpp.generate, - generateStateH.generate, - generateShadowNodeCpp.generate, - generateShadowNodeH.generate, - ], - modulesAndroid: [ - GenerateModuleJniCpp.generate, - GenerateModuleJniH.generate, - generateModuleJavaSpec.generate, - ], - modulesCxx: [generateModuleCpp.generate, generateModuleH.generate], - modulesIOS: [generateModuleObjCpp.generate], - tests: [generateTests.generate], - 'shadow-nodes': [ - generateShadowNodeCpp.generate, - generateShadowNodeH.generate, - ], -}; - -const SCHEMAS_GENERATORS = { - providerIOS: [ - generateThirdPartyFabricComponentsProviderObjCpp.generate, - generateThirdPartyFabricComponentsProviderH.generate, - ], -}; - -type CodeGenFile = { - name: string, - content: string, - outputDir: string, -}; - -function writeMapToFiles(map: Array) { - let success = true; - map.forEach(file => { - try { - const location = path.join(file.outputDir, file.name); - const dirName = path.dirname(location); - if (!fs.existsSync(dirName)) { - fs.mkdirSync(dirName, {recursive: true}); - } - fs.writeFileSync(location, file.content); - } catch (error) { - success = false; - console.error(`Failed to write ${file.name} to ${file.outputDir}`, error); - } - }); - - return success; -} - -function checkFilesForChanges(generated: Array): boolean { - let hasChanged = false; - - generated.forEach(file => { - const location = path.join(file.outputDir, file.name); - const currentContents = fs.readFileSync(location, 'utf8'); - if (currentContents !== file.content) { - console.error(`- ${file.name} has changed`); - - hasChanged = true; - } - }); - - return !hasChanged; -} - -function checkOrWriteFiles( - generatedFiles: Array, - test: void | boolean, -): boolean { - if (test === true) { - return checkFilesForChanges(generatedFiles); - } - return writeMapToFiles(generatedFiles); -} - -module.exports = { - generate( - { - libraryName, - schema, - outputDirectory, - packageName, - assumeNonnull, - }: LibraryOptions, - {generators, test}: LibraryConfig, - ): boolean { - schemaValidator.validate(schema); - - function composePath(intermediate: string) { - return path.join(outputDirectory, intermediate, libraryName); - } - - const componentIOSOutput = composePath('react/renderer/components/'); - const modulesIOSOutput = composePath('./'); - - const outputFoldersForGenerators = { - componentsIOS: componentIOSOutput, - modulesIOS: modulesIOSOutput, - descriptors: outputDirectory, - events: outputDirectory, - props: outputDirectory, - states: outputDirectory, - componentsAndroid: outputDirectory, - modulesAndroid: outputDirectory, - modulesCxx: outputDirectory, - tests: outputDirectory, - 'shadow-nodes': outputDirectory, - }; - - const generatedFiles: Array = []; - - for (const name of generators) { - for (const generator of LIBRARY_GENERATORS[name]) { - generator(libraryName, schema, packageName, assumeNonnull).forEach( - (contents: string, fileName: string) => { - generatedFiles.push({ - name: fileName, - content: contents, - outputDir: outputFoldersForGenerators[name], - }); - }, - ); - } - } - return checkOrWriteFiles(generatedFiles, test); - }, - generateFromSchemas( - {schemas, outputDirectory}: SchemasOptions, - {generators, test}: SchemasConfig, - ): boolean { - Object.keys(schemas).forEach(libraryName => - schemaValidator.validate(schemas[libraryName]), - ); - - const generatedFiles: Array = []; - - for (const name of generators) { - for (const generator of SCHEMAS_GENERATORS[name]) { - generator(schemas).forEach((contents: string, fileName: string) => { - generatedFiles.push({ - name: fileName, - content: contents, - outputDir: outputDirectory, - }); - }); - } - } - return checkOrWriteFiles(generatedFiles, test); - }, - generateViewConfig({libraryName, schema}: LibraryOptions): string { - schemaValidator.validate(schema); - - const result = generateViewConfigJs - .generate(libraryName, schema) - .values() - .next(); - - if (typeof result.value !== 'string') { - throw new Error(`Failed to generate view config for ${libraryName}`); - } - - return result.value; - }, -}; diff --git a/packages/react-native-codegen/src/generators/Utils.js b/packages/react-native-codegen/src/generators/Utils.js deleted file mode 100644 index e5d1e1b5f68f..000000000000 --- a/packages/react-native-codegen/src/generators/Utils.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -function capitalize(string: string): string { - return string.charAt(0).toUpperCase() + string.slice(1); -} - -function indent(nice: string, spaces: number): string { - return nice - .split('\n') - .map((line, index) => { - if (line.length === 0 || index === 0) { - return line; - } - const emptySpaces = new Array(spaces + 1).join(' '); - return emptySpaces + line; - }) - .join('\n'); -} - -module.exports = { - capitalize, - indent, -}; diff --git a/packages/react-native-codegen/src/generators/__test_fixtures__/fixtures.js b/packages/react-native-codegen/src/generators/__test_fixtures__/fixtures.js deleted file mode 100644 index b86597683933..000000000000 --- a/packages/react-native-codegen/src/generators/__test_fixtures__/fixtures.js +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {SchemaType} from '../../CodegenSchema.js'; - -const SCHEMA_WITH_TM_AND_FC: SchemaType = { - modules: { - ColoredView: { - type: 'Component', - components: { - ColoredView: { - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [], - props: [ - { - name: 'color', - optional: false, - typeAnnotation: { - type: 'StringTypeAnnotation', - default: null, - }, - }, - ], - commands: [], - }, - }, - }, - NativeCalculator: { - type: 'NativeModule', - aliases: {}, - spec: { - properties: [ - { - name: 'add', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'PromiseTypeAnnotation', - }, - params: [ - { - name: 'a', - optional: false, - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - { - name: 'b', - optional: false, - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - ], - }, - }, - ], - }, - moduleNames: ['Calculator'], - }, - }, -}; - -module.exports = { - all: SCHEMA_WITH_TM_AND_FC, -}; diff --git a/packages/react-native-codegen/src/generators/__tests__/RNCodegen-test.js b/packages/react-native-codegen/src/generators/__tests__/RNCodegen-test.js deleted file mode 100644 index 44a70349ab2e..000000000000 --- a/packages/react-native-codegen/src/generators/__tests__/RNCodegen-test.js +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const rnCodegen = require('../RNCodegen.js'); -const fixture = require('../__test_fixtures__/fixtures.js'); -const packageName = 'na'; - -describe('RNCodegen.generate', () => { - beforeEach(() => { - jest.resetModules(); - }); - - it('when type `all`, with default paths', () => { - jest.mock('fs', () => ({ - existsSync: location => { - return true; - }, - writeFileSync: (location, content) => { - // Jest in the OSS does not allow to capture variables in closures. - // Therefore, we have to bring the variables inside the closure. - // see: https://github.com/facebook/jest/issues/2567 - const path = require('path'); - const outputDirectory = 'tmp/out/'; - const componentsOutputDir = 'react/renderer/components/library'; - const modulesOutputDir = 'library'; - const expectedPaths = { - 'library.h': modulesOutputDir, - 'library-generated.mm': modulesOutputDir, - 'ShadowNodes.h': componentsOutputDir, - 'ShadowNodes.cpp': componentsOutputDir, - 'Props.h': componentsOutputDir, - 'Props.cpp': componentsOutputDir, - 'States.h': componentsOutputDir, - 'States.cpp': componentsOutputDir, - 'RCTComponentViewHelpers.h': componentsOutputDir, - 'EventEmitters.h': componentsOutputDir, - 'EventEmitters.cpp': componentsOutputDir, - 'ComponentDescriptors.h': componentsOutputDir, - }; - - let receivedDir = path.dirname(location); - let receivedBasename = path.basename(location); - - let expectedPath = path.join( - outputDirectory, - expectedPaths[receivedBasename], - ); - expect(receivedDir).toEqual(expectedPath); - }, - })); - - const outputDirectory = 'tmp/out/'; - const res = rnCodegen.generate( - { - libraryName: 'library', - schema: fixture.all, - outputDirectory: outputDirectory, - packageName: packageName, - assumeNonnull: true, - }, - { - generators: ['componentsIOS', 'modulesIOS'], - test: false, - }, - ); - - expect(res).toBeTruthy(); - }); -}); diff --git a/packages/react-native-codegen/src/generators/components/ComponentsGeneratorUtils.js b/packages/react-native-codegen/src/generators/components/ComponentsGeneratorUtils.js deleted file mode 100644 index 104b35d45293..000000000000 --- a/packages/react-native-codegen/src/generators/components/ComponentsGeneratorUtils.js +++ /dev/null @@ -1,307 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type {NamedShape, PropTypeAnnotation} from '../../CodegenSchema'; - -import type { - StringTypeAnnotation, - ReservedPropTypeAnnotation, - ObjectTypeAnnotation, - Int32TypeAnnotation, - FloatTypeAnnotation, - DoubleTypeAnnotation, - BooleanTypeAnnotation, -} from '../../CodegenSchema'; - -const { - getCppTypeForAnnotation, - getEnumMaskName, - getEnumName, - generateStructName, - getImports, -} = require('./CppHelpers.js'); - -function getNativeTypeFromAnnotation( - componentName: string, - prop: - | NamedShape - | { - name: string, - typeAnnotation: - | $FlowFixMe - | DoubleTypeAnnotation - | FloatTypeAnnotation - | BooleanTypeAnnotation - | Int32TypeAnnotation - | StringTypeAnnotation - | ObjectTypeAnnotation - | ReservedPropTypeAnnotation - | { - +default: string, - +options: $ReadOnlyArray, - +type: 'StringEnumTypeAnnotation', - } - | { - +elementType: ObjectTypeAnnotation, - +type: 'ArrayTypeAnnotation', - }, - }, - nameParts: $ReadOnlyArray, -): string { - const typeAnnotation = prop.typeAnnotation; - - switch (typeAnnotation.type) { - case 'BooleanTypeAnnotation': - case 'StringTypeAnnotation': - case 'Int32TypeAnnotation': - case 'DoubleTypeAnnotation': - case 'FloatTypeAnnotation': - return getCppTypeForAnnotation(typeAnnotation.type); - case 'ReservedPropTypeAnnotation': - switch (typeAnnotation.name) { - case 'ColorPrimitive': - return 'SharedColor'; - case 'ImageSourcePrimitive': - return 'ImageSource'; - case 'ImageRequestPrimitive': - return 'ImageRequest'; - case 'PointPrimitive': - return 'Point'; - case 'EdgeInsetsPrimitive': - return 'EdgeInsets'; - default: - (typeAnnotation.name: empty); - throw new Error('Received unknown ReservedPropTypeAnnotation'); - } - case 'ArrayTypeAnnotation': { - const arrayType = typeAnnotation.elementType.type; - if (arrayType === 'ArrayTypeAnnotation') { - return `std::vector<${getNativeTypeFromAnnotation( - componentName, - {typeAnnotation: typeAnnotation.elementType, name: ''}, - nameParts.concat([prop.name]), - )}>`; - } - if (arrayType === 'ObjectTypeAnnotation') { - const structName = generateStructName( - componentName, - nameParts.concat([prop.name]), - ); - return `std::vector<${structName}>`; - } - if (arrayType === 'StringEnumTypeAnnotation') { - const enumName = getEnumName(componentName, prop.name); - return getEnumMaskName(enumName); - } - const itemAnnotation = getNativeTypeFromAnnotation( - componentName, - { - typeAnnotation: typeAnnotation.elementType, - name: componentName, - }, - nameParts.concat([prop.name]), - ); - return `std::vector<${itemAnnotation}>`; - } - case 'ObjectTypeAnnotation': { - return generateStructName(componentName, nameParts.concat([prop.name])); - } - case 'StringEnumTypeAnnotation': - return getEnumName(componentName, prop.name); - case 'Int32EnumTypeAnnotation': - return getEnumName(componentName, prop.name); - default: - (typeAnnotation: empty); - throw new Error( - `Received invalid typeAnnotation for ${componentName} prop ${prop.name}, received ${typeAnnotation.type}`, - ); - } -} - -/// This function process some types if we need to customize them -/// For example, the ImageSource and the reserved types could be trasformed into -/// const address instead of using them as plain types. -function convertTypesToConstAddressIfNeeded( - type: string, - convertibleTypes: Set, -): string { - if (convertibleTypes.has(type)) { - return `${type} const &`; - } - return type; -} - -function convertValueToSharedPointerWithMove( - type: string, - value: string, - convertibleTypes: Set, -): string { - if (convertibleTypes.has(type)) { - return `std::make_shared<${type}>(std::move(${value}))`; - } - return value; -} - -function convertVariableToSharedPointer( - type: string, - convertibleTypes: Set, -): string { - if (convertibleTypes.has(type)) { - return `std::shared_ptr<${type}>`; - } - return type; -} - -function convertVariableToPointer( - type: string, - value: string, - convertibleTypes: Set, -): string { - if (convertibleTypes.has(type)) { - return `*${value}`; - } - return value; -} - -const convertCtorParamToAddressType = (type: string): string => { - const typesToConvert: Set = new Set(); - typesToConvert.add('ImageSource'); - - return convertTypesToConstAddressIfNeeded(type, typesToConvert); -}; - -const convertCtorInitToSharedPointers = ( - type: string, - value: string, -): string => { - const typesToConvert: Set = new Set(); - typesToConvert.add('ImageRequest'); - - return convertValueToSharedPointerWithMove(type, value, typesToConvert); -}; - -const convertGettersReturnTypeToAddressType = (type: string): string => { - const typesToConvert: Set = new Set(); - typesToConvert.add('ImageRequest'); - - return convertTypesToConstAddressIfNeeded(type, typesToConvert); -}; - -const convertVarTypeToSharedPointer = (type: string): string => { - const typesToConvert: Set = new Set(); - typesToConvert.add('ImageRequest'); - - return convertVariableToSharedPointer(type, typesToConvert); -}; - -const convertVarValueToPointer = (type: string, value: string): string => { - const typesToConvert: Set = new Set(); - typesToConvert.add('ImageRequest'); - - return convertVariableToPointer(type, value, typesToConvert); -}; - -function getLocalImports( - properties: $ReadOnlyArray>, -): Set { - const imports: Set = new Set(); - - function addImportsForNativeName( - name: - | 'ColorPrimitive' - | 'EdgeInsetsPrimitive' - | 'ImageSourcePrimitive' - | 'PointPrimitive' - | 'ImageRequestPrimitive', - ) { - switch (name) { - case 'ColorPrimitive': - imports.add('#include '); - return; - case 'ImageSourcePrimitive': - imports.add('#include '); - return; - case 'ImageRequestPrimitive': - imports.add('#include '); - return; - case 'PointPrimitive': - imports.add('#include '); - return; - case 'EdgeInsetsPrimitive': - imports.add('#include '); - return; - default: - (name: empty); - throw new Error(`Invalid ReservedPropTypeAnnotation name, got ${name}`); - } - } - - properties.forEach(prop => { - const typeAnnotation = prop.typeAnnotation; - - if (typeAnnotation.type === 'ReservedPropTypeAnnotation') { - addImportsForNativeName(typeAnnotation.name); - } - - if (typeAnnotation.type === 'ArrayTypeAnnotation') { - imports.add('#include '); - if (typeAnnotation.elementType.type === 'StringEnumTypeAnnotation') { - imports.add('#include '); - } - } - - if ( - typeAnnotation.type === 'ArrayTypeAnnotation' && - typeAnnotation.elementType.type === 'ReservedPropTypeAnnotation' - ) { - addImportsForNativeName(typeAnnotation.elementType.name); - } - - if ( - typeAnnotation.type === 'ArrayTypeAnnotation' && - typeAnnotation.elementType.type === 'ObjectTypeAnnotation' - ) { - imports.add('#include '); - const objectProps = typeAnnotation.elementType.properties; - // $FlowFixMe[incompatible-call] the type is guaranteed to be ObjectTypeAnnotation - const objectImports = getImports(objectProps); - // $FlowFixMe[incompatible-call] the type is guaranteed to be ObjectTypeAnnotation - const localImports = getLocalImports(objectProps); - // $FlowFixMe[method-unbinding] added when improving typing for this parameters - objectImports.forEach(imports.add, imports); - // $FlowFixMe[method-unbinding] added when improving typing for this parameters - localImports.forEach(imports.add, imports); - } - - if (typeAnnotation.type === 'ObjectTypeAnnotation') { - imports.add('#include '); - const objectImports = getImports(typeAnnotation.properties); - const localImports = getLocalImports(typeAnnotation.properties); - // $FlowFixMe[method-unbinding] added when improving typing for this parameters - objectImports.forEach(imports.add, imports); - // $FlowFixMe[method-unbinding] added when improving typing for this parameters - localImports.forEach(imports.add, imports); - } - }); - - return imports; -} - -module.exports = { - getNativeTypeFromAnnotation, - convertCtorParamToAddressType, - convertGettersReturnTypeToAddressType, - convertCtorInitToSharedPointers, - convertVarTypeToSharedPointer, - convertVarValueToPointer, - getLocalImports, -}; diff --git a/packages/react-native-codegen/src/generators/components/CppHelpers.js b/packages/react-native-codegen/src/generators/components/CppHelpers.js deleted file mode 100644 index 2f222412878b..000000000000 --- a/packages/react-native-codegen/src/generators/components/CppHelpers.js +++ /dev/null @@ -1,228 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; -import type {NamedShape, PropTypeAnnotation} from '../../CodegenSchema'; - -function upperCaseFirst(inString: string): string { - if (inString.length === 0) { - return inString; - } - - return inString[0].toUpperCase() + inString.slice(1); -} - -function toSafeCppString(input: string): string { - return input.split('-').map(upperCaseFirst).join(''); -} - -function toIntEnumValueName(propName: string, value: number): string { - return `${toSafeCppString(propName)}${value}`; -} - -function getCppTypeForAnnotation( - type: - | 'BooleanTypeAnnotation' - | 'StringTypeAnnotation' - | 'Int32TypeAnnotation' - | 'DoubleTypeAnnotation' - | 'FloatTypeAnnotation', -): string { - switch (type) { - case 'BooleanTypeAnnotation': - return 'bool'; - case 'StringTypeAnnotation': - return 'std::string'; - case 'Int32TypeAnnotation': - return 'int'; - case 'DoubleTypeAnnotation': - return 'double'; - case 'FloatTypeAnnotation': - return 'Float'; - default: - (type: empty); - throw new Error(`Received invalid typeAnnotation ${type}`); - } -} - -function getImports( - properties: $ReadOnlyArray>, -): Set { - const imports: Set = new Set(); - - function addImportsForNativeName( - name: - | 'ColorPrimitive' - | 'EdgeInsetsPrimitive' - | 'ImageRequestPrimitive' - | 'ImageSourcePrimitive' - | 'PointPrimitive', - ) { - switch (name) { - case 'ColorPrimitive': - return; - case 'PointPrimitive': - return; - case 'EdgeInsetsPrimitive': - return; - case 'ImageRequestPrimitive': - return; - case 'ImageSourcePrimitive': - imports.add('#include '); - return; - default: - (name: empty); - throw new Error(`Invalid name, got ${name}`); - } - } - - properties.forEach(prop => { - const typeAnnotation = prop.typeAnnotation; - - if (typeAnnotation.type === 'ReservedPropTypeAnnotation') { - addImportsForNativeName(typeAnnotation.name); - } - - if ( - typeAnnotation.type === 'ArrayTypeAnnotation' && - typeAnnotation.elementType.type === 'ReservedPropTypeAnnotation' - ) { - addImportsForNativeName(typeAnnotation.elementType.name); - } - - if (typeAnnotation.type === 'ObjectTypeAnnotation') { - const objectImports = getImports(typeAnnotation.properties); - // $FlowFixMe[method-unbinding] added when improving typing for this parameters - objectImports.forEach(imports.add, imports); - } - }); - - return imports; -} - -function generateEventStructName(parts: $ReadOnlyArray = []): string { - const additional = parts.map(toSafeCppString).join(''); - return `${additional}`; -} - -function generateStructName( - componentName: string, - parts: $ReadOnlyArray = [], -): string { - const additional = parts.map(toSafeCppString).join(''); - return `${componentName}${additional}Struct`; -} - -function getEnumName(componentName: string, propName: string): string { - const uppercasedPropName = toSafeCppString(propName); - return `${componentName}${uppercasedPropName}`; -} - -function getEnumMaskName(enumName: string): string { - return `${enumName}Mask`; -} - -function convertDefaultTypeToString( - componentName: string, - prop: NamedShape, -): string { - const typeAnnotation = prop.typeAnnotation; - switch (typeAnnotation.type) { - case 'BooleanTypeAnnotation': - if (typeAnnotation.default == null) { - return ''; - } - return String(typeAnnotation.default); - case 'StringTypeAnnotation': - if (typeAnnotation.default == null) { - return ''; - } - return `"${typeAnnotation.default}"`; - case 'Int32TypeAnnotation': - return String(typeAnnotation.default); - case 'DoubleTypeAnnotation': - const defaultDoubleVal = typeAnnotation.default; - return parseInt(defaultDoubleVal, 10) === defaultDoubleVal - ? typeAnnotation.default.toFixed(1) - : String(typeAnnotation.default); - case 'FloatTypeAnnotation': - const defaultFloatVal = typeAnnotation.default; - if (defaultFloatVal == null) { - return ''; - } - return parseInt(defaultFloatVal, 10) === defaultFloatVal - ? defaultFloatVal.toFixed(1) - : String(typeAnnotation.default); - case 'ReservedPropTypeAnnotation': - switch (typeAnnotation.name) { - case 'ColorPrimitive': - return ''; - case 'ImageSourcePrimitive': - return ''; - case 'ImageRequestPrimitive': - return ''; - case 'PointPrimitive': - return ''; - case 'EdgeInsetsPrimitive': - return ''; - default: - (typeAnnotation.name: empty); - throw new Error( - `Unsupported type annotation: ${typeAnnotation.name}`, - ); - } - case 'ArrayTypeAnnotation': { - const elementType = typeAnnotation.elementType; - switch (elementType.type) { - case 'StringEnumTypeAnnotation': - if (elementType.default == null) { - throw new Error( - 'A default is required for array StringEnumTypeAnnotation', - ); - } - const enumName = getEnumName(componentName, prop.name); - const enumMaskName = getEnumMaskName(enumName); - const defaultValue = `${enumName}::${toSafeCppString( - elementType.default, - )}`; - return `static_cast<${enumMaskName}>(${defaultValue})`; - default: - return ''; - } - } - case 'ObjectTypeAnnotation': { - return ''; - } - case 'StringEnumTypeAnnotation': - return `${getEnumName(componentName, prop.name)}::${toSafeCppString( - typeAnnotation.default, - )}`; - case 'Int32EnumTypeAnnotation': - return `${getEnumName(componentName, prop.name)}::${toIntEnumValueName( - prop.name, - typeAnnotation.default, - )}`; - default: - (typeAnnotation: empty); - throw new Error(`Unsupported type annotation: ${typeAnnotation.type}`); - } -} - -module.exports = { - convertDefaultTypeToString, - getCppTypeForAnnotation, - getEnumName, - getEnumMaskName, - getImports, - toSafeCppString, - toIntEnumValueName, - generateStructName, - generateEventStructName, -}; diff --git a/packages/react-native-codegen/src/generators/components/GenerateComponentDescriptorH.js b/packages/react-native-codegen/src/generators/components/GenerateComponentDescriptorH.js deleted file mode 100644 index a7c795622f90..000000000000 --- a/packages/react-native-codegen/src/generators/components/GenerateComponentDescriptorH.js +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type {SchemaType} from '../../CodegenSchema'; - -// File path -> contents -type FilesOutput = Map; - -const FileTemplate = ({ - componentDescriptors, - libraryName, -}: { - componentDescriptors: string, - libraryName: string, -}) => ` -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * ${'@'}generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -${componentDescriptors} - -} // namespace react -} // namespace facebook -`; - -const ComponentTemplate = ({className}: {className: string}) => - ` -using ${className}ComponentDescriptor = ConcreteComponentDescriptor<${className}ShadowNode>; -`.trim(); - -module.exports = { - generate( - libraryName: string, - schema: SchemaType, - packageName?: string, - assumeNonnull: boolean = false, - ): FilesOutput { - const fileName = 'ComponentDescriptors.h'; - - const componentDescriptors = Object.keys(schema.modules) - .map(moduleName => { - const module = schema.modules[moduleName]; - if (module.type !== 'Component') { - return; - } - - const {components} = module; - // No components in this module - if (components == null) { - return null; - } - - return Object.keys(components) - .map(componentName => { - if (components[componentName].interfaceOnly === true) { - return; - } - - return ComponentTemplate({className: componentName}); - }) - .join('\n'); - }) - .filter(Boolean) - .join('\n'); - - const replacedTemplate = FileTemplate({ - componentDescriptors, - libraryName, - }); - - return new Map([[fileName, replacedTemplate]]); - }, -}; diff --git a/packages/react-native-codegen/src/generators/components/GenerateComponentHObjCpp.js b/packages/react-native-codegen/src/generators/components/GenerateComponentHObjCpp.js deleted file mode 100644 index ee619f4617f7..000000000000 --- a/packages/react-native-codegen/src/generators/components/GenerateComponentHObjCpp.js +++ /dev/null @@ -1,418 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type { - NamedShape, - CommandTypeAnnotation, - ComponentShape, - SchemaType, - CommandParamTypeAnnotation, -} from '../../CodegenSchema'; - -type FilesOutput = Map; - -function getOrdinalNumber(num: number): string { - switch (num) { - case 1: - return '1st'; - case 2: - return '2nd'; - case 3: - return '3rd'; - } - - if (num <= 20) { - return `${num}th`; - } - - return 'unknown'; -} - -const ProtocolTemplate = ({ - componentName, - methods, -}: { - componentName: string, - methods: string, -}) => - ` -@protocol RCT${componentName}ViewProtocol -${methods} -@end -`.trim(); - -const CommandHandlerIfCaseConvertArgTemplate = ({ - componentName, - expectedKind, - argNumber, - argNumberString, - expectedKindString, - argConversion, -}: { - componentName: string, - expectedKind: string, - argNumber: number, - argNumberString: string, - expectedKindString: string, - argConversion: string, -}) => - ` - NSObject *arg${argNumber} = args[${argNumber}]; -#if RCT_DEBUG - if (!RCTValidateTypeOfViewCommandArgument(arg${argNumber}, ${expectedKind}, @"${expectedKindString}", @"${componentName}", commandName, @"${argNumberString}")) { - return; - } -#endif - ${argConversion} -`.trim(); - -const CommandHandlerIfCaseTemplate = ({ - componentName, - commandName, - numArgs, - convertArgs, - commandCall, -}: { - componentName: string, - commandName: string, - numArgs: number, - convertArgs: string, - commandCall: string, -}) => - ` -if ([commandName isEqualToString:@"${commandName}"]) { -#if RCT_DEBUG - if ([args count] != ${numArgs}) { - RCTLogError(@"%@ command %@ received %d arguments, expected %d.", @"${componentName}", commandName, (int)[args count], ${numArgs}); - return; - } -#endif - - ${convertArgs} - - ${commandCall} - return; -} -`.trim(); - -const CommandHandlerTemplate = ({ - componentName, - ifCases, -}: { - componentName: string, - ifCases: string, -}) => - ` -RCT_EXTERN inline void RCT${componentName}HandleCommand( - id componentView, - NSString const *commandName, - NSArray const *args) -{ - ${ifCases} - -#if RCT_DEBUG - RCTLogError(@"%@ received command %@, which is not a supported command.", @"${componentName}", commandName); -#endif -} -`.trim(); - -const FileTemplate = ({componentContent}: {componentContent: string}) => - ` -/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* ${'@'}generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -${componentContent} - -NS_ASSUME_NONNULL_END -`.trim(); - -type Param = NamedShape; - -function getObjCParamType(param: Param): string { - const {typeAnnotation} = param; - - switch (typeAnnotation.type) { - case 'ReservedTypeAnnotation': - switch (typeAnnotation.name) { - case 'RootTag': - return 'double'; - default: - (typeAnnotation.name: empty); - throw new Error(`Receieved invalid type: ${typeAnnotation.name}`); - } - case 'BooleanTypeAnnotation': - return 'BOOL'; - case 'DoubleTypeAnnotation': - return 'double'; - case 'FloatTypeAnnotation': - return 'float'; - case 'Int32TypeAnnotation': - return 'NSInteger'; - case 'StringTypeAnnotation': - return 'NSString *'; - default: - (typeAnnotation.type: empty); - throw new Error('Received invalid param type annotation'); - } -} - -function getObjCExpectedKindParamType(param: Param): string { - const {typeAnnotation} = param; - - switch (typeAnnotation.type) { - case 'ReservedTypeAnnotation': - switch (typeAnnotation.name) { - case 'RootTag': - return '[NSNumber class]'; - default: - (typeAnnotation.name: empty); - throw new Error(`Receieved invalid type: ${typeAnnotation.name}`); - } - case 'BooleanTypeAnnotation': - return '[NSNumber class]'; - case 'DoubleTypeAnnotation': - return '[NSNumber class]'; - case 'FloatTypeAnnotation': - return '[NSNumber class]'; - case 'Int32TypeAnnotation': - return '[NSNumber class]'; - case 'StringTypeAnnotation': - return '[NSString class]'; - default: - (typeAnnotation.type: empty); - throw new Error('Received invalid param type annotation'); - } -} - -function getReadableExpectedKindParamType(param: Param): string { - const {typeAnnotation} = param; - - switch (typeAnnotation.type) { - case 'ReservedTypeAnnotation': - switch (typeAnnotation.name) { - case 'RootTag': - return 'double'; - default: - (typeAnnotation.name: empty); - throw new Error(`Receieved invalid type: ${typeAnnotation.name}`); - } - case 'BooleanTypeAnnotation': - return 'boolean'; - case 'DoubleTypeAnnotation': - return 'double'; - case 'FloatTypeAnnotation': - return 'float'; - case 'Int32TypeAnnotation': - return 'number'; - case 'StringTypeAnnotation': - return 'string'; - default: - (typeAnnotation.type: empty); - throw new Error('Received invalid param type annotation'); - } -} - -function getObjCRightHandAssignmentParamType( - param: Param, - index: number, -): string { - const {typeAnnotation} = param; - - switch (typeAnnotation.type) { - case 'ReservedTypeAnnotation': - switch (typeAnnotation.name) { - case 'RootTag': - return `[(NSNumber *)arg${index} doubleValue]`; - default: - (typeAnnotation.name: empty); - throw new Error(`Receieved invalid type: ${typeAnnotation.name}`); - } - case 'BooleanTypeAnnotation': - return `[(NSNumber *)arg${index} boolValue]`; - case 'DoubleTypeAnnotation': - return `[(NSNumber *)arg${index} doubleValue]`; - case 'FloatTypeAnnotation': - return `[(NSNumber *)arg${index} floatValue]`; - case 'Int32TypeAnnotation': - return `[(NSNumber *)arg${index} intValue]`; - case 'StringTypeAnnotation': - return `(NSString *)arg${index}`; - default: - (typeAnnotation.type: empty); - throw new Error('Received invalid param type annotation'); - } -} - -function generateProtocol( - component: ComponentShape, - componentName: string, -): string { - const methods = component.commands - .map(command => { - const params = command.typeAnnotation.params; - const paramString = - params.length === 0 - ? '' - : params - .map((param, index) => { - const objCType = getObjCParamType(param); - - return `${index === 0 ? '' : param.name}:(${objCType})${ - param.name - }`; - }) - .join(' '); - return `- (void)${command.name}${paramString};`; - }) - .join('\n') - .trim(); - - return ProtocolTemplate({ - componentName, - methods, - }); -} - -function generateConvertAndValidateParam( - param: Param, - index: number, - componentName: string, -): string { - const leftSideType = getObjCParamType(param); - const expectedKind = getObjCExpectedKindParamType(param); - const expectedKindString = getReadableExpectedKindParamType(param); - const argConversion = `${leftSideType} ${ - param.name - } = ${getObjCRightHandAssignmentParamType(param, index)};`; - - return CommandHandlerIfCaseConvertArgTemplate({ - componentName, - argConversion, - argNumber: index, - argNumberString: getOrdinalNumber(index + 1), - expectedKind, - expectedKindString, - }); -} - -function generateCommandIfCase( - command: NamedShape, - componentName: string, -) { - const params = command.typeAnnotation.params; - - const convertArgs = params - .map((param, index) => - generateConvertAndValidateParam(param, index, componentName), - ) - .join('\n\n') - .trim(); - - const commandCallArgs = - params.length === 0 - ? '' - : params - .map((param, index) => { - return `${index === 0 ? '' : param.name}:${param.name}`; - }) - .join(' '); - const commandCall = `[componentView ${command.name}${commandCallArgs}];`; - - return CommandHandlerIfCaseTemplate({ - componentName, - commandName: command.name, - numArgs: params.length, - convertArgs, - commandCall, - }); -} - -function generateCommandHandler( - component: ComponentShape, - componentName: string, -): ?string { - if (component.commands.length === 0) { - return null; - } - - const ifCases = component.commands - .map(command => generateCommandIfCase(command, componentName)) - .join('\n\n'); - - return CommandHandlerTemplate({ - componentName, - ifCases, - }); -} - -module.exports = { - generate( - libraryName: string, - schema: SchemaType, - packageName?: string, - assumeNonnull: boolean = false, - ): FilesOutput { - const fileName = 'RCTComponentViewHelpers.h'; - - const componentContent = Object.keys(schema.modules) - .map(moduleName => { - const module = schema.modules[moduleName]; - if (module.type !== 'Component') { - return; - } - - const {components} = module; - // No components in this module - if (components == null) { - return null; - } - - return Object.keys(components) - .filter(componentName => { - const component = components[componentName]; - return !( - component.excludedPlatforms && - component.excludedPlatforms.includes('iOS') - ); - }) - .map(componentName => { - return [ - generateProtocol(components[componentName], componentName), - generateCommandHandler(components[componentName], componentName), - ] - .join('\n\n') - .trim(); - }) - .join('\n\n'); - }) - .filter(Boolean) - .join('\n\n'); - - const replacedTemplate = FileTemplate({ - componentContent, - }); - - return new Map([[fileName, replacedTemplate]]); - }, -}; diff --git a/packages/react-native-codegen/src/generators/components/GenerateEventEmitterCpp.js b/packages/react-native-codegen/src/generators/components/GenerateEventEmitterCpp.js deleted file mode 100644 index cb82e3903b06..000000000000 --- a/packages/react-native-codegen/src/generators/components/GenerateEventEmitterCpp.js +++ /dev/null @@ -1,273 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; -import type {EventTypeShape} from '../../CodegenSchema'; - -const {generateEventStructName} = require('./CppHelpers.js'); - -import type { - ComponentShape, - NamedShape, - EventTypeAnnotation, - SchemaType, -} from '../../CodegenSchema'; - -// File path -> contents -type FilesOutput = Map; - -type ComponentCollection = $ReadOnly<{ - [component: string]: ComponentShape, - ... -}>; - -const FileTemplate = ({ - events, - libraryName, -}: { - events: string, - libraryName: string, -}) => ` -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * ${'@'}generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - -${events} - -} // namespace react -} // namespace facebook -`; - -const ComponentTemplate = ({ - className, - eventName, - structName, - dispatchEventName, - implementation, -}: { - className: string, - eventName: string, - structName: string, - dispatchEventName: string, - implementation: string, -}) => - ` -void ${className}EventEmitter::${eventName}(${structName} event) const { - dispatchEvent("${dispatchEventName}", [event=std::move(event)](jsi::Runtime &runtime) { - ${implementation} - }); -} -`.trim(); - -const BasicComponentTemplate = ({ - className, - eventName, - dispatchEventName, -}: { - className: string, - eventName: string, - dispatchEventName: string, -}) => - ` -void ${className}EventEmitter::${eventName}() const { - dispatchEvent("${dispatchEventName}"); -} -`.trim(); - -function generateSetter( - variableName: string, - propertyName: string, - propertyParts: $ReadOnlyArray, -) { - const trailingPeriod = propertyParts.length === 0 ? '' : '.'; - const eventChain = `event.${propertyParts.join( - '.', - )}${trailingPeriod}${propertyName});`; - - return `${variableName}.setProperty(runtime, "${propertyName}", ${eventChain}`; -} - -function generateEnumSetter( - variableName: string, - propertyName: string, - propertyParts: $ReadOnlyArray, -) { - const trailingPeriod = propertyParts.length === 0 ? '' : '.'; - const eventChain = `event.${propertyParts.join( - '.', - )}${trailingPeriod}${propertyName})`; - - return `${variableName}.setProperty(runtime, "${propertyName}", toString(${eventChain});`; -} - -function generateSetters( - parentPropertyName: string, - properties: $ReadOnlyArray>, - propertyParts: $ReadOnlyArray, -): string { - const propSetters = properties - .map(eventProperty => { - const {typeAnnotation} = eventProperty; - switch (typeAnnotation.type) { - case 'BooleanTypeAnnotation': - return generateSetter( - parentPropertyName, - eventProperty.name, - propertyParts, - ); - case 'StringTypeAnnotation': - return generateSetter( - parentPropertyName, - eventProperty.name, - propertyParts, - ); - case 'Int32TypeAnnotation': - return generateSetter( - parentPropertyName, - eventProperty.name, - propertyParts, - ); - case 'DoubleTypeAnnotation': - return generateSetter( - parentPropertyName, - eventProperty.name, - propertyParts, - ); - case 'FloatTypeAnnotation': - return generateSetter( - parentPropertyName, - eventProperty.name, - propertyParts, - ); - case 'StringEnumTypeAnnotation': - return generateEnumSetter( - parentPropertyName, - eventProperty.name, - propertyParts, - ); - case 'ObjectTypeAnnotation': - const propertyName = eventProperty.name; - return ` - { - auto ${propertyName} = jsi::Object(runtime); - ${generateSetters( - propertyName, - typeAnnotation.properties, - propertyParts.concat([propertyName]), - )} - - ${parentPropertyName}.setProperty(runtime, "${propertyName}", ${propertyName}); - } - `.trim(); - default: - (typeAnnotation.type: empty); - throw new Error('Received invalid event property type'); - } - }) - .join('\n'); - - return propSetters; -} - -function generateEvent(componentName: string, event: EventTypeShape): string { - // This is a gross hack necessary because native code is sending - // events named things like topChange to JS which is then converted back to - // call the onChange prop. We should be consistent throughout the system. - // In order to migrate to this new system we have to support the current - // naming scheme. We should delete this once we are able to control this name - // throughout the system. - const dispatchEventName = `${event.name[2].toLowerCase()}${event.name.slice( - 3, - )}`; - - if (event.typeAnnotation.argument) { - const implementation = ` - auto payload = jsi::Object(runtime); - ${generateSetters('payload', event.typeAnnotation.argument.properties, [])} - return payload; - `.trim(); - - if (!event.name.startsWith('on')) { - throw new Error('Expected the event name to start with `on`'); - } - - return ComponentTemplate({ - className: componentName, - eventName: event.name, - dispatchEventName, - structName: generateEventStructName([event.name]), - implementation, - }); - } - - return BasicComponentTemplate({ - className: componentName, - eventName: event.name, - dispatchEventName, - }); -} - -module.exports = { - generate( - libraryName: string, - schema: SchemaType, - packageName?: string, - assumeNonnull: boolean = false, - ): FilesOutput { - const moduleComponents: ComponentCollection = Object.keys(schema.modules) - .map(moduleName => { - const module = schema.modules[moduleName]; - if (module.type !== 'Component') { - return; - } - - const {components} = module; - // No components in this module - if (components == null) { - return null; - } - - return components; - }) - .filter(Boolean) - .reduce((acc, components) => Object.assign(acc, components), {}); - - const fileName = 'EventEmitters.cpp'; - - const componentEmitters = Object.keys(moduleComponents) - .map(componentName => { - const component = moduleComponents[componentName]; - - return component.events - .map(event => { - return generateEvent(componentName, event); - }) - .join('\n'); - }) - .join('\n'); - - const replacedTemplate = FileTemplate({ - libraryName, - events: componentEmitters, - }); - - return new Map([[fileName, replacedTemplate]]); - }, -}; diff --git a/packages/react-native-codegen/src/generators/components/GenerateEventEmitterH.js b/packages/react-native-codegen/src/generators/components/GenerateEventEmitterH.js deleted file mode 100644 index f61ca1ac091a..000000000000 --- a/packages/react-native-codegen/src/generators/components/GenerateEventEmitterH.js +++ /dev/null @@ -1,315 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -const nullthrows = require('nullthrows'); - -const { - getCppTypeForAnnotation, - toSafeCppString, - generateEventStructName, -} = require('./CppHelpers'); -const {indent} = require('../Utils'); - -import type { - ComponentShape, - EventTypeShape, - NamedShape, - EventTypeAnnotation, - SchemaType, -} from '../../CodegenSchema'; - -// File path -> contents -type FilesOutput = Map; -type StructsMap = Map; - -type ComponentCollection = $ReadOnly<{ - [component: string]: ComponentShape, - ... -}>; - -const FileTemplate = ({componentEmitters}: {componentEmitters: string}) => ` -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * ${'@'}generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -${componentEmitters} - -} // namespace react -} // namespace facebook -`; - -const ComponentTemplate = ({ - className, - structs, - events, -}: { - className: string, - structs: string, - events: string, -}) => - ` -class JSI_EXPORT ${className}EventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - ${structs} - - ${events} -}; -`.trim(); - -const StructTemplate = ({ - structName, - fields, -}: { - structName: string, - fields: string, -}) => - ` - struct ${structName} { - ${fields} - }; -`.trim(); - -const EnumTemplate = ({ - enumName, - values, - toCases, -}: { - enumName: string, - values: string, - toCases: string, -}) => - `enum class ${enumName} { - ${values} -}; - -static char const *toString(const ${enumName} value) { - switch (value) { - ${toCases} - } -} -`.trim(); - -function getNativeTypeFromAnnotation( - componentName: string, - eventProperty: NamedShape, - nameParts: $ReadOnlyArray, -): string { - const {type} = eventProperty.typeAnnotation; - - switch (type) { - case 'BooleanTypeAnnotation': - case 'StringTypeAnnotation': - case 'Int32TypeAnnotation': - case 'DoubleTypeAnnotation': - case 'FloatTypeAnnotation': - return getCppTypeForAnnotation(type); - case 'StringEnumTypeAnnotation': - return generateEventStructName(nameParts.concat([eventProperty.name])); - case 'ObjectTypeAnnotation': - return generateEventStructName(nameParts.concat([eventProperty.name])); - default: - (type: empty); - throw new Error(`Received invalid event property type ${type}`); - } -} -function generateEnum( - structs: StructsMap, - options: $ReadOnlyArray, - nameParts: Array, -) { - const structName = generateEventStructName(nameParts); - const fields = options - .map((option, index) => `${toSafeCppString(option)}`) - .join(',\n '); - - const toCases = options - .map( - option => - `case ${structName}::${toSafeCppString(option)}: return "${option}";`, - ) - .join('\n' + ' '); - - structs.set( - structName, - EnumTemplate({ - enumName: structName, - values: fields, - toCases: toCases, - }), - ); -} - -function generateStruct( - structs: StructsMap, - componentName: string, - nameParts: $ReadOnlyArray, - properties: $ReadOnlyArray>, -): void { - const structNameParts = nameParts; - const structName = generateEventStructName(structNameParts); - - const fields = properties - .map(property => { - return `${getNativeTypeFromAnnotation( - componentName, - property, - structNameParts, - )} ${property.name};`; - }) - .join('\n' + ' '); - - properties.forEach(property => { - const {name, typeAnnotation} = property; - switch (typeAnnotation.type) { - case 'BooleanTypeAnnotation': - return; - case 'StringTypeAnnotation': - return; - case 'Int32TypeAnnotation': - return; - case 'DoubleTypeAnnotation': - return; - case 'FloatTypeAnnotation': - return; - case 'ObjectTypeAnnotation': - generateStruct( - structs, - componentName, - nameParts.concat([name]), - nullthrows(typeAnnotation.properties), - ); - return; - case 'StringEnumTypeAnnotation': - generateEnum(structs, typeAnnotation.options, nameParts.concat([name])); - return; - default: - (typeAnnotation.type: empty); - throw new Error( - `Received invalid event property type ${typeAnnotation.type}`, - ); - } - }); - - structs.set( - structName, - StructTemplate({ - structName, - fields, - }), - ); -} - -function generateStructs( - componentName: string, - component: ComponentShape, -): string { - const structs: StructsMap = new Map(); - - component.events.forEach(event => { - if (event.typeAnnotation.argument) { - generateStruct( - structs, - componentName, - [event.name], - event.typeAnnotation.argument.properties, - ); - } - }); - - return Array.from(structs.values()).join('\n\n'); -} - -function generateEvent(componentName: string, event: EventTypeShape): string { - if (event.typeAnnotation.argument) { - const structName = generateEventStructName([event.name]); - - return `void ${event.name}(${structName} value) const;`; - } - - return `void ${event.name}() const;`; -} -function generateEvents( - componentName: string, - component: ComponentShape, -): string { - return component.events - .map(event => generateEvent(componentName, event)) - .join('\n\n' + ' '); -} - -module.exports = { - generate( - libraryName: string, - schema: SchemaType, - packageName?: string, - assumeNonnull: boolean = false, - ): FilesOutput { - const moduleComponents: ComponentCollection = Object.keys(schema.modules) - .map(moduleName => { - const module = schema.modules[moduleName]; - if (module.type !== 'Component') { - return; - } - - const {components} = module; - // No components in this module - if (components == null) { - return null; - } - - return components; - }) - .filter(Boolean) - .reduce((acc, components) => Object.assign(acc, components), {}); - - const moduleComponentsWithEvents = Object.keys(moduleComponents); - - const fileName = 'EventEmitters.h'; - - const componentEmitters = - moduleComponentsWithEvents.length > 0 - ? Object.keys(moduleComponents) - .map(componentName => { - const component = moduleComponents[componentName]; - - const replacedTemplate = ComponentTemplate({ - className: componentName, - structs: indent(generateStructs(componentName, component), 2), - events: generateEvents(componentName, component), - }); - - return replacedTemplate; - }) - .join('\n') - : ''; - - const replacedTemplate = FileTemplate({ - componentEmitters, - }); - - return new Map([[fileName, replacedTemplate]]); - }, -}; diff --git a/packages/react-native-codegen/src/generators/components/GeneratePropsCpp.js b/packages/react-native-codegen/src/generators/components/GeneratePropsCpp.js deleted file mode 100644 index ad9d6aac61f4..000000000000 --- a/packages/react-native-codegen/src/generators/components/GeneratePropsCpp.js +++ /dev/null @@ -1,161 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type {ComponentShape, SchemaType} from '../../CodegenSchema'; -const {convertDefaultTypeToString, getImports} = require('./CppHelpers'); - -// File path -> contents -type FilesOutput = Map; - -const FileTemplate = ({ - libraryName, - imports, - componentClasses, -}: { - libraryName: string, - imports: string, - componentClasses: string, -}) => ` -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * ${'@'}generated by codegen project: GeneratePropsCpp.js - */ - -#include -${imports} - -namespace facebook { -namespace react { - -${componentClasses} - -} // namespace react -} // namespace facebook -`; - -const ComponentTemplate = ({ - className, - extendClasses, - props, -}: { - className: string, - extendClasses: string, - props: string, -}) => - ` -${className}::${className}( - const PropsParserContext &context, - const ${className} &sourceProps, - const RawProps &rawProps):${extendClasses} - - ${props} - {} -`.trim(); - -function generatePropsString(componentName: string, component: ComponentShape) { - return component.props - .map(prop => { - const defaultValue = convertDefaultTypeToString(componentName, prop); - return `${prop.name}(convertRawProp(context, rawProps, "${prop.name}", sourceProps.${prop.name}, {${defaultValue}}))`; - }) - .join(',\n' + ' '); -} - -function getClassExtendString(component: ComponentShape): string { - const extendString = - ' ' + - component.extendsProps - .map(extendProps => { - switch (extendProps.type) { - case 'ReactNativeBuiltInType': - switch (extendProps.knownTypeName) { - case 'ReactNativeCoreViewProps': - return 'ViewProps(context, sourceProps, rawProps)'; - default: - (extendProps.knownTypeName: empty); - throw new Error('Invalid knownTypeName'); - } - default: - (extendProps.type: empty); - throw new Error('Invalid extended type'); - } - }) - .join(', ') + - `${component.props.length > 0 ? ',' : ''}`; - - return extendString; -} - -module.exports = { - generate( - libraryName: string, - schema: SchemaType, - packageName?: string, - assumeNonnull: boolean = false, - ): FilesOutput { - const fileName = 'Props.cpp'; - const allImports: Set = new Set([ - '#include ', - '#include ', - ]); - - const componentProps = Object.keys(schema.modules) - .map(moduleName => { - const module = schema.modules[moduleName]; - if (module.type !== 'Component') { - return; - } - - const {components} = module; - // No components in this module - if (components == null) { - return null; - } - - return Object.keys(components) - .map(componentName => { - const component = components[componentName]; - const newName = `${componentName}Props`; - - const propsString = generatePropsString(componentName, component); - const extendString = getClassExtendString(component); - - const imports = getImports(component.props); - // $FlowFixMe[method-unbinding] added when improving typing for this parameters - imports.forEach(allImports.add, allImports); - - const replacedTemplate = ComponentTemplate({ - className: newName, - extendClasses: extendString, - props: propsString, - }); - - return replacedTemplate; - }) - .join('\n'); - }) - .filter(Boolean) - .join('\n'); - - const replacedTemplate = FileTemplate({ - componentClasses: componentProps, - libraryName, - imports: Array.from(allImports).sort().join('\n').trim(), - }); - - return new Map([[fileName, replacedTemplate]]); - }, -}; diff --git a/packages/react-native-codegen/src/generators/components/GeneratePropsH.js b/packages/react-native-codegen/src/generators/components/GeneratePropsH.js deleted file mode 100644 index 008c5d410611..000000000000 --- a/packages/react-native-codegen/src/generators/components/GeneratePropsH.js +++ /dev/null @@ -1,778 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; -import type {ComponentShape} from '../../CodegenSchema'; - -const { - getNativeTypeFromAnnotation, - getLocalImports, -} = require('./ComponentsGeneratorUtils.js'); - -const { - convertDefaultTypeToString, - getEnumMaskName, - getEnumName, - toSafeCppString, - generateStructName, - toIntEnumValueName, -} = require('./CppHelpers.js'); - -import type { - ExtendsPropsShape, - NamedShape, - PropTypeAnnotation, - SchemaType, -} from '../../CodegenSchema'; - -// File path -> contents -type FilesOutput = Map; -type StructsMap = Map; - -const FileTemplate = ({ - imports, - componentClasses, -}: { - imports: string, - componentClasses: string, -}) => ` -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * ${'@'}generated by codegen project: GeneratePropsH.js - */ -#pragma once - -${imports} - -namespace facebook { -namespace react { - -${componentClasses} - -} // namespace react -} // namespace facebook -`; - -const ClassTemplate = ({ - enums, - structs, - className, - props, - extendClasses, -}: { - enums: string, - structs: string, - className: string, - props: string, - extendClasses: string, -}) => - ` -${enums} -${structs} -class JSI_EXPORT ${className} final${extendClasses} { - public: - ${className}() = default; - ${className}(const PropsParserContext& context, const ${className} &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - ${props} -}; -`.trim(); - -const EnumTemplate = ({ - enumName, - values, - fromCases, - toCases, -}: { - enumName: string, - values: string, - fromCases: string, - toCases: string, -}) => - ` -enum class ${enumName} { ${values} }; - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ${enumName} &result) { - auto string = (std::string)value; - ${fromCases} - abort(); -} - -static inline std::string toString(const ${enumName} &value) { - switch (value) { - ${toCases} - } -} -`.trim(); - -const IntEnumTemplate = ({ - enumName, - values, - fromCases, - toCases, -}: { - enumName: string, - values: string, - fromCases: string, - toCases: string, -}) => - ` -enum class ${enumName} { ${values} }; - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ${enumName} &result) { - assert(value.hasType()); - auto integerValue = (int)value; - switch (integerValue) {${fromCases} - } - abort(); -} - -static inline std::string toString(const ${enumName} &value) { - switch (value) { - ${toCases} - } -} -`.trim(); - -const StructTemplate = ({ - structName, - fields, - fromCases, -}: { - structName: string, - fields: string, - fromCases: string, -}) => - `struct ${structName} { - ${fields} -}; - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ${structName} &result) { - auto map = (butter::map)value; - - ${fromCases} -} - -static inline std::string toString(const ${structName} &value) { - return "[Object ${structName}]"; -} -`.trim(); - -const ArrayConversionFunctionTemplate = ({ - structName, -}: { - structName: string, -}) => `static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, std::vector<${structName}> &result) { - auto items = (std::vector)value; - for (const auto &item : items) { - ${structName} newItem; - fromRawValue(context, item, newItem); - result.emplace_back(newItem); - } -} -`; - -const DoubleArrayConversionFunctionTemplate = ({ - structName, -}: { - structName: string, -}) => `static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, std::vector> &result) { - auto items = (std::vector>)value; - for (const std::vector &item : items) { - auto nestedArray = std::vector<${structName}>{}; - for (const RawValue &nestedItem : item) { - ${structName} newItem; - fromRawValue(context, nestedItem, newItem); - nestedArray.emplace_back(newItem); - } - result.emplace_back(nestedArray); - } -} -`; - -const ArrayEnumTemplate = ({ - enumName, - enumMask, - values, - fromCases, - toCases, -}: { - enumName: string, - enumMask: string, - values: string, - fromCases: string, - toCases: string, -}) => - ` -using ${enumMask} = uint32_t; - -enum class ${enumName}: ${enumMask} { - ${values} -}; - -constexpr bool operator&( - ${enumMask} const lhs, - enum ${enumName} const rhs) { - return lhs & static_cast<${enumMask}>(rhs); -} - -constexpr ${enumMask} operator|( - ${enumMask} const lhs, - enum ${enumName} const rhs) { - return lhs | static_cast<${enumMask}>(rhs); -} - -constexpr void operator|=( - ${enumMask} &lhs, - enum ${enumName} const rhs) { - lhs = lhs | static_cast<${enumMask}>(rhs); -} - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ${enumMask} &result) { - auto items = std::vector{value}; - for (const auto &item : items) { - ${fromCases} - abort(); - } -} - -static inline std::string toString(const ${enumMask} &value) { - auto result = std::string{}; - auto separator = std::string{", "}; - - ${toCases} - if (!result.empty()) { - result.erase(result.length() - separator.length()); - } - return result; -} -`.trim(); - -function getClassExtendString(component: ComponentShape): string { - if (component.extendsProps.length === 0) { - throw new Error('Invalid: component.extendsProps is empty'); - } - const extendString = - ' : ' + - component.extendsProps - .map(extendProps => { - switch (extendProps.type) { - case 'ReactNativeBuiltInType': - switch (extendProps.knownTypeName) { - case 'ReactNativeCoreViewProps': - return 'public ViewProps'; - default: - (extendProps.knownTypeName: empty); - throw new Error('Invalid knownTypeName'); - } - default: - (extendProps.type: empty); - throw new Error('Invalid extended type'); - } - }) - .join(' '); - - return extendString; -} - -function convertValueToEnumOption(value: string): string { - return toSafeCppString(value); -} - -function generateArrayEnumString( - componentName: string, - name: string, - options: $ReadOnlyArray, -): string { - const enumName = getEnumName(componentName, name); - - const values = options - .map((option, index) => `${toSafeCppString(option)} = 1 << ${index}`) - .join(',\n '); - - const fromCases = options - .map( - option => - `if (item == "${option}") { - result |= ${enumName}::${toSafeCppString(option)}; - continue; - }`, - ) - .join('\n '); - - const toCases = options - .map( - option => - `if (value & ${enumName}::${toSafeCppString(option)}) { - result += "${option}" + separator; - }`, - ) - .join('\n' + ' '); - - return ArrayEnumTemplate({ - enumName, - enumMask: getEnumMaskName(enumName), - values, - fromCases, - toCases, - }); -} - -function generateStringEnum( - componentName: string, - prop: NamedShape, -) { - const typeAnnotation = prop.typeAnnotation; - if (typeAnnotation.type === 'StringEnumTypeAnnotation') { - const values: $ReadOnlyArray = typeAnnotation.options; - const enumName = getEnumName(componentName, prop.name); - - const fromCases = values - .map( - value => - `if (string == "${value}") { result = ${enumName}::${convertValueToEnumOption( - value, - )}; return; }`, - ) - .join('\n' + ' '); - - const toCases = values - .map( - value => - `case ${enumName}::${convertValueToEnumOption( - value, - )}: return "${value}";`, - ) - .join('\n' + ' '); - - return EnumTemplate({ - enumName, - values: values.map(toSafeCppString).join(', '), - fromCases: fromCases, - toCases: toCases, - }); - } - - return ''; -} - -function generateIntEnum( - componentName: string, - prop: NamedShape, -) { - const typeAnnotation = prop.typeAnnotation; - if (typeAnnotation.type === 'Int32EnumTypeAnnotation') { - const values: $ReadOnlyArray = typeAnnotation.options; - const enumName = getEnumName(componentName, prop.name); - - const fromCases = values - .map( - value => - ` - case ${value}: - result = ${enumName}::${toIntEnumValueName(prop.name, value)}; - return;`, - ) - .join(''); - - const toCases = values - .map( - value => - `case ${enumName}::${toIntEnumValueName( - prop.name, - value, - )}: return "${value}";`, - ) - .join('\n' + ' '); - - const valueVariables = values - .map(val => `${toIntEnumValueName(prop.name, val)} = ${val}`) - .join(', '); - - return IntEnumTemplate({ - enumName, - values: valueVariables, - fromCases, - toCases, - }); - } - - return ''; -} - -function generateEnumString( - componentName: string, - component: ComponentShape, -): string { - return component.props - .map(prop => { - if ( - prop.typeAnnotation.type === 'ArrayTypeAnnotation' && - prop.typeAnnotation.elementType.type === 'StringEnumTypeAnnotation' - ) { - return generateArrayEnumString( - componentName, - prop.name, - prop.typeAnnotation.elementType.options, - ); - } - - if (prop.typeAnnotation.type === 'StringEnumTypeAnnotation') { - return generateStringEnum(componentName, prop); - } - - if (prop.typeAnnotation.type === 'Int32EnumTypeAnnotation') { - return generateIntEnum(componentName, prop); - } - - if (prop.typeAnnotation.type === 'ObjectTypeAnnotation') { - return prop.typeAnnotation.properties - .map(property => { - if (property.typeAnnotation.type === 'StringEnumTypeAnnotation') { - return generateStringEnum(componentName, property); - } else if ( - property.typeAnnotation.type === 'Int32EnumTypeAnnotation' - ) { - return generateIntEnum(componentName, property); - } - return null; - }) - .filter(Boolean) - .join('\n'); - } - }) - .filter(Boolean) - .join('\n'); -} - -function generatePropsString( - componentName: string, - props: $ReadOnlyArray>, -) { - return props - .map(prop => { - const nativeType = getNativeTypeFromAnnotation(componentName, prop, []); - const defaultValue = convertDefaultTypeToString(componentName, prop); - - return `${nativeType} ${prop.name}{${defaultValue}};`; - }) - .join('\n' + ' '); -} - -function getExtendsImports( - extendsProps: $ReadOnlyArray, -): Set { - const imports: Set = new Set(); - - imports.add('#include '); - imports.add('#include '); - - extendsProps.forEach(extendProps => { - switch (extendProps.type) { - case 'ReactNativeBuiltInType': - switch (extendProps.knownTypeName) { - case 'ReactNativeCoreViewProps': - imports.add( - '#include ', - ); - return; - default: - (extendProps.knownTypeName: empty); - throw new Error('Invalid knownTypeName'); - } - default: - (extendProps.type: empty); - throw new Error('Invalid extended type'); - } - }); - - return imports; -} - -function generateStructsForComponent( - componentName: string, - component: ComponentShape, -): string { - const structs = generateStructs(componentName, component.props, []); - const structArray = Array.from(structs.values()); - if (structArray.length < 1) { - return ''; - } - return structArray.join('\n\n'); -} - -function generateStructs( - componentName: string, - properties: $ReadOnlyArray>, - nameParts: Array, -): StructsMap { - const structs: StructsMap = new Map(); - properties.forEach(prop => { - const typeAnnotation = prop.typeAnnotation; - if (typeAnnotation.type === 'ObjectTypeAnnotation') { - // Recursively visit all of the object properties. - // Note: this is depth first so that the nested structs are ordered first. - const elementProperties = typeAnnotation.properties; - const nestedStructs = generateStructs( - componentName, - elementProperties, - nameParts.concat([prop.name]), - ); - nestedStructs.forEach(function (value, key) { - structs.set(key, value); - }); - - generateStruct( - structs, - componentName, - nameParts.concat([prop.name]), - typeAnnotation.properties, - ); - } - - if ( - prop.typeAnnotation.type === 'ArrayTypeAnnotation' && - prop.typeAnnotation.elementType.type === 'ObjectTypeAnnotation' - ) { - // Recursively visit all of the object properties. - // Note: this is depth first so that the nested structs are ordered first. - const elementProperties = prop.typeAnnotation.elementType.properties; - const nestedStructs = generateStructs( - componentName, - elementProperties, - nameParts.concat([prop.name]), - ); - nestedStructs.forEach(function (value, key) { - structs.set(key, value); - }); - - // Generate this struct and its conversion function. - generateStruct( - structs, - componentName, - nameParts.concat([prop.name]), - elementProperties, - ); - - // Generate the conversion function for std:vector. - // Note: This needs to be at the end since it references the struct above. - structs.set( - `${[componentName, ...nameParts.concat([prop.name])].join( - '', - )}ArrayStruct`, - ArrayConversionFunctionTemplate({ - structName: generateStructName( - componentName, - nameParts.concat([prop.name]), - ), - }), - ); - } - if ( - prop.typeAnnotation.type === 'ArrayTypeAnnotation' && - prop.typeAnnotation.elementType.type === 'ArrayTypeAnnotation' && - prop.typeAnnotation.elementType.elementType.type === - 'ObjectTypeAnnotation' - ) { - // Recursively visit all of the object properties. - // Note: this is depth first so that the nested structs are ordered first. - const elementProperties = - prop.typeAnnotation.elementType.elementType.properties; - const nestedStructs = generateStructs( - componentName, - elementProperties, - nameParts.concat([prop.name]), - ); - nestedStructs.forEach(function (value, key) { - structs.set(key, value); - }); - - // Generate this struct and its conversion function. - generateStruct( - structs, - componentName, - nameParts.concat([prop.name]), - elementProperties, - ); - - // Generate the conversion function for std:vector. - // Note: This needs to be at the end since it references the struct above. - structs.set( - `${[componentName, ...nameParts.concat([prop.name])].join( - '', - )}ArrayArrayStruct`, - DoubleArrayConversionFunctionTemplate({ - structName: generateStructName( - componentName, - nameParts.concat([prop.name]), - ), - }), - ); - } - }); - - return structs; -} - -function generateStruct( - structs: StructsMap, - componentName: string, - nameParts: $ReadOnlyArray, - properties: $ReadOnlyArray>, -): void { - const structNameParts = nameParts; - const structName = generateStructName(componentName, structNameParts); - - const fields = properties - .map(property => { - return `${getNativeTypeFromAnnotation( - componentName, - property, - structNameParts, - )} ${property.name};`; - }) - .join('\n' + ' '); - - properties.forEach((property: NamedShape) => { - const name = property.name; - switch (property.typeAnnotation.type) { - case 'BooleanTypeAnnotation': - return; - case 'StringTypeAnnotation': - return; - case 'Int32TypeAnnotation': - return; - case 'DoubleTypeAnnotation': - return; - case 'FloatTypeAnnotation': - return; - case 'ReservedPropTypeAnnotation': - return; - case 'ArrayTypeAnnotation': - return; - case 'StringEnumTypeAnnotation': - return; - case 'Int32EnumTypeAnnotation': - return; - case 'DoubleTypeAnnotation': - return; - case 'ObjectTypeAnnotation': - const props = property.typeAnnotation.properties; - if (props == null) { - throw new Error( - `Properties are expected for ObjectTypeAnnotation (see ${name} in ${componentName})`, - ); - } - generateStruct(structs, componentName, nameParts.concat([name]), props); - return; - default: - (property.typeAnnotation.type: empty); - throw new Error( - `Received invalid component property type ${property.typeAnnotation.type}`, - ); - } - }); - - const fromCases = properties - .map(property => { - const variable = 'tmp_' + property.name; - return `auto ${variable} = map.find("${property.name}"); - if (${variable} != map.end()) { - fromRawValue(context, ${variable}->second, result.${property.name}); - }`; - }) - .join('\n '); - - structs.set( - structName, - StructTemplate({ - structName, - fields, - fromCases, - }), - ); -} - -module.exports = { - generate( - libraryName: string, - schema: SchemaType, - packageName?: string, - assumeNonnull: boolean = false, - ): FilesOutput { - const fileName = 'Props.h'; - - const allImports: Set = new Set(); - - const componentClasses = Object.keys(schema.modules) - .map(moduleName => { - const module = schema.modules[moduleName]; - if (module.type !== 'Component') { - return; - } - - const {components} = module; - // No components in this module - if (components == null) { - return null; - } - - return Object.keys(components) - .map(componentName => { - const component = components[componentName]; - - const newName = `${componentName}Props`; - const structString = generateStructsForComponent( - componentName, - component, - ); - const enumString = generateEnumString(componentName, component); - const propsString = generatePropsString( - componentName, - component.props, - ); - const extendString = getClassExtendString(component); - const extendsImports = getExtendsImports(component.extendsProps); - const imports = getLocalImports(component.props); - - // $FlowFixMe[method-unbinding] added when improving typing for this parameters - extendsImports.forEach(allImports.add, allImports); - // $FlowFixMe[method-unbinding] added when improving typing for this parameters - imports.forEach(allImports.add, allImports); - - const replacedTemplate = ClassTemplate({ - enums: enumString, - structs: structString, - className: newName, - extendClasses: extendString, - props: propsString, - }); - - return replacedTemplate; - }) - .join('\n\n'); - }) - .filter(Boolean) - .join('\n\n'); - - const replacedTemplate = FileTemplate({ - componentClasses, - imports: Array.from(allImports).sort().join('\n'), - }); - - return new Map([[fileName, replacedTemplate]]); - }, -}; diff --git a/packages/react-native-codegen/src/generators/components/GeneratePropsJavaDelegate.js b/packages/react-native-codegen/src/generators/components/GeneratePropsJavaDelegate.js deleted file mode 100644 index a75042292076..000000000000 --- a/packages/react-native-codegen/src/generators/components/GeneratePropsJavaDelegate.js +++ /dev/null @@ -1,348 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; -import type {CommandParamTypeAnnotation} from '../../CodegenSchema'; - -import type { - NamedShape, - CommandTypeAnnotation, - ComponentShape, - PropTypeAnnotation, - SchemaType, -} from '../../CodegenSchema'; -const { - getImports, - toSafeJavaString, - getInterfaceJavaClassName, - getDelegateJavaClassName, -} = require('./JavaHelpers'); - -// File path -> contents -type FilesOutput = Map; - -const FileTemplate = ({ - packageName, - imports, - className, - extendClasses, - interfaceClassName, - methods, -}: { - packageName: string, - imports: string, - className: string, - extendClasses: string, - interfaceClassName: string, - methods: string, -}) => `/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* ${'@'}generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package ${packageName}; - -${imports} - -public class ${className} & ${interfaceClassName}> extends BaseViewManagerDelegate { - public ${className}(U viewManager) { - super(viewManager); - } - ${methods} -} -`; - -const PropSetterTemplate = ({propCases}: {propCases: string}) => - ` - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - ${propCases} - } -`.trim(); - -const CommandsTemplate = ({commandCases}: {commandCases: string}) => - ` - @Override - public void receiveCommand(T view, String commandName, ReadableArray args) { - switch (commandName) { - ${commandCases} - } - } -`.trim(); - -function getJavaValueForProp( - prop: NamedShape, - componentName: string, -): string { - const typeAnnotation = prop.typeAnnotation; - - switch (typeAnnotation.type) { - case 'BooleanTypeAnnotation': - if (typeAnnotation.default === null) { - return 'value == null ? null : (Boolean) value'; - } else { - return `value == null ? ${typeAnnotation.default.toString()} : (boolean) value`; - } - case 'StringTypeAnnotation': - const defaultValueString = - typeAnnotation.default === null - ? 'null' - : `"${typeAnnotation.default}"`; - return `value == null ? ${defaultValueString} : (String) value`; - case 'Int32TypeAnnotation': - return `value == null ? ${typeAnnotation.default} : ((Double) value).intValue()`; - case 'DoubleTypeAnnotation': - if (prop.optional) { - return `value == null ? ${typeAnnotation.default}f : ((Double) value).doubleValue()`; - } else { - return 'value == null ? Double.NaN : ((Double) value).doubleValue()'; - } - case 'FloatTypeAnnotation': - if (typeAnnotation.default === null) { - return 'value == null ? null : ((Double) value).floatValue()'; - } else if (prop.optional) { - return `value == null ? ${typeAnnotation.default}f : ((Double) value).floatValue()`; - } else { - return 'value == null ? Float.NaN : ((Double) value).floatValue()'; - } - case 'ReservedPropTypeAnnotation': - switch (typeAnnotation.name) { - case 'ColorPrimitive': - return 'ColorPropConverter.getColor(value, view.getContext())'; - case 'ImageSourcePrimitive': - return '(ReadableMap) value'; - case 'ImageRequestPrimitive': - return '(ReadableMap) value'; - case 'PointPrimitive': - return '(ReadableMap) value'; - case 'EdgeInsetsPrimitive': - return '(ReadableMap) value'; - default: - (typeAnnotation.name: empty); - throw new Error('Received unknown ReservedPropTypeAnnotation'); - } - case 'ArrayTypeAnnotation': { - return '(ReadableArray) value'; - } - case 'ObjectTypeAnnotation': { - return '(ReadableMap) value'; - } - case 'StringEnumTypeAnnotation': - return '(String) value'; - case 'Int32EnumTypeAnnotation': - return `value == null ? ${typeAnnotation.default} : ((Double) value).intValue()`; - default: - (typeAnnotation: empty); - throw new Error('Received invalid typeAnnotation'); - } -} - -function generatePropCasesString( - component: ComponentShape, - componentName: string, -) { - if (component.props.length === 0) { - return 'super.setProperty(view, propName, value);'; - } - - const cases = component.props - .map(prop => { - return `case "${prop.name}": - mViewManager.set${toSafeJavaString( - prop.name, - )}(view, ${getJavaValueForProp(prop, componentName)}); - break;`; - }) - .join('\n' + ' '); - - return `switch (propName) { - ${cases} - default: - super.setProperty(view, propName, value); - }`; -} - -function getCommandArgJavaType( - param: NamedShape, - index: number, -) { - const {typeAnnotation} = param; - - switch (typeAnnotation.type) { - case 'ReservedTypeAnnotation': - switch (typeAnnotation.name) { - case 'RootTag': - return `args.getDouble(${index})`; - default: - (typeAnnotation.name: empty); - throw new Error(`Receieved invalid type: ${typeAnnotation.name}`); - } - case 'BooleanTypeAnnotation': - return `args.getBoolean(${index})`; - case 'DoubleTypeAnnotation': - return `args.getDouble(${index})`; - case 'FloatTypeAnnotation': - return `(float) args.getDouble(${index})`; - case 'Int32TypeAnnotation': - return `args.getInt(${index})`; - case 'StringTypeAnnotation': - return `args.getString(${index})`; - default: - (typeAnnotation.type: empty); - throw new Error(`Receieved invalid type: ${typeAnnotation.type}`); - } -} - -function getCommandArguments( - command: NamedShape, -): string { - return [ - 'view', - ...command.typeAnnotation.params.map(getCommandArgJavaType), - ].join(', '); -} - -function generateCommandCasesString( - component: ComponentShape, - componentName: string, -) { - if (component.commands.length === 0) { - return null; - } - - const commandMethods = component.commands - .map(command => { - return `case "${command.name}": - mViewManager.${toSafeJavaString( - command.name, - false, - )}(${getCommandArguments(command)}); - break;`; - }) - .join('\n' + ' '); - - return commandMethods; -} - -function getClassExtendString(component: ComponentShape): string { - const extendString = component.extendsProps - .map(extendProps => { - switch (extendProps.type) { - case 'ReactNativeBuiltInType': - switch (extendProps.knownTypeName) { - case 'ReactNativeCoreViewProps': - return 'View'; - default: - (extendProps.knownTypeName: empty); - throw new Error('Invalid knownTypeName'); - } - default: - (extendProps.type: empty); - throw new Error('Invalid extended type'); - } - }) - .join(''); - - return extendString; -} - -function getDelegateImports(component: ComponentShape) { - const imports = getImports(component, 'delegate'); - // The delegate needs ReadableArray for commands always. - // The interface doesn't always need it - if (component.commands.length > 0) { - imports.add('import com.facebook.react.bridge.ReadableArray;'); - } - imports.add('import androidx.annotation.Nullable;'); - imports.add('import com.facebook.react.uimanager.BaseViewManagerDelegate;'); - imports.add('import com.facebook.react.uimanager.BaseViewManagerInterface;'); - - return imports; -} - -function generateMethods( - propsString: string, - commandsString: null | string, -): string { - return [ - PropSetterTemplate({propCases: propsString}), - commandsString != null - ? CommandsTemplate({commandCases: commandsString}) - : '', - ] - .join('\n\n ') - .trimRight(); -} - -module.exports = { - generate( - libraryName: string, - schema: SchemaType, - packageName?: string, - assumeNonnull: boolean = false, - ): FilesOutput { - // TODO: This doesn't support custom package name yet. - const normalizedPackageName = 'com.facebook.react.viewmanagers'; - const outputDir = `java/${normalizedPackageName.replace(/\./g, '/')}`; - - const files = new Map(); - Object.keys(schema.modules).forEach(moduleName => { - const module = schema.modules[moduleName]; - if (module.type !== 'Component') { - return; - } - - const {components} = module; - // No components in this module - if (components == null) { - return; - } - - return Object.keys(components) - .filter(componentName => { - const component = components[componentName]; - return !( - component.excludedPlatforms && - component.excludedPlatforms.includes('android') - ); - }) - .forEach(componentName => { - const component = components[componentName]; - const className = getDelegateJavaClassName(componentName); - const interfaceClassName = getInterfaceJavaClassName(componentName); - - const imports = getDelegateImports(component); - const propsString = generatePropCasesString(component, componentName); - const commandsString = generateCommandCasesString( - component, - componentName, - ); - const extendString = getClassExtendString(component); - - const replacedTemplate = FileTemplate({ - imports: Array.from(imports).sort().join('\n'), - packageName: normalizedPackageName, - className, - extendClasses: extendString, - methods: generateMethods(propsString, commandsString), - interfaceClassName: interfaceClassName, - }); - - files.set(`${outputDir}/${className}.java`, replacedTemplate); - }); - }); - - return files; - }, -}; diff --git a/packages/react-native-codegen/src/generators/components/GeneratePropsJavaInterface.js b/packages/react-native-codegen/src/generators/components/GeneratePropsJavaInterface.js deleted file mode 100644 index d373e1712244..000000000000 --- a/packages/react-native-codegen/src/generators/components/GeneratePropsJavaInterface.js +++ /dev/null @@ -1,288 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; -import type {CommandParamTypeAnnotation} from '../../CodegenSchema'; - -import type { - NamedShape, - CommandTypeAnnotation, - ComponentShape, - PropTypeAnnotation, - SchemaType, -} from '../../CodegenSchema'; -const { - getImports, - toSafeJavaString, - getInterfaceJavaClassName, -} = require('./JavaHelpers'); - -// File path -> contents -type FilesOutput = Map; - -const FileTemplate = ({ - packageName, - imports, - className, - extendClasses, - methods, -}: { - packageName: string, - imports: string, - className: string, - extendClasses: string, - methods: string, -}) => `/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* ${'@'}generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package ${packageName}; - -${imports} - -public interface ${className} { - ${methods} -} -`; - -function addNullable(imports: Set) { - imports.add('import androidx.annotation.Nullable;'); -} - -function getJavaValueForProp( - prop: NamedShape, - imports: Set, -): string { - const typeAnnotation = prop.typeAnnotation; - - switch (typeAnnotation.type) { - case 'BooleanTypeAnnotation': - if (typeAnnotation.default === null) { - addNullable(imports); - return '@Nullable Boolean value'; - } else { - return 'boolean value'; - } - case 'StringTypeAnnotation': - addNullable(imports); - return '@Nullable String value'; - case 'Int32TypeAnnotation': - return 'int value'; - case 'DoubleTypeAnnotation': - return 'double value'; - case 'FloatTypeAnnotation': - if (typeAnnotation.default === null) { - addNullable(imports); - return '@Nullable Float value'; - } else { - return 'float value'; - } - case 'ReservedPropTypeAnnotation': - switch (typeAnnotation.name) { - case 'ColorPrimitive': - addNullable(imports); - return '@Nullable Integer value'; - case 'ImageSourcePrimitive': - addNullable(imports); - return '@Nullable ReadableMap value'; - case 'ImageRequestPrimitive': - addNullable(imports); - return '@Nullable ReadableMap value'; - case 'PointPrimitive': - addNullable(imports); - return '@Nullable ReadableMap value'; - case 'EdgeInsetsPrimitive': - addNullable(imports); - return '@Nullable ReadableMap value'; - default: - (typeAnnotation.name: empty); - throw new Error('Received unknown ReservedPropTypeAnnotation'); - } - case 'ArrayTypeAnnotation': { - addNullable(imports); - return '@Nullable ReadableArray value'; - } - case 'ObjectTypeAnnotation': { - addNullable(imports); - return '@Nullable ReadableMap value'; - } - case 'StringEnumTypeAnnotation': - addNullable(imports); - return '@Nullable String value'; - case 'Int32EnumTypeAnnotation': - addNullable(imports); - return '@Nullable Integer value'; - default: - (typeAnnotation: empty); - throw new Error('Received invalid typeAnnotation'); - } -} - -function generatePropsString(component: ComponentShape, imports: Set) { - if (component.props.length === 0) { - return '// No props'; - } - - return component.props - .map(prop => { - return `void set${toSafeJavaString( - prop.name, - )}(T view, ${getJavaValueForProp(prop, imports)});`; - }) - .join('\n' + ' '); -} - -function getCommandArgJavaType(param: NamedShape) { - const {typeAnnotation} = param; - - switch (typeAnnotation.type) { - case 'ReservedTypeAnnotation': - switch (typeAnnotation.name) { - case 'RootTag': - return 'double'; - default: - (typeAnnotation.name: empty); - throw new Error(`Receieved invalid type: ${typeAnnotation.name}`); - } - case 'BooleanTypeAnnotation': - return 'boolean'; - case 'DoubleTypeAnnotation': - return 'double'; - case 'FloatTypeAnnotation': - return 'float'; - case 'Int32TypeAnnotation': - return 'int'; - case 'StringTypeAnnotation': - return 'String'; - default: - (typeAnnotation.type: empty); - throw new Error('Receieved invalid typeAnnotation'); - } -} - -function getCommandArguments( - command: NamedShape, - componentName: string, -): string { - return [ - 'T view', - ...command.typeAnnotation.params.map(param => { - const commandArgJavaType = getCommandArgJavaType(param); - - return `${commandArgJavaType} ${param.name}`; - }), - ].join(', '); -} - -function generateCommandsString( - component: ComponentShape, - componentName: string, -) { - return component.commands - .map(command => { - const safeJavaName = toSafeJavaString(command.name, false); - - return `void ${safeJavaName}(${getCommandArguments( - command, - componentName, - )});`; - }) - .join('\n' + ' '); -} - -function getClassExtendString(component: ComponentShape): string { - const extendString = component.extendsProps - .map(extendProps => { - switch (extendProps.type) { - case 'ReactNativeBuiltInType': - switch (extendProps.knownTypeName) { - case 'ReactNativeCoreViewProps': - return 'View'; - default: - (extendProps.knownTypeName: empty); - throw new Error('Invalid knownTypeName'); - } - default: - (extendProps.type: empty); - throw new Error('Invalid extended type'); - } - }) - .join(''); - - return extendString; -} - -module.exports = { - generate( - libraryName: string, - schema: SchemaType, - packageName?: string, - assumeNonnull: boolean = false, - ): FilesOutput { - // TODO: This doesn't support custom package name yet. - const normalizedPackageName = 'com.facebook.react.viewmanagers'; - const outputDir = `java/${normalizedPackageName.replace(/\./g, '/')}`; - - const files = new Map(); - Object.keys(schema.modules).forEach(moduleName => { - const module = schema.modules[moduleName]; - if (module.type !== 'Component') { - return; - } - - const {components} = module; - - // No components in this module - if (components == null) { - return; - } - - return Object.keys(components) - .filter(componentName => { - const component = components[componentName]; - return !( - component.excludedPlatforms && - component.excludedPlatforms.includes('android') - ); - }) - .forEach(componentName => { - const component = components[componentName]; - const className = getInterfaceJavaClassName(componentName); - - const imports = getImports(component, 'interface'); - const propsString = generatePropsString(component, imports); - const commandsString = generateCommandsString( - component, - componentName, - ); - const extendString = getClassExtendString(component); - - const replacedTemplate = FileTemplate({ - imports: Array.from(imports).sort().join('\n'), - packageName: normalizedPackageName, - className, - extendClasses: extendString, - methods: [propsString, commandsString] - .join('\n' + ' ') - .trimRight(), - }); - - files.set(`${outputDir}/${className}.java`, replacedTemplate); - }); - }); - - return files; - }, -}; diff --git a/packages/react-native-codegen/src/generators/components/GeneratePropsJavaPojo/PojoCollector.js b/packages/react-native-codegen/src/generators/components/GeneratePropsJavaPojo/PojoCollector.js deleted file mode 100644 index eb7b1091dc77..000000000000 --- a/packages/react-native-codegen/src/generators/components/GeneratePropsJavaPojo/PojoCollector.js +++ /dev/null @@ -1,187 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type { - ReservedPropTypeAnnotation, - NamedShape, - ObjectTypeAnnotation, - BooleanTypeAnnotation, - StringTypeAnnotation, - DoubleTypeAnnotation, - FloatTypeAnnotation, - Int32TypeAnnotation, - PropTypeAnnotation, -} from '../../../CodegenSchema'; - -const {capitalize} = require('../../Utils'); - -export type Pojo = { - name: string, - namespace: string, - properties: $ReadOnlyArray, -}; - -export type PojoProperty = NamedShape; - -export type PojoTypeAliasAnnotation = { - type: 'PojoTypeAliasTypeAnnotation', - name: string, -}; - -export type PojoTypeAnnotation = - | $ReadOnly<{ - type: 'BooleanTypeAnnotation', - default: boolean | null, - }> - | $ReadOnly<{ - type: 'StringTypeAnnotation', - default: string | null, - }> - | $ReadOnly<{ - type: 'DoubleTypeAnnotation', - default: number, - }> - | $ReadOnly<{ - type: 'FloatTypeAnnotation', - default: number | null, - }> - | $ReadOnly<{ - type: 'Int32TypeAnnotation', - default: number, - }> - | $ReadOnly<{ - type: 'StringEnumTypeAnnotation', - default: string, - options: $ReadOnlyArray, - }> - | $ReadOnly<{ - type: 'Int32EnumTypeAnnotation', - default: number, - options: $ReadOnlyArray, - }> - | ReservedPropTypeAnnotation - | PojoTypeAliasAnnotation - | $ReadOnly<{ - type: 'ArrayTypeAnnotation', - elementType: - | BooleanTypeAnnotation - | StringTypeAnnotation - | DoubleTypeAnnotation - | FloatTypeAnnotation - | Int32TypeAnnotation - | $ReadOnly<{ - type: 'StringEnumTypeAnnotation', - default: string, - options: $ReadOnlyArray, - }> - | PojoTypeAliasAnnotation - | ReservedPropTypeAnnotation - | $ReadOnly<{ - type: 'ArrayTypeAnnotation', - elementType: PojoTypeAliasAnnotation, - }>, - }>; - -class PojoCollector { - _pojos: Map = new Map(); - process( - namespace: string, - pojoName: string, - typeAnnotation: PropTypeAnnotation, - ): PojoTypeAnnotation { - switch (typeAnnotation.type) { - case 'ObjectTypeAnnotation': { - this._insertPojo(namespace, pojoName, typeAnnotation); - return { - type: 'PojoTypeAliasTypeAnnotation', - name: pojoName, - }; - } - case 'ArrayTypeAnnotation': { - const arrayTypeAnnotation = typeAnnotation; - // TODO: Flow assumes elementType can be any. Fix this. - const elementType: $PropertyType< - typeof arrayTypeAnnotation, - 'elementType', - > = arrayTypeAnnotation.elementType; - - const pojoElementType = (() => { - switch (elementType.type) { - case 'ObjectTypeAnnotation': { - this._insertPojo(namespace, `${pojoName}Element`, elementType); - return { - type: 'PojoTypeAliasTypeAnnotation', - name: `${pojoName}Element`, - }; - } - case 'ArrayTypeAnnotation': { - const {elementType: objectTypeAnnotation} = elementType; - this._insertPojo( - namespace, - `${pojoName}ElementElement`, - objectTypeAnnotation, - ); - return { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'PojoTypeAliasTypeAnnotation', - name: `${pojoName}ElementElement`, - }, - }; - } - default: { - return elementType; - } - } - })(); - - return { - type: 'ArrayTypeAnnotation', - elementType: pojoElementType, - }; - } - default: - return typeAnnotation; - } - } - - _insertPojo( - namespace: string, - pojoName: string, - objectTypeAnnotation: ObjectTypeAnnotation, - ) { - const properties = objectTypeAnnotation.properties.map(property => { - const propertyPojoName = pojoName + capitalize(property.name); - - return { - ...property, - typeAnnotation: this.process( - namespace, - propertyPojoName, - property.typeAnnotation, - ), - }; - }); - - this._pojos.set(pojoName, { - name: pojoName, - namespace, - properties, - }); - } - - getAllPojos(): $ReadOnlyArray { - return [...this._pojos.values()]; - } -} - -module.exports = PojoCollector; diff --git a/packages/react-native-codegen/src/generators/components/GeneratePropsJavaPojo/index.js b/packages/react-native-codegen/src/generators/components/GeneratePropsJavaPojo/index.js deleted file mode 100644 index 66b11f26c8c3..000000000000 --- a/packages/react-native-codegen/src/generators/components/GeneratePropsJavaPojo/index.js +++ /dev/null @@ -1,80 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type {SchemaType} from '../../../CodegenSchema'; - -const PojoCollector = require('./PojoCollector'); -const {capitalize} = require('../../Utils'); -const {serializePojo} = require('./serializePojo'); - -type FilesOutput = Map; - -module.exports = { - generate( - libraryName: string, - schema: SchemaType, - packageName?: string, - ): FilesOutput { - const pojoCollector = new PojoCollector(); - const basePackageName = 'com.facebook.react.viewmanagers'; - - Object.keys(schema.modules).forEach(hasteModuleName => { - const module = schema.modules[hasteModuleName]; - if (module.type !== 'Component') { - return; - } - - const {components} = module; - // No components in this module - if (components == null) { - return null; - } - - Object.keys(components) - .filter(componentName => { - const component = components[componentName]; - return !( - component.excludedPlatforms && - component.excludedPlatforms.includes('android') - ); - }) - .forEach(componentName => { - const component = components[componentName]; - if (component == null) { - return; - } - - const {props} = component; - - pojoCollector.process( - capitalize(hasteModuleName), - `${capitalize(componentName)}Props`, - { - type: 'ObjectTypeAnnotation', - properties: props, - }, - ); - }); - }); - - const pojoDir = basePackageName.split('.').join('/'); - - return new Map( - pojoCollector.getAllPojos().map(pojo => { - return [ - `java/${pojoDir}/${pojo.namespace}/${pojo.name}.java`, - serializePojo(pojo, basePackageName), - ]; - }), - ); - }, -}; diff --git a/packages/react-native-codegen/src/generators/components/GeneratePropsJavaPojo/serializePojo.js b/packages/react-native-codegen/src/generators/components/GeneratePropsJavaPojo/serializePojo.js deleted file mode 100644 index c2c36c1ff610..000000000000 --- a/packages/react-native-codegen/src/generators/components/GeneratePropsJavaPojo/serializePojo.js +++ /dev/null @@ -1,296 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type {Pojo, PojoProperty, PojoTypeAnnotation} from './PojoCollector'; -const {capitalize} = require('../../Utils'); - -type ImportCollector = ($import: string) => void; - -function toJavaType( - typeAnnotation: PojoTypeAnnotation, - addImport: ImportCollector, -): string { - const importNullable = () => addImport('androidx.annotation.Nullable'); - const importReadableMap = () => - addImport('com.facebook.react.bridge.ReadableMap'); - const importArrayList = () => addImport('java.util.ArrayList'); - switch (typeAnnotation.type) { - /** - * Primitives - */ - case 'BooleanTypeAnnotation': { - if (typeAnnotation.default === null) { - importNullable(); - return '@Nullable Boolean'; - } else { - return 'boolean'; - } - } - case 'StringTypeAnnotation': { - importNullable(); - return '@Nullable String'; - } - case 'DoubleTypeAnnotation': { - return 'double'; - } - case 'FloatTypeAnnotation': { - if (typeAnnotation.default === null) { - importNullable(); - return '@Nullable Float'; - } else { - return 'float'; - } - } - case 'Int32TypeAnnotation': { - return 'int'; - } - - /** - * Enums - */ - // TODO: Make StringEnumTypeAnnotation type-safe? - case 'StringEnumTypeAnnotation': - importNullable(); - return '@Nullable String'; - // TODO: Make Int32EnumTypeAnnotation type-safe? - case 'Int32EnumTypeAnnotation': - importNullable(); - return '@Nullable Integer'; - - /** - * Reserved types - */ - case 'ReservedPropTypeAnnotation': { - switch (typeAnnotation.name) { - case 'ColorPrimitive': - importNullable(); - return '@Nullable Integer'; - - // TODO: Make ImageSourcePrimitive type-safe - case 'ImageSourcePrimitive': - importNullable(); - importReadableMap(); - return '@Nullable ReadableMap'; - - // TODO: Make ImageRequestPrimitive type-safe - case 'ImageRequestPrimitive': - importNullable(); - importReadableMap(); - return '@Nullable ReadableMap'; - - // TODO: Make PointPrimitive type-safe - case 'PointPrimitive': - importNullable(); - importReadableMap(); - return '@Nullable ReadableMap'; - - // TODO: Make EdgeInsetsPrimitive type-safe - case 'EdgeInsetsPrimitive': - importNullable(); - importReadableMap(); - return '@Nullable ReadableMap'; - default: - (typeAnnotation.name: empty); - throw new Error( - `Received unknown ReservedPropTypeAnnotation ${typeAnnotation.name}`, - ); - } - } - - /** - * Other Pojo objects - */ - case 'PojoTypeAliasTypeAnnotation': { - return typeAnnotation.name; - } - - /** - * Arrays - */ - case 'ArrayTypeAnnotation': { - const {elementType} = typeAnnotation; - - const elementTypeString = (() => { - switch (elementType.type) { - /** - * Primitives - */ - case 'BooleanTypeAnnotation': { - return 'Boolean'; - } - case 'StringTypeAnnotation': { - return 'String'; - } - case 'DoubleTypeAnnotation': { - return 'Double'; - } - case 'FloatTypeAnnotation': { - return 'Float'; - } - case 'Int32TypeAnnotation': { - return 'Integer'; - } - - /** - * Enums - */ - // TODO: Make StringEnums type-safe in Pojos - case 'StringEnumTypeAnnotation': { - return 'String'; - } - - /** - * Other Pojo objects - */ - case 'PojoTypeAliasTypeAnnotation': { - return elementType.name; - } - - /** - * Reserved types - */ - case 'ReservedPropTypeAnnotation': { - switch (elementType.name) { - case 'ColorPrimitive': - return 'Integer'; - - // TODO: Make ImageSourcePrimitive type-safe - case 'ImageSourcePrimitive': - importReadableMap(); - return 'ReadableMap'; - - // TODO: Make ImageRequestPrimitive type-safe - case 'ImageRequestPrimitive': - importReadableMap(); - return 'ReadableMap'; - - // TODO: Make PointPrimitive type-safe - case 'PointPrimitive': - importReadableMap(); - return 'ReadableMap'; - - // TODO: Make EdgeInsetsPrimitive type-safe - case 'EdgeInsetsPrimitive': - importReadableMap(); - return 'ReadableMap'; - default: - (elementType.name: empty); - throw new Error( - `Received unknown ReservedPropTypeAnnotation ${elementType.name}`, - ); - } - } - - // Arrays - case 'ArrayTypeAnnotation': { - const {elementType: pojoTypeAliasTypeAnnotation} = elementType; - - importArrayList(); - return `ArrayList<${pojoTypeAliasTypeAnnotation.name}>`; - } - default: { - (elementType.type: empty); - throw new Error( - `Unrecognized PojoTypeAnnotation Array element type annotation '${typeAnnotation.type}'`, - ); - } - } - })(); - - importArrayList(); - return `ArrayList<${elementTypeString}>`; - } - - default: { - (typeAnnotation.type: empty); - throw new Error( - `Unrecognized PojoTypeAnnotation '${typeAnnotation.type}'`, - ); - } - } -} - -function toJavaMemberName(property: PojoProperty): string { - return `m${capitalize(property.name)}`; -} - -function toJavaMemberDeclaration( - property: PojoProperty, - addImport: ImportCollector, -): string { - const type = toJavaType(property.typeAnnotation, addImport); - const memberName = toJavaMemberName(property); - return `private ${type} ${memberName};`; -} - -function toJavaGetter(property: PojoProperty, addImport: ImportCollector) { - const type = toJavaType(property.typeAnnotation, addImport); - const getterName = `get${capitalize(property.name)}`; - const memberName = toJavaMemberName(property); - - addImport('com.facebook.proguard.annotations.DoNotStrip'); - return `@DoNotStrip -public ${type} ${getterName}() { - return ${memberName}; -}`; -} - -function serializePojo(pojo: Pojo, basePackageName: string): string { - const importSet: Set = new Set(); - const addImport = ($import: string) => { - importSet.add($import); - }; - - addImport('com.facebook.proguard.annotations.DoNotStrip'); - - const indent = ' '.repeat(2); - - const members = pojo.properties - .map(property => toJavaMemberDeclaration(property, addImport)) - .map(member => `${indent}${member}`) - .join('\n'); - - const getters = pojo.properties - .map(property => toJavaGetter(property, addImport)) - .map(getter => - getter - .split('\n') - .map(line => `${indent}${line}`) - .join('\n'), - ) - .join('\n'); - - const imports = [...importSet] - .map($import => `import ${$import};`) - .sort() - .join('\n'); - - return `/** -* 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. -* -* ${'@'}generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package ${basePackageName}.${pojo.namespace}; -${imports === '' ? '' : `\n${imports}\n`} -@DoNotStrip -public class ${pojo.name} { -${members} -${getters} -} -`; -} - -module.exports = {serializePojo}; diff --git a/packages/react-native-codegen/src/generators/components/GenerateShadowNodeCpp.js b/packages/react-native-codegen/src/generators/components/GenerateShadowNodeCpp.js deleted file mode 100644 index 82cb8ffd5ab5..000000000000 --- a/packages/react-native-codegen/src/generators/components/GenerateShadowNodeCpp.js +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type {SchemaType} from '../../CodegenSchema'; - -// File path -> contents -type FilesOutput = Map; - -const FileTemplate = ({ - libraryName, - componentNames, -}: { - libraryName: string, - componentNames: string, -}) => ` -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * ${'@'}generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -${componentNames} - -} // namespace react -} // namespace facebook -`; - -const ComponentTemplate = ({className}: {className: string}) => - ` -extern const char ${className}ComponentName[] = "${className}"; -`.trim(); - -module.exports = { - generate( - libraryName: string, - schema: SchemaType, - packageName?: string, - assumeNonnull: boolean = false, - ): FilesOutput { - const fileName = 'ShadowNodes.cpp'; - - const componentNames = Object.keys(schema.modules) - .map(moduleName => { - const module = schema.modules[moduleName]; - if (module.type !== 'Component') { - return; - } - - const {components} = module; - // No components in this module - if (components == null) { - return null; - } - - return Object.keys(components) - .map(componentName => { - if (components[componentName].interfaceOnly === true) { - return; - } - const replacedTemplate = ComponentTemplate({ - className: componentName, - }); - - return replacedTemplate; - }) - .join('\n'); - }) - .filter(Boolean) - .join('\n'); - - const replacedTemplate = FileTemplate({ - componentNames, - libraryName, - }); - - return new Map([[fileName, replacedTemplate]]); - }, -}; diff --git a/packages/react-native-codegen/src/generators/components/GenerateShadowNodeH.js b/packages/react-native-codegen/src/generators/components/GenerateShadowNodeH.js deleted file mode 100644 index 3e7cf71117ef..000000000000 --- a/packages/react-native-codegen/src/generators/components/GenerateShadowNodeH.js +++ /dev/null @@ -1,124 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type {SchemaType} from '../../CodegenSchema'; - -// File path -> contents -type FilesOutput = Map; - -const FileTemplate = ({ - imports, - libraryName, - componentClasses, -}: { - imports: string, - libraryName: string, - componentClasses: string, -}) => ` -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * ${'@'}generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -${imports}#include -#include -#include -#include - -namespace facebook { -namespace react { - -${componentClasses} - -} // namespace react -} // namespace facebook -`; - -const ComponentTemplate = ({ - className, - eventEmitter, -}: { - className: string, - eventEmitter: string, -}) => - ` -JSI_EXPORT extern const char ${className}ComponentName[]; - -/* - * \`ShadowNode\` for <${className}> component. - */ -using ${className}ShadowNode = ConcreteViewShadowNode< - ${className}ComponentName, - ${className}Props${eventEmitter}, - ${className}State>; -`.trim(); - -module.exports = { - generate( - libraryName: string, - schema: SchemaType, - packageName?: string, - assumeNonnull: boolean = false, - ): FilesOutput { - const fileName = 'ShadowNodes.h'; - - const moduleResults = Object.keys(schema.modules) - .map(moduleName => { - const module = schema.modules[moduleName]; - if (module.type !== 'Component') { - return; - } - - const {components} = module; - // No components in this module - if (components == null) { - return null; - } - - return Object.keys(components) - .map(componentName => { - const component = components[componentName]; - if (component.interfaceOnly === true) { - return; - } - - const eventEmitter = `,\n ${componentName}EventEmitter`; - - const replacedTemplate = ComponentTemplate({ - className: componentName, - eventEmitter, - }); - - return replacedTemplate; - }) - .join('\n\n'); - }) - .filter(Boolean) - .join('\n\n'); - - const eventEmitterImport = `#include \n`; - - const replacedTemplate = FileTemplate({ - componentClasses: moduleResults, - libraryName, - imports: eventEmitterImport, - }); - - return new Map([[fileName, replacedTemplate]]); - }, -}; diff --git a/packages/react-native-codegen/src/generators/components/GenerateStateCpp.js b/packages/react-native-codegen/src/generators/components/GenerateStateCpp.js deleted file mode 100644 index 36c843398192..000000000000 --- a/packages/react-native-codegen/src/generators/components/GenerateStateCpp.js +++ /dev/null @@ -1,92 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type {SchemaType} from '../../CodegenSchema'; - -// File path -> contents -type FilesOutput = Map; - -const FileTemplate = ({ - libraryName, - stateClasses, -}: { - libraryName: string, - stateClasses: string, -}) => ` -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * ${'@'}generated by codegen project: GenerateStateCpp.js - */ -#include - -namespace facebook { -namespace react { - -${stateClasses} - -} // namespace react -} // namespace facebook -`; - -const StateTemplate = ({stateName}: {stateName: string}) => ''; - -module.exports = { - generate( - libraryName: string, - schema: SchemaType, - packageName?: string, - assumeNonnull: boolean = false, - ): FilesOutput { - const fileName = 'States.cpp'; - - const stateClasses = Object.keys(schema.modules) - .map(moduleName => { - const module = schema.modules[moduleName]; - if (module.type !== 'Component') { - return; - } - - const {components} = module; - // No components in this module - if (components == null) { - return null; - } - - return Object.keys(components) - .map(componentName => { - const component = components[componentName]; - if (component.interfaceOnly === true) { - return null; - } - - return StateTemplate({ - stateName: `${componentName}State`, - }); - }) - .filter(Boolean) - .join('\n'); - }) - .filter(Boolean) - .join('\n'); - - const replacedTemplate = FileTemplate({ - libraryName, - stateClasses, - }); - - return new Map([[fileName, replacedTemplate]]); - }, -}; diff --git a/packages/react-native-codegen/src/generators/components/GenerateStateH.js b/packages/react-native-codegen/src/generators/components/GenerateStateH.js deleted file mode 100644 index 658142eaea04..000000000000 --- a/packages/react-native-codegen/src/generators/components/GenerateStateH.js +++ /dev/null @@ -1,111 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type {SchemaType} from '../../CodegenSchema'; - -// File path -> contents -type FilesOutput = Map; - -const FileTemplate = ({ - libraryName, - stateClasses, -}: { - libraryName: string, - stateClasses: string, -}) => - ` -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * ${'@'}generated by codegen project: GenerateStateH.js - */ -#pragma once - -#ifdef ANDROID -#include -#include -#include -#endif - -namespace facebook { -namespace react { - -${stateClasses} - -} // namespace react -} // namespace facebook -`.trim(); - -const StateTemplate = ({stateName}: {stateName: string}) => - ` -class ${stateName}State { -public: - ${stateName}State() = default; - -#ifdef ANDROID - ${stateName}State(${stateName}State const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; - MapBuffer getMapBuffer() const { - return MapBufferBuilder::EMPTY(); - }; -#endif -}; -`.trim(); - -module.exports = { - generate( - libraryName: string, - schema: SchemaType, - packageName?: string, - assumeNonnull: boolean = false, - ): FilesOutput { - const fileName = 'States.h'; - - const stateClasses = Object.keys(schema.modules) - .map(moduleName => { - const module = schema.modules[moduleName]; - if (module.type !== 'Component') { - return; - } - - const {components} = module; - // No components in this module - if (components == null) { - return null; - } - - return Object.keys(components) - .map(componentName => { - const component = components[componentName]; - if (component.interfaceOnly === true) { - return null; - } - return StateTemplate({stateName: componentName}); - }) - .filter(Boolean) - .join('\n\n'); - }) - .filter(Boolean) - .join('\n\n'); - - const template = FileTemplate({ - libraryName, - stateClasses, - }); - return new Map([[fileName, template]]); - }, -}; diff --git a/packages/react-native-codegen/src/generators/components/GenerateTests.js b/packages/react-native-codegen/src/generators/components/GenerateTests.js deleted file mode 100644 index cfefaa318bd9..000000000000 --- a/packages/react-native-codegen/src/generators/components/GenerateTests.js +++ /dev/null @@ -1,219 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; -import type {PropTypeAnnotation, ComponentShape} from '../../CodegenSchema'; - -import type {SchemaType} from '../../CodegenSchema'; -const {getImports, toSafeCppString} = require('./CppHelpers'); - -type FilesOutput = Map; -type PropValueType = string | number | boolean; - -type TestCase = $ReadOnly<{ - propName: string, - propValue: ?PropValueType, - testName?: string, - raw?: boolean, -}>; - -const FileTemplate = ({ - libraryName, - imports, - componentTests, -}: { - libraryName: string, - imports: string, - componentTests: string, -}) => - ` -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * ${'@'}generated by codegen project: GenerateTests.js - * */ - -#include -#include -#include -${imports} - -using namespace facebook::react; -${componentTests} -`.trim(); - -const TestTemplate = ({ - componentName, - testName, - propName, - propValue, -}: { - componentName: string, - testName: string, - propName: string, - propValue: string, -}) => ` -TEST(${componentName}_${testName}, etc) { - auto propParser = RawPropsParser(); - propParser.prepare<${componentName}>(); - auto const &sourceProps = ${componentName}(); - auto const &rawProps = RawProps(folly::dynamic::object("${propName}", ${propValue})); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - ${componentName}(parserContext, sourceProps, rawProps); -} -`; - -function getTestCasesForProp( - propName: string, - typeAnnotation: PropTypeAnnotation, -) { - const cases = []; - if (typeAnnotation.type === 'StringEnumTypeAnnotation') { - typeAnnotation.options.forEach(option => - cases.push({ - propName, - testName: `${propName}_${toSafeCppString(option)}`, - propValue: option, - }), - ); - } else if (typeAnnotation.type === 'StringTypeAnnotation') { - cases.push({ - propName, - propValue: - typeAnnotation.default != null && typeAnnotation.default !== '' - ? typeAnnotation.default - : 'foo', - }); - } else if (typeAnnotation.type === 'BooleanTypeAnnotation') { - cases.push({ - propName: propName, - propValue: typeAnnotation.default != null ? typeAnnotation.default : true, - }); - // $FlowFixMe[incompatible-type] - } else if (typeAnnotation.type === 'IntegerTypeAnnotation') { - cases.push({ - propName, - propValue: typeAnnotation.default || 10, - }); - } else if (typeAnnotation.type === 'FloatTypeAnnotation') { - cases.push({ - propName, - propValue: typeAnnotation.default != null ? typeAnnotation.default : 0.1, - }); - } else if (typeAnnotation.type === 'ReservedPropTypeAnnotation') { - if (typeAnnotation.name === 'ColorPrimitive') { - cases.push({ - propName, - propValue: 1, - }); - } else if (typeAnnotation.name === 'PointPrimitive') { - cases.push({ - propName, - propValue: 'folly::dynamic::object("x", 1)("y", 1)', - raw: true, - }); - } else if (typeAnnotation.name === 'ImageSourcePrimitive') { - cases.push({ - propName, - propValue: 'folly::dynamic::object("url", "testurl")', - raw: true, - }); - } - } - - return cases; -} - -function generateTestsString(name: string, component: ComponentShape) { - function createTest({testName, propName, propValue, raw = false}: TestCase) { - const value = - !raw && typeof propValue === 'string' ? `"${propValue}"` : propValue; - - return TestTemplate({ - componentName: name, - testName: testName != null ? testName : propName, - propName, - propValue: String(value), - }); - } - - const testCases = component.props.reduce((cases, prop) => { - return cases.concat(getTestCasesForProp(prop.name, prop.typeAnnotation)); - }, []); - - const baseTest = { - testName: 'DoesNotDie', - propName: 'xx_invalid_xx', - propValue: 'xx_invalid_xx', - }; - - return [baseTest, ...testCases].map(createTest).join(''); -} - -module.exports = { - generate( - libraryName: string, - schema: SchemaType, - packageName?: string, - assumeNonnull: boolean = false, - ): FilesOutput { - const fileName = 'Tests.cpp'; - const allImports = new Set([ - '#include ', - '#include ', - '#include ', - ]); - - const componentTests = Object.keys(schema.modules) - .map(moduleName => { - const module = schema.modules[moduleName]; - if (module.type !== 'Component') { - return; - } - - const {components} = module; - if (components == null) { - return null; - } - - return Object.keys(components) - .map(componentName => { - const component = components[componentName]; - const name = `${componentName}Props`; - - const imports = getImports(component.props); - // $FlowFixMe[method-unbinding] added when improving typing for this parameters - imports.forEach(allImports.add, allImports); - - return generateTestsString(name, component); - }) - .join(''); - }) - .filter(Boolean) - .join(''); - - const imports = Array.from(allImports).sort().join('\n').trim(); - - const replacedTemplate = FileTemplate({ - imports, - libraryName, - componentTests, - }); - - return new Map([[fileName, replacedTemplate]]); - }, -}; diff --git a/packages/react-native-codegen/src/generators/components/GenerateThirdPartyFabricComponentsProviderH.js b/packages/react-native-codegen/src/generators/components/GenerateThirdPartyFabricComponentsProviderH.js deleted file mode 100644 index cddb1302d754..000000000000 --- a/packages/react-native-codegen/src/generators/components/GenerateThirdPartyFabricComponentsProviderH.js +++ /dev/null @@ -1,107 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type {SchemaType} from '../../CodegenSchema'; - -// File path -> contents -type FilesOutput = Map; - -const FileTemplate = ({lookupFuncs}: {lookupFuncs: string}) => ` -/* - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * ${'@'}generated by GenerateRCTThirdPartyFabricComponentsProviderH - */ - -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wreturn-type-c-linkage" - -#import - -#ifdef __cplusplus -extern "C" { -#endif - -Class RCTThirdPartyFabricComponentsProvider(const char *name); - -${lookupFuncs} - -#ifdef __cplusplus -} -#endif - -#pragma GCC diagnostic pop - -`; - -const LookupFuncTemplate = ({ - className, - libraryName, -}: { - className: string, - libraryName: string, -}) => - ` -Class ${className}Cls(void) __attribute__((used)); // ${libraryName} -`.trim(); - -module.exports = { - generate(schemas: {[string]: SchemaType}): FilesOutput { - const fileName = 'RCTThirdPartyFabricComponentsProvider.h'; - - const lookupFuncs = Object.keys(schemas) - .map(libraryName => { - const schema = schemas[libraryName]; - return Object.keys(schema.modules) - .map(moduleName => { - const module = schema.modules[moduleName]; - if (module.type !== 'Component') { - return; - } - - const {components} = module; - // No components in this module - if (components == null) { - return null; - } - - return Object.keys(components) - .filter(componentName => { - const component = components[componentName]; - return !( - component.excludedPlatforms && - component.excludedPlatforms.includes('iOS') - ); - }) - .map(componentName => { - return LookupFuncTemplate({ - className: componentName, - libraryName, - }); - }) - .join('\n'); - }) - .filter(Boolean) - .join('\n'); - }) - .join('\n'); - - const replacedTemplate = FileTemplate({ - lookupFuncs, - }); - - return new Map([[fileName, replacedTemplate]]); - }, -}; diff --git a/packages/react-native-codegen/src/generators/components/GenerateThirdPartyFabricComponentsProviderObjCpp.js b/packages/react-native-codegen/src/generators/components/GenerateThirdPartyFabricComponentsProviderObjCpp.js deleted file mode 100644 index fcd7b5281926..000000000000 --- a/packages/react-native-codegen/src/generators/components/GenerateThirdPartyFabricComponentsProviderObjCpp.js +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type {SchemaType} from '../../CodegenSchema'; - -// File path -> contents -type FilesOutput = Map; - -const FileTemplate = ({lookupMap}: {lookupMap: string}) => ` -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * ${'@'}generated by GenerateRCTThirdPartyFabricComponentsProviderCpp - */ - -// OSS-compatibility layer - -#import "RCTThirdPartyFabricComponentsProvider.h" - -#import -#import - -Class RCTThirdPartyFabricComponentsProvider(const char *name) { - static std::unordered_map sFabricComponentsClassMap = { -${lookupMap} - }; - - auto p = sFabricComponentsClassMap.find(name); - if (p != sFabricComponentsClassMap.end()) { - auto classFunc = p->second; - return classFunc(); - } - return nil; -} -`; - -const LookupMapTemplate = ({ - className, - libraryName, -}: { - className: string, - libraryName: string, -}) => ` - {"${className}", ${className}Cls}, // ${libraryName}`; - -module.exports = { - generate(schemas: {[string]: SchemaType}): FilesOutput { - const fileName = 'RCTThirdPartyFabricComponentsProvider.mm'; - - const lookupMap = Object.keys(schemas) - .map(libraryName => { - const schema = schemas[libraryName]; - return Object.keys(schema.modules) - .map(moduleName => { - const module = schema.modules[moduleName]; - if (module.type !== 'Component') { - return; - } - - const {components} = module; - // No components in this module - if (components == null) { - return null; - } - - const componentTemplates = Object.keys(components) - .filter(componentName => { - const component = components[componentName]; - return !( - component.excludedPlatforms && - component.excludedPlatforms.includes('iOS') - ); - }) - .map(componentName => { - const replacedTemplate = LookupMapTemplate({ - className: componentName, - libraryName, - }); - - return replacedTemplate; - }); - - return componentTemplates.length > 0 ? componentTemplates : null; - }) - .filter(Boolean); - }) - .join('\n'); - - const replacedTemplate = FileTemplate({lookupMap}); - - return new Map([[fileName, replacedTemplate]]); - }, -}; diff --git a/packages/react-native-codegen/src/generators/components/GenerateViewConfigJs.js b/packages/react-native-codegen/src/generators/components/GenerateViewConfigJs.js deleted file mode 100644 index efdea0ec5ade..000000000000 --- a/packages/react-native-codegen/src/generators/components/GenerateViewConfigJs.js +++ /dev/null @@ -1,485 +0,0 @@ -/** - * 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 - */ - -'use strict'; -import type { - PropTypeAnnotation, - EventTypeShape, - ComponentShape, -} from '../../CodegenSchema'; - -const j = require('jscodeshift'); - -import type {SchemaType} from '../../CodegenSchema'; - -// File path -> contents -type FilesOutput = Map; - -const FileTemplate = ({ - imports, - componentConfig, -}: { - imports: string, - componentConfig: string, -}) => ` -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * ${'@'}generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -${imports} - -${componentConfig} -`; - -// We use this to add to a set. Need to make sure we aren't importing -// this multiple times. -const UIMANAGER_IMPORT = 'const {UIManager} = require("react-native")'; - -function getReactDiffProcessValue(typeAnnotation: PropTypeAnnotation) { - switch (typeAnnotation.type) { - case 'BooleanTypeAnnotation': - case 'StringTypeAnnotation': - case 'Int32TypeAnnotation': - case 'DoubleTypeAnnotation': - case 'FloatTypeAnnotation': - case 'ObjectTypeAnnotation': - case 'StringEnumTypeAnnotation': - case 'Int32EnumTypeAnnotation': - return j.literal(true); - case 'ReservedPropTypeAnnotation': - switch (typeAnnotation.name) { - case 'ColorPrimitive': - return j.template - .expression`{ process: require('react-native/Libraries/StyleSheet/processColor') }`; - case 'ImageSourcePrimitive': - return j.template - .expression`{ process: require('react-native/Libraries/Image/resolveAssetSource') }`; - case 'ImageRequestPrimitive': - throw new Error('ImageRequest should not be used in props'); - case 'PointPrimitive': - return j.template - .expression`{ diff: require('react-native/Libraries/Utilities/differ/pointsDiffer') }`; - case 'EdgeInsetsPrimitive': - return j.template - .expression`{ diff: require('react-native/Libraries/Utilities/differ/insetsDiffer') }`; - default: - (typeAnnotation.name: empty); - throw new Error( - `Received unknown native typeAnnotation: "${typeAnnotation.name}"`, - ); - } - case 'ArrayTypeAnnotation': - if (typeAnnotation.elementType.type === 'ReservedPropTypeAnnotation') { - switch (typeAnnotation.elementType.name) { - case 'ColorPrimitive': - return j.template - .expression`{ process: require('react-native/Libraries/StyleSheet/processColorArray') }`; - case 'ImageSourcePrimitive': - return j.literal(true); - case 'PointPrimitive': - return j.literal(true); - default: - throw new Error( - `Received unknown array native typeAnnotation: "${typeAnnotation.elementType.name}"`, - ); - } - } - return j.literal(true); - default: - (typeAnnotation: empty); - throw new Error( - `Received unknown typeAnnotation: "${typeAnnotation.type}"`, - ); - } -} - -const ComponentTemplate = ({ - componentName, - paperComponentName, - paperComponentNameDeprecated, -}: { - componentName: string, - paperComponentName: ?string, - paperComponentNameDeprecated: ?string, -}) => { - const nativeComponentName = paperComponentName ?? componentName; - - return ` -let nativeComponentName = '${nativeComponentName}'; -${ - paperComponentNameDeprecated != null - ? DeprecatedComponentNameCheckTemplate({ - componentName, - paperComponentNameDeprecated, - }) - : '' -} - -export const __INTERNAL_VIEW_CONFIG = VIEW_CONFIG; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -`.trim(); -}; - -// Check whether the native component exists in the app binary. -// Old getViewManagerConfig() checks for the existance of the native Paper view manager. Not available in Bridgeless. -// New hasViewManagerConfig() queries Fabric’s native component registry directly. -const DeprecatedComponentNameCheckTemplate = ({ - componentName, - paperComponentNameDeprecated, -}: { - componentName: string, - paperComponentNameDeprecated: string, -}) => - ` -if (UIManager.hasViewManagerConfig('${componentName}')) { - nativeComponentName = '${componentName}'; -} else if (UIManager.hasViewManagerConfig('${paperComponentNameDeprecated}')) { - nativeComponentName = '${paperComponentNameDeprecated}'; -} else { - throw new Error('Failed to find native component for either "${componentName}" or "${paperComponentNameDeprecated}"'); -} -`.trim(); - -// Replicates the behavior of RCTNormalizeInputEventName in RCTEventDispatcher.m -function normalizeInputEventName(name: string) { - if (name.startsWith('on')) { - return name.replace(/^on/, 'top'); - } else if (!name.startsWith('top')) { - return `top${name[0].toUpperCase()}${name.slice(1)}`; - } - - return name; -} - -// Replicates the behavior of viewConfig in RCTComponentData.m -function getValidAttributesForEvents( - events: $ReadOnlyArray, - imports: Set, -) { - imports.add( - "const {ConditionallyIgnoredEventHandlers} = require('react-native/Libraries/NativeComponent/ViewConfigIgnore');", - ); - - const validAttributes = j.objectExpression( - events.map(eventType => { - return j.property('init', j.identifier(eventType.name), j.literal(true)); - }), - ); - - return j.callExpression(j.identifier('ConditionallyIgnoredEventHandlers'), [ - validAttributes, - ]); -} - -function generateBubblingEventInfo( - event: EventTypeShape, - nameOveride: void | string, -) { - return j.property( - 'init', - j.identifier(nameOveride || normalizeInputEventName(event.name)), - j.objectExpression([ - j.property( - 'init', - j.identifier('phasedRegistrationNames'), - j.objectExpression([ - j.property( - 'init', - j.identifier('captured'), - j.literal(`${event.name}Capture`), - ), - j.property('init', j.identifier('bubbled'), j.literal(event.name)), - ]), - ), - ]), - ); -} - -function generateDirectEventInfo( - event: EventTypeShape, - nameOveride: void | string, -) { - return j.property( - 'init', - j.identifier(nameOveride || normalizeInputEventName(event.name)), - j.objectExpression([ - j.property( - 'init', - j.identifier('registrationName'), - j.literal(event.name), - ), - ]), - ); -} - -function buildViewConfig( - schema: SchemaType, - componentName: string, - component: ComponentShape, - imports: Set, -) { - const componentProps = component.props; - const componentEvents = component.events; - - component.extendsProps.forEach(extendProps => { - switch (extendProps.type) { - case 'ReactNativeBuiltInType': - switch (extendProps.knownTypeName) { - case 'ReactNativeCoreViewProps': - imports.add( - "const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry');", - ); - - return; - default: - (extendProps.knownTypeName: empty); - throw new Error('Invalid knownTypeName'); - } - default: - (extendProps.type: empty); - throw new Error('Invalid extended type'); - } - }); - - const validAttributes = j.objectExpression([ - ...componentProps.map(schemaProp => { - return j.property( - 'init', - j.identifier(schemaProp.name), - getReactDiffProcessValue(schemaProp.typeAnnotation), - ); - }), - ...(componentEvents.length > 0 - ? [ - j.spreadProperty( - getValidAttributesForEvents(componentEvents, imports), - ), - ] - : []), - ]); - - const bubblingEventNames = component.events - .filter(event => event.bubblingType === 'bubble') - .reduce((bubblingEvents, event) => { - // We add in the deprecated paper name so that it is in the view config. - // This means either the old event name or the new event name can fire - // and be sent to the listener until the old top level name is removed. - if (event.paperTopLevelNameDeprecated) { - bubblingEvents.push( - generateBubblingEventInfo(event, event.paperTopLevelNameDeprecated), - ); - } else { - bubblingEvents.push(generateBubblingEventInfo(event)); - } - return bubblingEvents; - }, []); - - const bubblingEvents = - bubblingEventNames.length > 0 - ? j.property( - 'init', - j.identifier('bubblingEventTypes'), - j.objectExpression(bubblingEventNames), - ) - : null; - - const directEventNames = component.events - .filter(event => event.bubblingType === 'direct') - .reduce((directEvents, event) => { - // We add in the deprecated paper name so that it is in the view config. - // This means either the old event name or the new event name can fire - // and be sent to the listener until the old top level name is removed. - if (event.paperTopLevelNameDeprecated) { - directEvents.push( - generateDirectEventInfo(event, event.paperTopLevelNameDeprecated), - ); - } else { - directEvents.push(generateDirectEventInfo(event)); - } - return directEvents; - }, []); - - const directEvents = - directEventNames.length > 0 - ? j.property( - 'init', - j.identifier('directEventTypes'), - j.objectExpression(directEventNames), - ) - : null; - - const properties = [ - j.property( - 'init', - j.identifier('uiViewClassName'), - j.literal(componentName), - ), - bubblingEvents, - directEvents, - j.property('init', j.identifier('validAttributes'), validAttributes), - ].filter(Boolean); - - return j.objectExpression(properties); -} - -function buildCommands( - schema: SchemaType, - componentName: string, - component: ComponentShape, - imports: Set, -) { - const commands = component.commands; - - if (commands.length === 0) { - return null; - } - - imports.add( - 'const {dispatchCommand} = require("react-native/Libraries/ReactNative/RendererProxy");', - ); - - const properties = commands.map(command => { - const commandName = command.name; - const params = command.typeAnnotation.params; - - const commandNameLiteral = j.literal(commandName); - const commandNameIdentifier = j.identifier(commandName); - const arrayParams = j.arrayExpression( - params.map(param => { - return j.identifier(param.name); - }), - ); - - const expression = j.template - .expression`dispatchCommand(ref, ${commandNameLiteral}, ${arrayParams})`; - - const functionParams = params.map(param => { - return j.identifier(param.name); - }); - - const property = j.property( - 'init', - commandNameIdentifier, - j.functionExpression( - null, - [j.identifier('ref'), ...functionParams], - j.blockStatement([j.expressionStatement(expression)]), - ), - ); - property.method = true; - - return property; - }); - - return j.exportNamedDeclaration( - j.variableDeclaration('const', [ - j.variableDeclarator( - j.identifier('Commands'), - j.objectExpression(properties), - ), - ]), - ); -} - -module.exports = { - generate(libraryName: string, schema: SchemaType): FilesOutput { - try { - const fileName = `${libraryName}NativeViewConfig.js`; - const imports: Set = new Set(); - - const moduleResults = Object.keys(schema.modules) - .map(moduleName => { - const module = schema.modules[moduleName]; - if (module.type !== 'Component') { - return; - } - - const {components} = module; - - return Object.keys(components) - .map((componentName: string) => { - const component = components[componentName]; - - if (component.paperComponentNameDeprecated) { - imports.add(UIMANAGER_IMPORT); - } - - const replacedTemplate = ComponentTemplate({ - componentName, - paperComponentName: component.paperComponentName, - paperComponentNameDeprecated: - component.paperComponentNameDeprecated, - }); - - const replacedSourceRoot = j.withParser('flow')(replacedTemplate); - - const paperComponentName = - component.paperComponentName ?? componentName; - - replacedSourceRoot - .find(j.Identifier, { - name: 'VIEW_CONFIG', - }) - .replaceWith( - buildViewConfig( - schema, - paperComponentName, - component, - imports, - ), - ); - - const commands = buildCommands( - schema, - paperComponentName, - component, - imports, - ); - if (commands) { - replacedSourceRoot - .find(j.ExportDefaultDeclaration) - .insertAfter(j(commands).toSource()); - } - - const replacedSource: string = replacedSourceRoot.toSource({ - quote: 'single', - trailingComma: true, - }); - - return replacedSource; - }) - .join('\n\n'); - }) - .filter(Boolean) - .join('\n\n'); - - const replacedTemplate = FileTemplate({ - componentConfig: moduleResults, - imports: Array.from(imports).sort().join('\n'), - }); - - return new Map([[fileName, replacedTemplate]]); - } catch (error) { - console.error(`\nError parsing schema for ${libraryName}\n`); - console.error(JSON.stringify(schema)); - throw error; - } - }, -}; diff --git a/packages/react-native-codegen/src/generators/components/JavaHelpers.js b/packages/react-native-codegen/src/generators/components/JavaHelpers.js deleted file mode 100644 index 421ed3e58513..000000000000 --- a/packages/react-native-codegen/src/generators/components/JavaHelpers.js +++ /dev/null @@ -1,119 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type {ComponentShape} from '../../CodegenSchema'; - -function upperCaseFirst(inString: string): string { - return inString[0].toUpperCase() + inString.slice(1); -} - -function getInterfaceJavaClassName(componentName: string): string { - return `${componentName.replace(/^RCT/, '')}ManagerInterface`; -} - -function getDelegateJavaClassName(componentName: string): string { - return `${componentName.replace(/^RCT/, '')}ManagerDelegate`; -} - -function toSafeJavaString( - input: string, - shouldUpperCaseFirst?: boolean, -): string { - const parts = input.split('-'); - - if (shouldUpperCaseFirst === false) { - return parts.join(''); - } - - return parts.map(upperCaseFirst).join(''); -} - -function getImports( - component: ComponentShape, - type: 'interface' | 'delegate', -): Set { - const imports: Set = new Set(); - - component.extendsProps.forEach(extendProps => { - switch (extendProps.type) { - case 'ReactNativeBuiltInType': - switch (extendProps.knownTypeName) { - case 'ReactNativeCoreViewProps': - imports.add('import android.view.View;'); - return; - default: - (extendProps.knownTypeName: empty); - throw new Error('Invalid knownTypeName'); - } - default: - (extendProps.type: empty); - throw new Error('Invalid extended type'); - } - }); - - function addImportsForNativeName( - name: - | 'ColorPrimitive' - | 'EdgeInsetsPrimitive' - | 'ImageSourcePrimitive' - | 'PointPrimitive' - | $TEMPORARY$string<'ColorPrimitive'> - | $TEMPORARY$string<'EdgeInsetsPrimitive'> - | $TEMPORARY$string<'ImageSourcePrimitive'> - | $TEMPORARY$string<'PointPrimitive'>, - ) { - switch (name) { - case 'ColorPrimitive': - if (type === 'delegate') { - imports.add('import com.facebook.react.bridge.ColorPropConverter;'); - } - return; - case 'ImageSourcePrimitive': - imports.add('import com.facebook.react.bridge.ReadableMap;'); - return; - case 'PointPrimitive': - imports.add('import com.facebook.react.bridge.ReadableMap;'); - return; - case 'EdgeInsetsPrimitive': - imports.add('import com.facebook.react.bridge.ReadableMap;'); - return; - default: - (name: empty); - throw new Error(`Invalid ReservedPropTypeAnnotation name, got ${name}`); - } - } - - component.props.forEach(prop => { - const typeAnnotation = prop.typeAnnotation; - - if (typeAnnotation.type === 'ReservedPropTypeAnnotation') { - addImportsForNativeName(typeAnnotation.name); - } - - if (typeAnnotation.type === 'ArrayTypeAnnotation') { - imports.add('import com.facebook.react.bridge.ReadableArray;'); - } - - if (typeAnnotation.type === 'ObjectTypeAnnotation') { - imports.add('import com.facebook.react.bridge.ReadableMap;'); - } - }); - - return imports; -} - -module.exports = { - getInterfaceJavaClassName, - getDelegateJavaClassName, - toSafeJavaString, - getImports, -}; diff --git a/packages/react-native-codegen/src/generators/components/__test_fixtures__/fixtures.js b/packages/react-native-codegen/src/generators/components/__test_fixtures__/fixtures.js deleted file mode 100644 index b38d07d189e6..000000000000 --- a/packages/react-native-codegen/src/generators/components/__test_fixtures__/fixtures.js +++ /dev/null @@ -1,1672 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {SchemaType} from '../../../CodegenSchema.js'; - -const NO_PROPS_NO_EVENTS: SchemaType = { - modules: { - NoPropsNoEvents: { - type: 'Component', - components: { - NoPropsNoEventsComponent: { - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [], - props: [], - commands: [], - }, - }, - }, - }, -}; - -const INTERFACE_ONLY: SchemaType = { - modules: { - Switch: { - type: 'Component', - components: { - InterfaceOnlyComponent: { - interfaceOnly: true, - paperComponentName: 'RCTInterfaceOnlyComponent', - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [ - { - name: 'onChange', - optional: true, - bubblingType: 'bubble', - typeAnnotation: { - type: 'EventTypeAnnotation', - argument: { - type: 'ObjectTypeAnnotation', - properties: [ - { - name: 'value', - optional: false, - typeAnnotation: { - type: 'BooleanTypeAnnotation', - }, - }, - ], - }, - }, - }, - ], - props: [ - { - name: 'accessibilityHint', - optional: true, - typeAnnotation: { - type: 'StringTypeAnnotation', - default: '', - }, - }, - ], - commands: [], - }, - }, - }, - }, -}; - -const EVENTS_WITH_PAPER_NAME: SchemaType = { - modules: { - Switch: { - type: 'Component', - components: { - InterfaceOnlyComponent: { - interfaceOnly: true, - paperComponentName: 'RCTInterfaceOnlyComponent', - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [ - { - name: 'onChange', - paperTopLevelNameDeprecated: 'paperChange', - optional: true, - bubblingType: 'bubble', - typeAnnotation: { - type: 'EventTypeAnnotation', - argument: { - type: 'ObjectTypeAnnotation', - properties: [ - { - name: 'value', - optional: false, - typeAnnotation: { - type: 'BooleanTypeAnnotation', - }, - }, - ], - }, - }, - }, - { - name: 'onDire tChange', - paperTopLevelNameDeprecated: 'paperDirectChange', - optional: true, - bubblingType: 'direct', - typeAnnotation: { - type: 'EventTypeAnnotation', - argument: { - type: 'ObjectTypeAnnotation', - properties: [ - { - name: 'value', - optional: false, - typeAnnotation: { - type: 'BooleanTypeAnnotation', - }, - }, - ], - }, - }, - }, - ], - props: [], - commands: [], - }, - }, - }, - }, -}; - -const BOOLEAN_PROP: SchemaType = { - modules: { - Switch: { - type: 'Component', - components: { - BooleanPropNativeComponent: { - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [], - props: [ - { - name: 'disabled', - optional: true, - typeAnnotation: { - type: 'BooleanTypeAnnotation', - default: false, - }, - }, - ], - commands: [], - }, - }, - }, - }, -}; - -const STRING_PROP: SchemaType = { - modules: { - Switch: { - type: 'Component', - components: { - StringPropComponent: { - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [], - props: [ - { - name: 'accessibilityHint', - optional: true, - typeAnnotation: { - type: 'StringTypeAnnotation', - default: '', - }, - }, - { - name: 'accessibilityRole', - optional: true, - typeAnnotation: { - type: 'StringTypeAnnotation', - default: null, - }, - }, - ], - commands: [], - }, - }, - }, - }, -}; - -const INTEGER_PROPS: SchemaType = { - modules: { - Switch: { - type: 'Component', - components: { - IntegerPropNativeComponent: { - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [], - props: [ - { - name: 'progress1', - optional: true, - typeAnnotation: { - type: 'Int32TypeAnnotation', - default: 0, - }, - }, - { - name: 'progress2', - optional: true, - typeAnnotation: { - type: 'Int32TypeAnnotation', - default: -1, - }, - }, - { - name: 'progress3', - optional: true, - typeAnnotation: { - type: 'Int32TypeAnnotation', - default: 10, - }, - }, - ], - commands: [], - }, - }, - }, - }, -}; - -const FLOAT_PROPS: SchemaType = { - modules: { - Switch: { - type: 'Component', - components: { - FloatPropNativeComponent: { - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [], - props: [ - { - name: 'blurRadius', - optional: false, - typeAnnotation: { - type: 'FloatTypeAnnotation', - default: 0.0, - }, - }, - { - name: 'blurRadius2', - optional: true, - typeAnnotation: { - type: 'FloatTypeAnnotation', - default: 0.001, - }, - }, - { - name: 'blurRadius3', - optional: true, - typeAnnotation: { - type: 'FloatTypeAnnotation', - default: 2.1, - }, - }, - { - name: 'blurRadius4', - optional: true, - typeAnnotation: { - type: 'FloatTypeAnnotation', - default: 0, - }, - }, - { - name: 'blurRadius5', - optional: true, - typeAnnotation: { - type: 'FloatTypeAnnotation', - default: 1, - }, - }, - { - name: 'blurRadius6', - optional: true, - typeAnnotation: { - type: 'FloatTypeAnnotation', - default: -0.0, - }, - }, - ], - commands: [], - }, - }, - }, - }, -}; - -const DOUBLE_PROPS: SchemaType = { - modules: { - Switch: { - type: 'Component', - components: { - DoublePropNativeComponent: { - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [], - props: [ - { - name: 'blurRadius', - optional: false, - typeAnnotation: { - type: 'DoubleTypeAnnotation', - default: 0.0, - }, - }, - { - name: 'blurRadius2', - optional: true, - typeAnnotation: { - type: 'DoubleTypeAnnotation', - default: 0.001, - }, - }, - { - name: 'blurRadius3', - optional: true, - typeAnnotation: { - type: 'DoubleTypeAnnotation', - default: 2.1, - }, - }, - { - name: 'blurRadius4', - optional: true, - typeAnnotation: { - type: 'DoubleTypeAnnotation', - default: 0, - }, - }, - { - name: 'blurRadius5', - optional: true, - typeAnnotation: { - type: 'DoubleTypeAnnotation', - default: 1, - }, - }, - { - name: 'blurRadius6', - optional: true, - typeAnnotation: { - type: 'DoubleTypeAnnotation', - default: -0.0, - }, - }, - ], - commands: [], - }, - }, - }, - }, -}; - -const COLOR_PROP: SchemaType = { - modules: { - Switch: { - type: 'Component', - components: { - ColorPropNativeComponent: { - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [], - props: [ - { - name: 'tintColor', - optional: true, - typeAnnotation: { - type: 'ReservedPropTypeAnnotation', - name: 'ColorPrimitive', - }, - }, - ], - commands: [], - }, - }, - }, - }, -}; - -const IMAGE_PROP: SchemaType = { - modules: { - Slider: { - type: 'Component', - components: { - ImagePropNativeComponent: { - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [], - props: [ - { - name: 'thumbImage', - optional: true, - typeAnnotation: { - type: 'ReservedPropTypeAnnotation', - name: 'ImageSourcePrimitive', - }, - }, - ], - commands: [], - }, - }, - }, - }, -}; - -const POINT_PROP: SchemaType = { - modules: { - Switch: { - type: 'Component', - components: { - PointPropNativeComponent: { - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [], - props: [ - { - name: 'startPoint', - optional: true, - typeAnnotation: { - type: 'ReservedPropTypeAnnotation', - name: 'PointPrimitive', - }, - }, - ], - commands: [], - }, - }, - }, - }, -}; - -const INSETS_PROP: SchemaType = { - modules: { - ScrollView: { - type: 'Component', - components: { - InsetsPropNativeComponent: { - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [], - props: [ - { - name: 'contentInset', - optional: true, - typeAnnotation: { - type: 'ReservedPropTypeAnnotation', - name: 'EdgeInsetsPrimitive', - }, - }, - ], - commands: [], - }, - }, - }, - }, -}; - -const ARRAY_PROPS: SchemaType = { - modules: { - Slider: { - type: 'Component', - components: { - ArrayPropsNativeComponent: { - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [], - props: [ - { - name: 'names', - optional: true, - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'StringTypeAnnotation', - }, - }, - }, - { - name: 'disableds', - optional: true, - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'BooleanTypeAnnotation', - }, - }, - }, - { - name: 'progress', - optional: true, - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'Int32TypeAnnotation', - }, - }, - }, - { - name: 'radii', - optional: true, - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'FloatTypeAnnotation', - }, - }, - }, - { - name: 'colors', - optional: true, - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'ReservedPropTypeAnnotation', - name: 'ColorPrimitive', - }, - }, - }, - { - name: 'srcs', - optional: true, - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'ReservedPropTypeAnnotation', - name: 'ImageSourcePrimitive', - }, - }, - }, - { - name: 'points', - optional: true, - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'ReservedPropTypeAnnotation', - name: 'PointPrimitive', - }, - }, - }, - { - name: 'sizes', - optional: true, - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'StringEnumTypeAnnotation', - default: 'small', - options: ['small', 'large'], - }, - }, - }, - { - name: 'object', - optional: true, - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'ObjectTypeAnnotation', - properties: [ - { - name: 'stringProp', - optional: true, - typeAnnotation: { - type: 'StringTypeAnnotation', - default: '', - }, - }, - ], - }, - }, - }, - { - name: 'array', - optional: true, - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'ObjectTypeAnnotation', - properties: [ - { - // This needs to stay the same as the object above - // to confirm that the structs are generated - // with unique non-colliding names - name: 'object', - optional: true, - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'ObjectTypeAnnotation', - properties: [ - { - name: 'stringProp', - optional: true, - typeAnnotation: { - type: 'StringTypeAnnotation', - default: '', - }, - }, - ], - }, - }, - }, - ], - }, - }, - }, - { - name: 'arrayOfArrayOfObject', - optional: true, - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'ObjectTypeAnnotation', - properties: [ - { - name: 'stringProp', - optional: true, - typeAnnotation: { - type: 'StringTypeAnnotation', - default: '', - }, - }, - ], - }, - }, - }, - }, - ], - commands: [], - }, - }, - }, - }, -}; - -const ARRAY_PROPS_WITH_NESTED_OBJECT: SchemaType = { - modules: { - Slider: { - type: 'Component', - components: { - ArrayPropsNativeComponent: { - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [], - props: [ - { - name: 'nativePrimitives', - optional: true, - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'ObjectTypeAnnotation', - properties: [ - { - name: 'colors', - optional: true, - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'ReservedPropTypeAnnotation', - name: 'ColorPrimitive', - }, - }, - }, - { - name: 'srcs', - optional: true, - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'ReservedPropTypeAnnotation', - name: 'ImageSourcePrimitive', - }, - }, - }, - { - name: 'points', - optional: true, - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'ReservedPropTypeAnnotation', - name: 'PointPrimitive', - }, - }, - }, - ], - }, - }, - }, - ], - commands: [], - }, - }, - }, - }, -}; - -const OBJECT_PROPS: SchemaType = { - modules: { - ObjectPropsNativeComponent: { - type: 'Component', - components: { - ObjectProps: { - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [], - props: [ - { - name: 'objectProp', - optional: true, - typeAnnotation: { - type: 'ObjectTypeAnnotation', - properties: [ - { - name: 'stringProp', - optional: true, - typeAnnotation: { - type: 'StringTypeAnnotation', - default: '', - }, - }, - { - name: 'booleanProp', - optional: true, - typeAnnotation: { - type: 'BooleanTypeAnnotation', - default: false, - }, - }, - { - name: 'floatProp', - optional: true, - typeAnnotation: { - type: 'FloatTypeAnnotation', - default: 0.0, - }, - }, - { - name: 'intProp', - optional: true, - typeAnnotation: { - type: 'Int32TypeAnnotation', - default: 0, - }, - }, - { - name: 'stringEnumProp', - optional: true, - typeAnnotation: { - type: 'StringEnumTypeAnnotation', - default: 'option1', - options: ['option1'], - }, - }, - { - name: 'intEnumProp', - optional: true, - typeAnnotation: { - type: 'Int32EnumTypeAnnotation', - default: 0, - options: [0], - }, - }, - { - name: 'objectArrayProp', - optional: false, - typeAnnotation: { - type: 'ObjectTypeAnnotation', - properties: [ - { - name: 'array', - optional: true, - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'StringTypeAnnotation', - }, - }, - }, - ], - }, - }, - { - name: 'objectPrimitiveRequiredProp', - optional: false, - typeAnnotation: { - type: 'ObjectTypeAnnotation', - properties: [ - { - name: 'image', - optional: true, - typeAnnotation: { - type: 'ReservedPropTypeAnnotation', - name: 'ImageSourcePrimitive', - }, - }, - { - name: 'color', - optional: true, - typeAnnotation: { - type: 'ReservedPropTypeAnnotation', - name: 'ColorPrimitive', - }, - }, - { - name: 'point', - optional: true, - typeAnnotation: { - type: 'ReservedPropTypeAnnotation', - name: 'PointPrimitive', - }, - }, - ], - }, - }, - { - name: 'nestedPropA', - optional: false, - typeAnnotation: { - type: 'ObjectTypeAnnotation', - properties: [ - { - name: 'nestedPropB', - optional: false, - typeAnnotation: { - type: 'ObjectTypeAnnotation', - properties: [ - { - name: 'nestedPropC', - optional: true, - typeAnnotation: { - type: 'StringTypeAnnotation', - default: '', - }, - }, - ], - }, - }, - ], - }, - }, - { - name: 'nestedArrayAsProperty', - optional: false, - typeAnnotation: { - type: 'ObjectTypeAnnotation', - properties: [ - { - name: 'arrayProp', - optional: false, - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'ObjectTypeAnnotation', - properties: [ - { - name: 'stringProp', - optional: false, - typeAnnotation: { - type: 'StringTypeAnnotation', - default: '', - }, - }, - ], - }, - }, - }, - ], - }, - }, - ], - }, - }, - ], - commands: [], - }, - }, - }, - }, -}; - -const MULTI_NATIVE_PROP: SchemaType = { - modules: { - Slider: { - type: 'Component', - components: { - ImageColorPropNativeComponent: { - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [], - props: [ - { - name: 'thumbImage', - optional: true, - typeAnnotation: { - type: 'ReservedPropTypeAnnotation', - name: 'ImageSourcePrimitive', - }, - }, - { - name: 'color', - optional: true, - typeAnnotation: { - type: 'ReservedPropTypeAnnotation', - name: 'ColorPrimitive', - }, - }, - { - name: 'thumbTintColor', - optional: true, - typeAnnotation: { - type: 'ReservedPropTypeAnnotation', - name: 'ColorPrimitive', - }, - }, - { - name: 'point', - optional: true, - typeAnnotation: { - type: 'ReservedPropTypeAnnotation', - name: 'PointPrimitive', - }, - }, - ], - commands: [], - }, - }, - }, - }, -}; - -const STRING_ENUM_PROP: SchemaType = { - modules: { - Switch: { - type: 'Component', - components: { - StringEnumPropsNativeComponent: { - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [], - props: [ - { - name: 'alignment', - optional: true, - typeAnnotation: { - type: 'StringEnumTypeAnnotation', - default: 'center', - options: ['top', 'center', 'bottom-right'], - }, - }, - ], - commands: [], - }, - }, - }, - }, -}; - -const INT32_ENUM_PROP: SchemaType = { - modules: { - Switch: { - type: 'Component', - components: { - Int32EnumPropsNativeComponent: { - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [], - props: [ - { - name: 'maxInterval', - optional: true, - typeAnnotation: { - type: 'Int32EnumTypeAnnotation', - default: 0, - options: [0, 1, 2], - }, - }, - ], - commands: [], - }, - }, - }, - }, -}; - -const EVENT_PROPS: SchemaType = { - modules: { - Switch: { - type: 'Component', - components: { - EventsNativeComponent: { - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [ - { - name: 'onChange', - optional: true, - bubblingType: 'bubble', - typeAnnotation: { - type: 'EventTypeAnnotation', - argument: { - type: 'ObjectTypeAnnotation', - properties: [ - { - name: 'value', - optional: false, - typeAnnotation: { - type: 'BooleanTypeAnnotation', - }, - }, - { - name: 'source', - optional: true, - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - { - name: 'progress', - optional: true, - typeAnnotation: { - type: 'Int32TypeAnnotation', - }, - }, - { - name: 'scale', - optional: true, - typeAnnotation: { - type: 'FloatTypeAnnotation', - }, - }, - ], - }, - }, - }, - { - name: 'onEventDirect', - optional: true, - bubblingType: 'direct', - typeAnnotation: { - type: 'EventTypeAnnotation', - argument: { - type: 'ObjectTypeAnnotation', - properties: [ - { - name: 'value', - optional: false, - typeAnnotation: { - type: 'BooleanTypeAnnotation', - }, - }, - ], - }, - }, - }, - { - name: 'onOrientationChange', - optional: true, - bubblingType: 'direct', - typeAnnotation: { - type: 'EventTypeAnnotation', - argument: { - type: 'ObjectTypeAnnotation', - properties: [ - { - name: 'orientation', - optional: false, - typeAnnotation: { - type: 'StringEnumTypeAnnotation', - options: ['landscape', 'portrait'], - }, - }, - ], - }, - }, - }, - { - name: 'onEnd', - optional: true, - bubblingType: 'bubble', - typeAnnotation: { - type: 'EventTypeAnnotation', - }, - }, - ], - props: [ - { - name: 'disabled', - optional: true, - typeAnnotation: { - type: 'BooleanTypeAnnotation', - default: false, - }, - }, - ], - commands: [], - }, - }, - }, - }, -}; - -const EVENT_NESTED_OBJECT_PROPS: SchemaType = { - modules: { - Switch: { - type: 'Component', - components: { - EventsNestedObjectNativeComponent: { - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [ - { - name: 'onChange', - optional: true, - bubblingType: 'bubble', - typeAnnotation: { - type: 'EventTypeAnnotation', - argument: { - type: 'ObjectTypeAnnotation', - properties: [ - { - name: 'location', - optional: false, - typeAnnotation: { - type: 'ObjectTypeAnnotation', - properties: [ - { - name: 'source', - optional: false, - typeAnnotation: { - type: 'ObjectTypeAnnotation', - properties: [ - { - name: 'url', - optional: false, - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - ], - }, - }, - { - name: 'x', - optional: false, - typeAnnotation: { - type: 'Int32TypeAnnotation', - }, - }, - { - name: 'y', - optional: false, - typeAnnotation: { - type: 'Int32TypeAnnotation', - }, - }, - ], - }, - }, - ], - }, - }, - }, - ], - props: [ - { - name: 'disabled', - optional: true, - typeAnnotation: { - type: 'BooleanTypeAnnotation', - default: false, - }, - }, - ], - commands: [], - }, - }, - }, - }, -}; - -const TWO_COMPONENTS_SAME_FILE: SchemaType = { - modules: { - MyComponents: { - type: 'Component', - components: { - MultiComponent1NativeComponent: { - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [], - props: [ - { - name: 'disabled', - optional: true, - typeAnnotation: { - type: 'BooleanTypeAnnotation', - default: false, - }, - }, - ], - commands: [], - }, - - MultiComponent2NativeComponent: { - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [], - props: [ - { - name: 'disabled', - optional: true, - typeAnnotation: { - type: 'BooleanTypeAnnotation', - default: true, - }, - }, - ], - commands: [], - }, - }, - }, - }, -}; - -const TWO_COMPONENTS_DIFFERENT_FILES: SchemaType = { - modules: { - ComponentFile1: { - type: 'Component', - components: { - MultiFile1NativeComponent: { - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [], - props: [ - { - name: 'disabled', - optional: true, - typeAnnotation: { - type: 'BooleanTypeAnnotation', - default: false, - }, - }, - ], - commands: [], - }, - }, - }, - - ComponentFile2: { - type: 'Component', - components: { - MultiFile2NativeComponent: { - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [], - props: [ - { - name: 'disabled', - optional: true, - typeAnnotation: { - type: 'BooleanTypeAnnotation', - default: true, - }, - }, - ], - commands: [], - }, - }, - }, - }, -}; - -const COMMANDS: SchemaType = { - modules: { - Switch: { - type: 'Component', - components: { - CommandNativeComponent: { - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [], - props: [], - commands: [ - { - name: 'flashScrollIndicators', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - params: [], - returnTypeAnnotation: { - type: 'VoidTypeAnnotation', - }, - }, - }, - { - name: 'allTypes', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - params: [ - { - name: 'x', - optional: false, - typeAnnotation: { - type: 'Int32TypeAnnotation', - }, - }, - { - name: 'y', - optional: false, - typeAnnotation: { - type: 'FloatTypeAnnotation', - }, - }, - { - name: 'z', - optional: false, - typeAnnotation: { - type: 'DoubleTypeAnnotation', - }, - }, - { - name: 'message', - optional: false, - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - { - name: 'animated', - optional: false, - typeAnnotation: { - type: 'BooleanTypeAnnotation', - }, - }, - ], - returnTypeAnnotation: { - type: 'VoidTypeAnnotation', - }, - }, - }, - ], - }, - }, - }, - }, -}; - -const COMMANDS_AND_PROPS: SchemaType = { - modules: { - Switch: { - type: 'Component', - components: { - CommandNativeComponent: { - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [], - props: [ - { - name: 'accessibilityHint', - optional: true, - typeAnnotation: { - type: 'StringTypeAnnotation', - default: '', - }, - }, - ], - commands: [ - { - name: 'handleRootTag', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - params: [ - { - name: 'rootTag', - optional: false, - typeAnnotation: { - type: 'ReservedTypeAnnotation', - name: 'RootTag', - }, - }, - ], - returnTypeAnnotation: { - type: 'VoidTypeAnnotation', - }, - }, - }, - { - name: 'hotspotUpdate', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - params: [ - { - name: 'x', - optional: false, - typeAnnotation: { - type: 'Int32TypeAnnotation', - }, - }, - { - name: 'y', - optional: false, - typeAnnotation: { - type: 'Int32TypeAnnotation', - }, - }, - ], - returnTypeAnnotation: { - type: 'VoidTypeAnnotation', - }, - }, - }, - ], - }, - }, - }, - }, -}; - -const EXCLUDE_ANDROID: SchemaType = { - modules: { - ExcludedAndroid: { - type: 'Component', - components: { - ExcludedAndroidComponent: { - excludedPlatforms: ['android'], - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [], - props: [], - commands: [], - }, - }, - }, - }, -}; - -const EXCLUDE_ANDROID_IOS: SchemaType = { - modules: { - ExcludedAndroidIos: { - type: 'Component', - components: { - ExcludedAndroidIosComponent: { - excludedPlatforms: ['android', 'iOS'], - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [], - props: [], - commands: [], - }, - }, - }, - }, -}; - -const EXCLUDE_IOS_TWO_COMPONENTS_DIFFERENT_FILES: SchemaType = { - modules: { - ComponentFile1: { - type: 'Component', - components: { - ExcludedIosComponent: { - excludedPlatforms: ['iOS'], - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [], - props: [], - commands: [], - }, - }, - }, - ComponentFile2: { - type: 'Component', - components: { - MultiFileIncludedNativeComponent: { - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [], - props: [ - { - name: 'disabled', - optional: true, - typeAnnotation: { - type: 'BooleanTypeAnnotation', - default: true, - }, - }, - ], - commands: [], - }, - }, - }, - }, -}; - -module.exports = { - NO_PROPS_NO_EVENTS, - INTERFACE_ONLY, - BOOLEAN_PROP, - STRING_PROP, - INTEGER_PROPS, - DOUBLE_PROPS, - FLOAT_PROPS, - COLOR_PROP, - IMAGE_PROP, - POINT_PROP, - INSETS_PROP, - ARRAY_PROPS, - ARRAY_PROPS_WITH_NESTED_OBJECT, - OBJECT_PROPS, - MULTI_NATIVE_PROP, - STRING_ENUM_PROP, - INT32_ENUM_PROP, - EVENT_PROPS, - EVENTS_WITH_PAPER_NAME, - EVENT_NESTED_OBJECT_PROPS, - TWO_COMPONENTS_SAME_FILE, - TWO_COMPONENTS_DIFFERENT_FILES, - COMMANDS, - COMMANDS_AND_PROPS, - EXCLUDE_ANDROID, - EXCLUDE_ANDROID_IOS, - EXCLUDE_IOS_TWO_COMPONENTS_DIFFERENT_FILES, -}; diff --git a/packages/react-native-codegen/src/generators/components/__tests__/GenerateComponentDescriptorH-test.js b/packages/react-native-codegen/src/generators/components/__tests__/GenerateComponentDescriptorH-test.js deleted file mode 100644 index 4074282cc57a..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/GenerateComponentDescriptorH-test.js +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const fixtures = require('../__test_fixtures__/fixtures.js'); -const generator = require('../GenerateComponentDescriptorH.js'); - -describe('GenerateComponentDescriptorH', () => { - Object.keys(fixtures) - .sort() - .forEach(fixtureName => { - const fixture = fixtures[fixtureName]; - - it(`can generate fixture ${fixtureName}`, () => { - expect(generator.generate(fixtureName, fixture)).toMatchSnapshot(); - }); - }); -}); diff --git a/packages/react-native-codegen/src/generators/components/__tests__/GenerateComponentHObjCpp-test.js b/packages/react-native-codegen/src/generators/components/__tests__/GenerateComponentHObjCpp-test.js deleted file mode 100644 index 0dbe605607ce..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/GenerateComponentHObjCpp-test.js +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const fixtures = require('../__test_fixtures__/fixtures.js'); -const generator = require('../GenerateComponentHObjCpp.js'); - -describe('GenerateComponentHObjCpp', () => { - Object.keys(fixtures) - .sort() - .forEach(fixtureName => { - const fixture = fixtures[fixtureName]; - - it(`can generate fixture ${fixtureName}`, () => { - expect(generator.generate(fixtureName, fixture)).toMatchSnapshot(); - }); - }); -}); diff --git a/packages/react-native-codegen/src/generators/components/__tests__/GenerateEventEmitterCpp-test.js b/packages/react-native-codegen/src/generators/components/__tests__/GenerateEventEmitterCpp-test.js deleted file mode 100644 index 11c6328ab729..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/GenerateEventEmitterCpp-test.js +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const fixtures = require('../__test_fixtures__/fixtures.js'); -const generator = require('../GenerateEventEmitterCpp.js'); - -describe('GenerateEventEmitterCpp', () => { - Object.keys(fixtures) - .sort() - .forEach(fixtureName => { - const fixture = fixtures[fixtureName]; - - it(`can generate fixture ${fixtureName}`, () => { - expect(generator.generate(fixtureName, fixture)).toMatchSnapshot(); - }); - }); -}); diff --git a/packages/react-native-codegen/src/generators/components/__tests__/GenerateEventEmitterH-test.js b/packages/react-native-codegen/src/generators/components/__tests__/GenerateEventEmitterH-test.js deleted file mode 100644 index 7709553b48a6..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/GenerateEventEmitterH-test.js +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const fixtures = require('../__test_fixtures__/fixtures.js'); -const generator = require('../GenerateEventEmitterH.js'); - -describe('GenerateEventEmitterH', () => { - Object.keys(fixtures) - .sort() - .forEach(fixtureName => { - const fixture = fixtures[fixtureName]; - - it(`can generate fixture ${fixtureName}`, () => { - expect(generator.generate(fixtureName, fixture)).toMatchSnapshot(); - }); - }); -}); diff --git a/packages/react-native-codegen/src/generators/components/__tests__/GeneratePropsCpp-test.js b/packages/react-native-codegen/src/generators/components/__tests__/GeneratePropsCpp-test.js deleted file mode 100644 index ff77b09ca49b..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/GeneratePropsCpp-test.js +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const fixtures = require('../__test_fixtures__/fixtures.js'); -const generator = require('../GeneratePropsCpp.js'); - -describe('GeneratePropsCpp', () => { - Object.keys(fixtures) - .sort() - .forEach(fixtureName => { - const fixture = fixtures[fixtureName]; - - it(`can generate fixture ${fixtureName}`, () => { - expect(generator.generate(fixtureName, fixture)).toMatchSnapshot(); - }); - }); -}); diff --git a/packages/react-native-codegen/src/generators/components/__tests__/GeneratePropsH-test.js b/packages/react-native-codegen/src/generators/components/__tests__/GeneratePropsH-test.js deleted file mode 100644 index 4e03ca4f8f68..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/GeneratePropsH-test.js +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const fixtures = require('../__test_fixtures__/fixtures.js'); -const generator = require('../GeneratePropsH.js'); - -describe('GeneratePropsH', () => { - Object.keys(fixtures) - .sort() - .forEach(fixtureName => { - const fixture = fixtures[fixtureName]; - - it(`can generate fixture ${fixtureName}`, () => { - expect(generator.generate(fixtureName, fixture)).toMatchSnapshot(); - }); - }); -}); diff --git a/packages/react-native-codegen/src/generators/components/__tests__/GeneratePropsJavaDelegate-test.js b/packages/react-native-codegen/src/generators/components/__tests__/GeneratePropsJavaDelegate-test.js deleted file mode 100644 index a4e310642d84..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/GeneratePropsJavaDelegate-test.js +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const fixtures = require('../__test_fixtures__/fixtures.js'); -const generator = require('../GeneratePropsJavaDelegate.js'); - -describe('GeneratePropsJavaDelegate', () => { - Object.keys(fixtures) - .sort() - .forEach(fixtureName => { - const fixture = fixtures[fixtureName]; - - it(`can generate fixture ${fixtureName}`, () => { - expect(generator.generate(fixtureName, fixture)).toMatchSnapshot(); - }); - }); -}); diff --git a/packages/react-native-codegen/src/generators/components/__tests__/GeneratePropsJavaInterface-test.js b/packages/react-native-codegen/src/generators/components/__tests__/GeneratePropsJavaInterface-test.js deleted file mode 100644 index 7f5af5f68c5d..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/GeneratePropsJavaInterface-test.js +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const fixtures = require('../__test_fixtures__/fixtures.js'); -const generator = require('../GeneratePropsJavaInterface.js'); - -describe('GeneratePropsJavaInterface', () => { - Object.keys(fixtures) - .sort() - .forEach(fixtureName => { - const fixture = fixtures[fixtureName]; - - it(`can generate fixture ${fixtureName}`, () => { - expect(generator.generate(fixtureName, fixture)).toMatchSnapshot(); - }); - }); -}); diff --git a/packages/react-native-codegen/src/generators/components/__tests__/GeneratePropsJavaPojo-test.js b/packages/react-native-codegen/src/generators/components/__tests__/GeneratePropsJavaPojo-test.js deleted file mode 100644 index f53552383403..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/GeneratePropsJavaPojo-test.js +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const fixtures = require('../__test_fixtures__/fixtures.js'); -const generator = require('../GeneratePropsJavaPojo'); - -describe('GeneratePropsJavaPojo', () => { - Object.keys(fixtures) - .sort() - .forEach(fixtureName => { - const fixture = fixtures[fixtureName]; - - it(`can generate fixture ${fixtureName}`, () => { - expect(generator.generate(fixtureName, fixture)).toMatchSnapshot(); - }); - }); -}); diff --git a/packages/react-native-codegen/src/generators/components/__tests__/GenerateShadowNodeCpp-test.js b/packages/react-native-codegen/src/generators/components/__tests__/GenerateShadowNodeCpp-test.js deleted file mode 100644 index 3acb8162fe65..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/GenerateShadowNodeCpp-test.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const fixtures = require('../__test_fixtures__/fixtures.js'); -const generator = require('../GenerateShadowNodeCpp.js'); - -describe('GenerateShadowNodeCpp', () => { - Object.keys(fixtures) - .sort() - .forEach(fixtureName => { - const fixture = fixtures[fixtureName]; - - it(`can generate fixture ${fixtureName}`, () => { - expect( - generator.generate(fixtureName, fixture, 'SampleSpec'), - ).toMatchSnapshot(); - }); - }); -}); diff --git a/packages/react-native-codegen/src/generators/components/__tests__/GenerateShadowNodeH-test.js b/packages/react-native-codegen/src/generators/components/__tests__/GenerateShadowNodeH-test.js deleted file mode 100644 index cafe5cf886f7..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/GenerateShadowNodeH-test.js +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const fixtures = require('../__test_fixtures__/fixtures.js'); -const generator = require('../GenerateShadowNodeH.js'); - -describe('GenerateShadowNodeH', () => { - Object.keys(fixtures) - .sort() - .forEach(fixtureName => { - const fixture = fixtures[fixtureName]; - - it(`can generate fixture ${fixtureName}`, () => { - expect(generator.generate(fixtureName, fixture)).toMatchSnapshot(); - }); - }); -}); diff --git a/packages/react-native-codegen/src/generators/components/__tests__/GenerateStateCpp-test.js b/packages/react-native-codegen/src/generators/components/__tests__/GenerateStateCpp-test.js deleted file mode 100644 index 1ccba96ba02d..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/GenerateStateCpp-test.js +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const fixtures = require('../__test_fixtures__/fixtures.js'); -const generator = require('../GenerateStateCpp.js'); - -describe('GenerateStateCpp', () => { - Object.keys(fixtures) - .sort() - .forEach(fixtureName => { - const fixture = fixtures[fixtureName]; - - it(`can generate fixture ${fixtureName}`, () => { - expect(generator.generate(fixtureName, fixture)).toMatchSnapshot(); - }); - }); -}); diff --git a/packages/react-native-codegen/src/generators/components/__tests__/GenerateStateH-test.js b/packages/react-native-codegen/src/generators/components/__tests__/GenerateStateH-test.js deleted file mode 100644 index 30b6b184b0e5..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/GenerateStateH-test.js +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const fixtures = require('../__test_fixtures__/fixtures.js'); -const generator = require('../GenerateStateH.js'); - -describe('GenerateStateH', () => { - Object.keys(fixtures) - .sort() - .forEach(fixtureName => { - const fixture = fixtures[fixtureName]; - - it(`can generate fixture ${fixtureName}`, () => { - expect(generator.generate(fixtureName, fixture)).toMatchSnapshot(); - }); - }); -}); diff --git a/packages/react-native-codegen/src/generators/components/__tests__/GenerateTests-test.js b/packages/react-native-codegen/src/generators/components/__tests__/GenerateTests-test.js deleted file mode 100644 index e40772a62b47..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/GenerateTests-test.js +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const fixtures = require('../__test_fixtures__/fixtures.js'); -const generator = require('../GenerateTests.js'); - -describe('GenerateTests', () => { - Object.keys(fixtures) - .sort() - .forEach(fixtureName => { - const fixture = fixtures[fixtureName]; - - it(`can generate fixture ${fixtureName}`, () => { - expect(generator.generate(fixtureName, fixture)).toMatchSnapshot(); - }); - }); -}); diff --git a/packages/react-native-codegen/src/generators/components/__tests__/GenerateThirdPartyFabricComponentsProviderH-test.js b/packages/react-native-codegen/src/generators/components/__tests__/GenerateThirdPartyFabricComponentsProviderH-test.js deleted file mode 100644 index f5cc5eac0d9e..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/GenerateThirdPartyFabricComponentsProviderH-test.js +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const fixtures = require('../__test_fixtures__/fixtures.js'); -const generator = require('../GenerateThirdPartyFabricComponentsProviderH.js'); - -describe('GenerateThirdPartyFabricComponentsProviderH', () => { - it(`can generate fixtures`, () => { - expect(generator.generate(fixtures)).toMatchSnapshot(); - }); -}); diff --git a/packages/react-native-codegen/src/generators/components/__tests__/GenerateThirdPartyFabricComponentsProviderObjCpp-test.js b/packages/react-native-codegen/src/generators/components/__tests__/GenerateThirdPartyFabricComponentsProviderObjCpp-test.js deleted file mode 100644 index 046c7c81ff29..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/GenerateThirdPartyFabricComponentsProviderObjCpp-test.js +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const fixtures = require('../__test_fixtures__/fixtures.js'); -const generator = require('../GenerateThirdPartyFabricComponentsProviderObjCpp.js'); - -describe('GenerateThirdPartyFabricComponentsProviderObjCpp', () => { - it(`can generate fixtures`, () => { - expect(generator.generate(fixtures)).toMatchSnapshot(); - }); -}); diff --git a/packages/react-native-codegen/src/generators/components/__tests__/GenerateViewConfigJs-test.js b/packages/react-native-codegen/src/generators/components/__tests__/GenerateViewConfigJs-test.js deleted file mode 100644 index e90bfe4e4a36..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/GenerateViewConfigJs-test.js +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const fixtures = require('../__test_fixtures__/fixtures.js'); -const generator = require('../GenerateViewConfigJs.js'); - -describe('GenerateViewConfigJs', () => { - Object.keys(fixtures) - .sort() - .forEach(fixtureName => { - const fixture = fixtures[fixtureName]; - - it(`can generate fixture ${fixtureName}`, () => { - expect(generator.generate(fixtureName, fixture)).toMatchSnapshot(); - }); - }); - - it('can generate fixture with a deprecated view config name', () => { - expect( - generator.generate('DEPRECATED_VIEW_CONFIG_NAME', { - modules: { - Component: { - type: 'Component', - components: { - NativeComponentName: { - paperComponentNameDeprecated: 'DeprecatedNativeComponentName', - extendsProps: [ - { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }, - ], - events: [], - props: [], - commands: [], - }, - }, - }, - }, - }), - ).toMatchSnapshot(); - }); -}); diff --git a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateComponentDescriptorH-test.js.snap b/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateComponentDescriptorH-test.js.snap deleted file mode 100644 index 7cf29170dec8..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateComponentDescriptorH-test.js.snap +++ /dev/null @@ -1,760 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GenerateComponentDescriptorH can generate fixture ARRAY_PROPS 1`] = ` -Map { - "ComponentDescriptors.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using ArrayPropsNativeComponentComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate fixture ARRAY_PROPS_WITH_NESTED_OBJECT 1`] = ` -Map { - "ComponentDescriptors.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using ArrayPropsNativeComponentComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate fixture BOOLEAN_PROP 1`] = ` -Map { - "ComponentDescriptors.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using BooleanPropNativeComponentComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate fixture COLOR_PROP 1`] = ` -Map { - "ComponentDescriptors.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using ColorPropNativeComponentComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate fixture COMMANDS 1`] = ` -Map { - "ComponentDescriptors.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using CommandNativeComponentComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate fixture COMMANDS_AND_PROPS 1`] = ` -Map { - "ComponentDescriptors.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using CommandNativeComponentComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate fixture DOUBLE_PROPS 1`] = ` -Map { - "ComponentDescriptors.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using DoublePropNativeComponentComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate fixture EVENT_NESTED_OBJECT_PROPS 1`] = ` -Map { - "ComponentDescriptors.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using EventsNestedObjectNativeComponentComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate fixture EVENT_PROPS 1`] = ` -Map { - "ComponentDescriptors.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using EventsNativeComponentComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate fixture EVENTS_WITH_PAPER_NAME 1`] = ` -Map { - "ComponentDescriptors.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate fixture EXCLUDE_ANDROID 1`] = ` -Map { - "ComponentDescriptors.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using ExcludedAndroidComponentComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate fixture EXCLUDE_ANDROID_IOS 1`] = ` -Map { - "ComponentDescriptors.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using ExcludedAndroidIosComponentComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate fixture EXCLUDE_IOS_TWO_COMPONENTS_DIFFERENT_FILES 1`] = ` -Map { - "ComponentDescriptors.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using ExcludedIosComponentComponentDescriptor = ConcreteComponentDescriptor; -using MultiFileIncludedNativeComponentComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate fixture FLOAT_PROPS 1`] = ` -Map { - "ComponentDescriptors.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using FloatPropNativeComponentComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate fixture IMAGE_PROP 1`] = ` -Map { - "ComponentDescriptors.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using ImagePropNativeComponentComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate fixture INSETS_PROP 1`] = ` -Map { - "ComponentDescriptors.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using InsetsPropNativeComponentComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate fixture INT32_ENUM_PROP 1`] = ` -Map { - "ComponentDescriptors.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using Int32EnumPropsNativeComponentComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate fixture INTEGER_PROPS 1`] = ` -Map { - "ComponentDescriptors.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using IntegerPropNativeComponentComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate fixture INTERFACE_ONLY 1`] = ` -Map { - "ComponentDescriptors.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate fixture MULTI_NATIVE_PROP 1`] = ` -Map { - "ComponentDescriptors.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using ImageColorPropNativeComponentComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate fixture NO_PROPS_NO_EVENTS 1`] = ` -Map { - "ComponentDescriptors.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using NoPropsNoEventsComponentComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate fixture OBJECT_PROPS 1`] = ` -Map { - "ComponentDescriptors.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using ObjectPropsComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate fixture POINT_PROP 1`] = ` -Map { - "ComponentDescriptors.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using PointPropNativeComponentComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate fixture STRING_ENUM_PROP 1`] = ` -Map { - "ComponentDescriptors.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using StringEnumPropsNativeComponentComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate fixture STRING_PROP 1`] = ` -Map { - "ComponentDescriptors.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using StringPropComponentComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate fixture TWO_COMPONENTS_DIFFERENT_FILES 1`] = ` -Map { - "ComponentDescriptors.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using MultiFile1NativeComponentComponentDescriptor = ConcreteComponentDescriptor; -using MultiFile2NativeComponentComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateComponentDescriptorH can generate fixture TWO_COMPONENTS_SAME_FILE 1`] = ` -Map { - "ComponentDescriptors.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateComponentDescriptorH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -using MultiComponent1NativeComponentComponentDescriptor = ConcreteComponentDescriptor; -using MultiComponent2NativeComponentComponentDescriptor = ConcreteComponentDescriptor; - -} // namespace react -} // namespace facebook -", -} -`; diff --git a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateComponentHObjCpp-test.js.snap b/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateComponentHObjCpp-test.js.snap deleted file mode 100644 index f7b45e6fc31e..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateComponentHObjCpp-test.js.snap +++ /dev/null @@ -1,818 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GenerateComponentHObjCpp can generate fixture ARRAY_PROPS 1`] = ` -Map { - "RCTComponentViewHelpers.h" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTArrayPropsNativeComponentViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate fixture ARRAY_PROPS_WITH_NESTED_OBJECT 1`] = ` -Map { - "RCTComponentViewHelpers.h" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTArrayPropsNativeComponentViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate fixture BOOLEAN_PROP 1`] = ` -Map { - "RCTComponentViewHelpers.h" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTBooleanPropNativeComponentViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate fixture COLOR_PROP 1`] = ` -Map { - "RCTComponentViewHelpers.h" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTColorPropNativeComponentViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate fixture COMMANDS 1`] = ` -Map { - "RCTComponentViewHelpers.h" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTCommandNativeComponentViewProtocol -- (void)flashScrollIndicators; -- (void)allTypes:(NSInteger)x y:(float)y z:(double)z message:(NSString *)message animated:(BOOL)animated; -@end - -RCT_EXTERN inline void RCTCommandNativeComponentHandleCommand( - id componentView, - NSString const *commandName, - NSArray const *args) -{ - if ([commandName isEqualToString:@\\"flashScrollIndicators\\"]) { -#if RCT_DEBUG - if ([args count] != 0) { - RCTLogError(@\\"%@ command %@ received %d arguments, expected %d.\\", @\\"CommandNativeComponent\\", commandName, (int)[args count], 0); - return; - } -#endif - - - - [componentView flashScrollIndicators]; - return; -} - -if ([commandName isEqualToString:@\\"allTypes\\"]) { -#if RCT_DEBUG - if ([args count] != 5) { - RCTLogError(@\\"%@ command %@ received %d arguments, expected %d.\\", @\\"CommandNativeComponent\\", commandName, (int)[args count], 5); - return; - } -#endif - - NSObject *arg0 = args[0]; -#if RCT_DEBUG - if (!RCTValidateTypeOfViewCommandArgument(arg0, [NSNumber class], @\\"number\\", @\\"CommandNativeComponent\\", commandName, @\\"1st\\")) { - return; - } -#endif - NSInteger x = [(NSNumber *)arg0 intValue]; - -NSObject *arg1 = args[1]; -#if RCT_DEBUG - if (!RCTValidateTypeOfViewCommandArgument(arg1, [NSNumber class], @\\"float\\", @\\"CommandNativeComponent\\", commandName, @\\"2nd\\")) { - return; - } -#endif - float y = [(NSNumber *)arg1 floatValue]; - -NSObject *arg2 = args[2]; -#if RCT_DEBUG - if (!RCTValidateTypeOfViewCommandArgument(arg2, [NSNumber class], @\\"double\\", @\\"CommandNativeComponent\\", commandName, @\\"3rd\\")) { - return; - } -#endif - double z = [(NSNumber *)arg2 doubleValue]; - -NSObject *arg3 = args[3]; -#if RCT_DEBUG - if (!RCTValidateTypeOfViewCommandArgument(arg3, [NSString class], @\\"string\\", @\\"CommandNativeComponent\\", commandName, @\\"4th\\")) { - return; - } -#endif - NSString * message = (NSString *)arg3; - -NSObject *arg4 = args[4]; -#if RCT_DEBUG - if (!RCTValidateTypeOfViewCommandArgument(arg4, [NSNumber class], @\\"boolean\\", @\\"CommandNativeComponent\\", commandName, @\\"5th\\")) { - return; - } -#endif - BOOL animated = [(NSNumber *)arg4 boolValue]; - - [componentView allTypes:x y:y z:z message:message animated:animated]; - return; -} - -#if RCT_DEBUG - RCTLogError(@\\"%@ received command %@, which is not a supported command.\\", @\\"CommandNativeComponent\\", commandName); -#endif -} - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate fixture COMMANDS_AND_PROPS 1`] = ` -Map { - "RCTComponentViewHelpers.h" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTCommandNativeComponentViewProtocol -- (void)handleRootTag:(double)rootTag; -- (void)hotspotUpdate:(NSInteger)x y:(NSInteger)y; -@end - -RCT_EXTERN inline void RCTCommandNativeComponentHandleCommand( - id componentView, - NSString const *commandName, - NSArray const *args) -{ - if ([commandName isEqualToString:@\\"handleRootTag\\"]) { -#if RCT_DEBUG - if ([args count] != 1) { - RCTLogError(@\\"%@ command %@ received %d arguments, expected %d.\\", @\\"CommandNativeComponent\\", commandName, (int)[args count], 1); - return; - } -#endif - - NSObject *arg0 = args[0]; -#if RCT_DEBUG - if (!RCTValidateTypeOfViewCommandArgument(arg0, [NSNumber class], @\\"double\\", @\\"CommandNativeComponent\\", commandName, @\\"1st\\")) { - return; - } -#endif - double rootTag = [(NSNumber *)arg0 doubleValue]; - - [componentView handleRootTag:rootTag]; - return; -} - -if ([commandName isEqualToString:@\\"hotspotUpdate\\"]) { -#if RCT_DEBUG - if ([args count] != 2) { - RCTLogError(@\\"%@ command %@ received %d arguments, expected %d.\\", @\\"CommandNativeComponent\\", commandName, (int)[args count], 2); - return; - } -#endif - - NSObject *arg0 = args[0]; -#if RCT_DEBUG - if (!RCTValidateTypeOfViewCommandArgument(arg0, [NSNumber class], @\\"number\\", @\\"CommandNativeComponent\\", commandName, @\\"1st\\")) { - return; - } -#endif - NSInteger x = [(NSNumber *)arg0 intValue]; - -NSObject *arg1 = args[1]; -#if RCT_DEBUG - if (!RCTValidateTypeOfViewCommandArgument(arg1, [NSNumber class], @\\"number\\", @\\"CommandNativeComponent\\", commandName, @\\"2nd\\")) { - return; - } -#endif - NSInteger y = [(NSNumber *)arg1 intValue]; - - [componentView hotspotUpdate:x y:y]; - return; -} - -#if RCT_DEBUG - RCTLogError(@\\"%@ received command %@, which is not a supported command.\\", @\\"CommandNativeComponent\\", commandName); -#endif -} - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate fixture DOUBLE_PROPS 1`] = ` -Map { - "RCTComponentViewHelpers.h" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTDoublePropNativeComponentViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate fixture EVENT_NESTED_OBJECT_PROPS 1`] = ` -Map { - "RCTComponentViewHelpers.h" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTEventsNestedObjectNativeComponentViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate fixture EVENT_PROPS 1`] = ` -Map { - "RCTComponentViewHelpers.h" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTEventsNativeComponentViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate fixture EVENTS_WITH_PAPER_NAME 1`] = ` -Map { - "RCTComponentViewHelpers.h" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTInterfaceOnlyComponentViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate fixture EXCLUDE_ANDROID 1`] = ` -Map { - "RCTComponentViewHelpers.h" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTExcludedAndroidComponentViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate fixture EXCLUDE_ANDROID_IOS 1`] = ` -Map { - "RCTComponentViewHelpers.h" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - - - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate fixture EXCLUDE_IOS_TWO_COMPONENTS_DIFFERENT_FILES 1`] = ` -Map { - "RCTComponentViewHelpers.h" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTMultiFileIncludedNativeComponentViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate fixture FLOAT_PROPS 1`] = ` -Map { - "RCTComponentViewHelpers.h" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTFloatPropNativeComponentViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate fixture IMAGE_PROP 1`] = ` -Map { - "RCTComponentViewHelpers.h" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTImagePropNativeComponentViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate fixture INSETS_PROP 1`] = ` -Map { - "RCTComponentViewHelpers.h" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTInsetsPropNativeComponentViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate fixture INT32_ENUM_PROP 1`] = ` -Map { - "RCTComponentViewHelpers.h" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTInt32EnumPropsNativeComponentViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate fixture INTEGER_PROPS 1`] = ` -Map { - "RCTComponentViewHelpers.h" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTIntegerPropNativeComponentViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate fixture INTERFACE_ONLY 1`] = ` -Map { - "RCTComponentViewHelpers.h" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTInterfaceOnlyComponentViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate fixture MULTI_NATIVE_PROP 1`] = ` -Map { - "RCTComponentViewHelpers.h" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTImageColorPropNativeComponentViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate fixture NO_PROPS_NO_EVENTS 1`] = ` -Map { - "RCTComponentViewHelpers.h" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTNoPropsNoEventsComponentViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate fixture OBJECT_PROPS 1`] = ` -Map { - "RCTComponentViewHelpers.h" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTObjectPropsViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate fixture POINT_PROP 1`] = ` -Map { - "RCTComponentViewHelpers.h" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTPointPropNativeComponentViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate fixture STRING_ENUM_PROP 1`] = ` -Map { - "RCTComponentViewHelpers.h" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTStringEnumPropsNativeComponentViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate fixture STRING_PROP 1`] = ` -Map { - "RCTComponentViewHelpers.h" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTStringPropComponentViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate fixture TWO_COMPONENTS_DIFFERENT_FILES 1`] = ` -Map { - "RCTComponentViewHelpers.h" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTMultiFile1NativeComponentViewProtocol - -@end - -@protocol RCTMultiFile2NativeComponentViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; - -exports[`GenerateComponentHObjCpp can generate fixture TWO_COMPONENTS_SAME_FILE 1`] = ` -Map { - "RCTComponentViewHelpers.h" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GenerateComponentHObjCpp.js -*/ - -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol RCTMultiComponent1NativeComponentViewProtocol - -@end - -@protocol RCTMultiComponent2NativeComponentViewProtocol - -@end - -NS_ASSUME_NONNULL_END", -} -`; diff --git a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateEventEmitterCpp-test.js.snap b/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateEventEmitterCpp-test.js.snap deleted file mode 100644 index 9c58425980fe..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateEventEmitterCpp-test.js.snap +++ /dev/null @@ -1,742 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GenerateEventEmitterCpp can generate fixture ARRAY_PROPS 1`] = ` -Map { - "EventEmitters.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate fixture ARRAY_PROPS_WITH_NESTED_OBJECT 1`] = ` -Map { - "EventEmitters.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate fixture BOOLEAN_PROP 1`] = ` -Map { - "EventEmitters.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate fixture COLOR_PROP 1`] = ` -Map { - "EventEmitters.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate fixture COMMANDS 1`] = ` -Map { - "EventEmitters.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate fixture COMMANDS_AND_PROPS 1`] = ` -Map { - "EventEmitters.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate fixture DOUBLE_PROPS 1`] = ` -Map { - "EventEmitters.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate fixture EVENT_NESTED_OBJECT_PROPS 1`] = ` -Map { - "EventEmitters.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - -void EventsNestedObjectNativeComponentEventEmitter::onChange(OnChange event) const { - dispatchEvent(\\"change\\", [event=std::move(event)](jsi::Runtime &runtime) { - auto payload = jsi::Object(runtime); - { - auto location = jsi::Object(runtime); - { - auto source = jsi::Object(runtime); - source.setProperty(runtime, \\"url\\", event.location.source.url); - - location.setProperty(runtime, \\"source\\", source); - } -location.setProperty(runtime, \\"x\\", event.location.x); -location.setProperty(runtime, \\"y\\", event.location.y); - - payload.setProperty(runtime, \\"location\\", location); - } - return payload; - }); -} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate fixture EVENT_PROPS 1`] = ` -Map { - "EventEmitters.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - -void EventsNativeComponentEventEmitter::onChange(OnChange event) const { - dispatchEvent(\\"change\\", [event=std::move(event)](jsi::Runtime &runtime) { - auto payload = jsi::Object(runtime); - payload.setProperty(runtime, \\"value\\", event.value); -payload.setProperty(runtime, \\"source\\", event.source); -payload.setProperty(runtime, \\"progress\\", event.progress); -payload.setProperty(runtime, \\"scale\\", event.scale); - return payload; - }); -} -void EventsNativeComponentEventEmitter::onEventDirect(OnEventDirect event) const { - dispatchEvent(\\"eventDirect\\", [event=std::move(event)](jsi::Runtime &runtime) { - auto payload = jsi::Object(runtime); - payload.setProperty(runtime, \\"value\\", event.value); - return payload; - }); -} -void EventsNativeComponentEventEmitter::onOrientationChange(OnOrientationChange event) const { - dispatchEvent(\\"orientationChange\\", [event=std::move(event)](jsi::Runtime &runtime) { - auto payload = jsi::Object(runtime); - payload.setProperty(runtime, \\"orientation\\", toString(event.orientation)); - return payload; - }); -} -void EventsNativeComponentEventEmitter::onEnd() const { - dispatchEvent(\\"end\\"); -} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate fixture EVENTS_WITH_PAPER_NAME 1`] = ` -Map { - "EventEmitters.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - -void InterfaceOnlyComponentEventEmitter::onChange(OnChange event) const { - dispatchEvent(\\"change\\", [event=std::move(event)](jsi::Runtime &runtime) { - auto payload = jsi::Object(runtime); - payload.setProperty(runtime, \\"value\\", event.value); - return payload; - }); -} -void InterfaceOnlyComponentEventEmitter::onDire tChange(OnDire tChange event) const { - dispatchEvent(\\"dire tChange\\", [event=std::move(event)](jsi::Runtime &runtime) { - auto payload = jsi::Object(runtime); - payload.setProperty(runtime, \\"value\\", event.value); - return payload; - }); -} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate fixture EXCLUDE_ANDROID 1`] = ` -Map { - "EventEmitters.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate fixture EXCLUDE_ANDROID_IOS 1`] = ` -Map { - "EventEmitters.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate fixture EXCLUDE_IOS_TWO_COMPONENTS_DIFFERENT_FILES 1`] = ` -Map { - "EventEmitters.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate fixture FLOAT_PROPS 1`] = ` -Map { - "EventEmitters.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate fixture IMAGE_PROP 1`] = ` -Map { - "EventEmitters.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate fixture INSETS_PROP 1`] = ` -Map { - "EventEmitters.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate fixture INT32_ENUM_PROP 1`] = ` -Map { - "EventEmitters.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate fixture INTEGER_PROPS 1`] = ` -Map { - "EventEmitters.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate fixture INTERFACE_ONLY 1`] = ` -Map { - "EventEmitters.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - -void InterfaceOnlyComponentEventEmitter::onChange(OnChange event) const { - dispatchEvent(\\"change\\", [event=std::move(event)](jsi::Runtime &runtime) { - auto payload = jsi::Object(runtime); - payload.setProperty(runtime, \\"value\\", event.value); - return payload; - }); -} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate fixture MULTI_NATIVE_PROP 1`] = ` -Map { - "EventEmitters.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate fixture NO_PROPS_NO_EVENTS 1`] = ` -Map { - "EventEmitters.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate fixture OBJECT_PROPS 1`] = ` -Map { - "EventEmitters.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate fixture POINT_PROP 1`] = ` -Map { - "EventEmitters.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate fixture STRING_ENUM_PROP 1`] = ` -Map { - "EventEmitters.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate fixture STRING_PROP 1`] = ` -Map { - "EventEmitters.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate fixture TWO_COMPONENTS_DIFFERENT_FILES 1`] = ` -Map { - "EventEmitters.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterCpp can generate fixture TWO_COMPONENTS_SAME_FILE 1`] = ` -Map { - "EventEmitters.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - - -} // namespace react -} // namespace facebook -", -} -`; diff --git a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateEventEmitterH-test.js.snap b/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateEventEmitterH-test.js.snap deleted file mode 100644 index fffed7043384..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateEventEmitterH-test.js.snap +++ /dev/null @@ -1,996 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GenerateEventEmitterH can generate fixture ARRAY_PROPS 1`] = ` -Map { - "EventEmitters.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT ArrayPropsNativeComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate fixture ARRAY_PROPS_WITH_NESTED_OBJECT 1`] = ` -Map { - "EventEmitters.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT ArrayPropsNativeComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate fixture BOOLEAN_PROP 1`] = ` -Map { - "EventEmitters.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT BooleanPropNativeComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate fixture COLOR_PROP 1`] = ` -Map { - "EventEmitters.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT ColorPropNativeComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate fixture COMMANDS 1`] = ` -Map { - "EventEmitters.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT CommandNativeComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate fixture COMMANDS_AND_PROPS 1`] = ` -Map { - "EventEmitters.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT CommandNativeComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate fixture DOUBLE_PROPS 1`] = ` -Map { - "EventEmitters.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT DoublePropNativeComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate fixture EVENT_NESTED_OBJECT_PROPS 1`] = ` -Map { - "EventEmitters.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT EventsNestedObjectNativeComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - struct OnChangeLocationSource { - std::string url; - }; - - struct OnChangeLocation { - OnChangeLocationSource source; - int x; - int y; - }; - - struct OnChange { - OnChangeLocation location; - }; - - void onChange(OnChange value) const; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate fixture EVENT_PROPS 1`] = ` -Map { - "EventEmitters.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT EventsNativeComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - struct OnChange { - bool value; - std::string source; - int progress; - Float scale; - }; - - struct OnEventDirect { - bool value; - }; - - enum class OnOrientationChangeOrientation { - Landscape, - Portrait - }; - - static char const *toString(const OnOrientationChangeOrientation value) { - switch (value) { - case OnOrientationChangeOrientation::Landscape: return \\"landscape\\"; - case OnOrientationChangeOrientation::Portrait: return \\"portrait\\"; - } - } - - struct OnOrientationChange { - OnOrientationChangeOrientation orientation; - }; - - void onChange(OnChange value) const; - - void onEventDirect(OnEventDirect value) const; - - void onOrientationChange(OnOrientationChange value) const; - - void onEnd() const; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate fixture EVENTS_WITH_PAPER_NAME 1`] = ` -Map { - "EventEmitters.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT InterfaceOnlyComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - struct OnChange { - bool value; - }; - - struct OnDire tChange { - bool value; - }; - - void onChange(OnChange value) const; - - void onDire tChange(OnDire tChange value) const; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate fixture EXCLUDE_ANDROID 1`] = ` -Map { - "EventEmitters.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT ExcludedAndroidComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate fixture EXCLUDE_ANDROID_IOS 1`] = ` -Map { - "EventEmitters.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT ExcludedAndroidIosComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate fixture EXCLUDE_IOS_TWO_COMPONENTS_DIFFERENT_FILES 1`] = ` -Map { - "EventEmitters.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT ExcludedIosComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; -class JSI_EXPORT MultiFileIncludedNativeComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate fixture FLOAT_PROPS 1`] = ` -Map { - "EventEmitters.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT FloatPropNativeComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate fixture IMAGE_PROP 1`] = ` -Map { - "EventEmitters.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT ImagePropNativeComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate fixture INSETS_PROP 1`] = ` -Map { - "EventEmitters.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT InsetsPropNativeComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate fixture INT32_ENUM_PROP 1`] = ` -Map { - "EventEmitters.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT Int32EnumPropsNativeComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate fixture INTEGER_PROPS 1`] = ` -Map { - "EventEmitters.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT IntegerPropNativeComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate fixture INTERFACE_ONLY 1`] = ` -Map { - "EventEmitters.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT InterfaceOnlyComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - struct OnChange { - bool value; - }; - - void onChange(OnChange value) const; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate fixture MULTI_NATIVE_PROP 1`] = ` -Map { - "EventEmitters.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT ImageColorPropNativeComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate fixture NO_PROPS_NO_EVENTS 1`] = ` -Map { - "EventEmitters.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT NoPropsNoEventsComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate fixture OBJECT_PROPS 1`] = ` -Map { - "EventEmitters.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT ObjectPropsEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate fixture POINT_PROP 1`] = ` -Map { - "EventEmitters.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT PointPropNativeComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate fixture STRING_ENUM_PROP 1`] = ` -Map { - "EventEmitters.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT StringEnumPropsNativeComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate fixture STRING_PROP 1`] = ` -Map { - "EventEmitters.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT StringPropComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate fixture TWO_COMPONENTS_DIFFERENT_FILES 1`] = ` -Map { - "EventEmitters.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT MultiFile1NativeComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; -class JSI_EXPORT MultiFile2NativeComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateEventEmitterH can generate fixture TWO_COMPONENTS_SAME_FILE 1`] = ` -Map { - "EventEmitters.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateEventEmitterH.js - */ -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT MultiComponent1NativeComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; -class JSI_EXPORT MultiComponent2NativeComponentEventEmitter : public ViewEventEmitter { - public: - using ViewEventEmitter::ViewEventEmitter; - - - - -}; - -} // namespace react -} // namespace facebook -", -} -`; diff --git a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GeneratePropsCpp-test.js.snap b/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GeneratePropsCpp-test.js.snap deleted file mode 100644 index 56ada8a6bffe..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GeneratePropsCpp-test.js.snap +++ /dev/null @@ -1,943 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GeneratePropsCpp can generate fixture ARRAY_PROPS 1`] = ` -Map { - "Props.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include -#include - -namespace facebook { -namespace react { - -ArrayPropsNativeComponentProps::ArrayPropsNativeComponentProps( - const PropsParserContext &context, - const ArrayPropsNativeComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - names(convertRawProp(context, rawProps, \\"names\\", sourceProps.names, {})), - disableds(convertRawProp(context, rawProps, \\"disableds\\", sourceProps.disableds, {})), - progress(convertRawProp(context, rawProps, \\"progress\\", sourceProps.progress, {})), - radii(convertRawProp(context, rawProps, \\"radii\\", sourceProps.radii, {})), - colors(convertRawProp(context, rawProps, \\"colors\\", sourceProps.colors, {})), - srcs(convertRawProp(context, rawProps, \\"srcs\\", sourceProps.srcs, {})), - points(convertRawProp(context, rawProps, \\"points\\", sourceProps.points, {})), - sizes(convertRawProp(context, rawProps, \\"sizes\\", sourceProps.sizes, {static_cast(ArrayPropsNativeComponentSizes::Small)})), - object(convertRawProp(context, rawProps, \\"object\\", sourceProps.object, {})), - array(convertRawProp(context, rawProps, \\"array\\", sourceProps.array, {})), - arrayOfArrayOfObject(convertRawProp(context, rawProps, \\"arrayOfArrayOfObject\\", sourceProps.arrayOfArrayOfObject, {})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate fixture ARRAY_PROPS_WITH_NESTED_OBJECT 1`] = ` -Map { - "Props.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -ArrayPropsNativeComponentProps::ArrayPropsNativeComponentProps( - const PropsParserContext &context, - const ArrayPropsNativeComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - nativePrimitives(convertRawProp(context, rawProps, \\"nativePrimitives\\", sourceProps.nativePrimitives, {})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate fixture BOOLEAN_PROP 1`] = ` -Map { - "Props.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -BooleanPropNativeComponentProps::BooleanPropNativeComponentProps( - const PropsParserContext &context, - const BooleanPropNativeComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - disabled(convertRawProp(context, rawProps, \\"disabled\\", sourceProps.disabled, {false})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate fixture COLOR_PROP 1`] = ` -Map { - "Props.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -ColorPropNativeComponentProps::ColorPropNativeComponentProps( - const PropsParserContext &context, - const ColorPropNativeComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - tintColor(convertRawProp(context, rawProps, \\"tintColor\\", sourceProps.tintColor, {})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate fixture COMMANDS 1`] = ` -Map { - "Props.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -CommandNativeComponentProps::CommandNativeComponentProps( - const PropsParserContext &context, - const CommandNativeComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps) - - - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate fixture COMMANDS_AND_PROPS 1`] = ` -Map { - "Props.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -CommandNativeComponentProps::CommandNativeComponentProps( - const PropsParserContext &context, - const CommandNativeComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - accessibilityHint(convertRawProp(context, rawProps, \\"accessibilityHint\\", sourceProps.accessibilityHint, {\\"\\"})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate fixture DOUBLE_PROPS 1`] = ` -Map { - "Props.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -DoublePropNativeComponentProps::DoublePropNativeComponentProps( - const PropsParserContext &context, - const DoublePropNativeComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - blurRadius(convertRawProp(context, rawProps, \\"blurRadius\\", sourceProps.blurRadius, {0.0})), - blurRadius2(convertRawProp(context, rawProps, \\"blurRadius2\\", sourceProps.blurRadius2, {0.001})), - blurRadius3(convertRawProp(context, rawProps, \\"blurRadius3\\", sourceProps.blurRadius3, {2.1})), - blurRadius4(convertRawProp(context, rawProps, \\"blurRadius4\\", sourceProps.blurRadius4, {0.0})), - blurRadius5(convertRawProp(context, rawProps, \\"blurRadius5\\", sourceProps.blurRadius5, {1.0})), - blurRadius6(convertRawProp(context, rawProps, \\"blurRadius6\\", sourceProps.blurRadius6, {0.0})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate fixture EVENT_NESTED_OBJECT_PROPS 1`] = ` -Map { - "Props.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -EventsNestedObjectNativeComponentProps::EventsNestedObjectNativeComponentProps( - const PropsParserContext &context, - const EventsNestedObjectNativeComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - disabled(convertRawProp(context, rawProps, \\"disabled\\", sourceProps.disabled, {false})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate fixture EVENT_PROPS 1`] = ` -Map { - "Props.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -EventsNativeComponentProps::EventsNativeComponentProps( - const PropsParserContext &context, - const EventsNativeComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - disabled(convertRawProp(context, rawProps, \\"disabled\\", sourceProps.disabled, {false})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate fixture EVENTS_WITH_PAPER_NAME 1`] = ` -Map { - "Props.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -InterfaceOnlyComponentProps::InterfaceOnlyComponentProps( - const PropsParserContext &context, - const InterfaceOnlyComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps) - - - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate fixture EXCLUDE_ANDROID 1`] = ` -Map { - "Props.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -ExcludedAndroidComponentProps::ExcludedAndroidComponentProps( - const PropsParserContext &context, - const ExcludedAndroidComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps) - - - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate fixture EXCLUDE_ANDROID_IOS 1`] = ` -Map { - "Props.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -ExcludedAndroidIosComponentProps::ExcludedAndroidIosComponentProps( - const PropsParserContext &context, - const ExcludedAndroidIosComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps) - - - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate fixture EXCLUDE_IOS_TWO_COMPONENTS_DIFFERENT_FILES 1`] = ` -Map { - "Props.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -ExcludedIosComponentProps::ExcludedIosComponentProps( - const PropsParserContext &context, - const ExcludedIosComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps) - - - {} -MultiFileIncludedNativeComponentProps::MultiFileIncludedNativeComponentProps( - const PropsParserContext &context, - const MultiFileIncludedNativeComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - disabled(convertRawProp(context, rawProps, \\"disabled\\", sourceProps.disabled, {true})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate fixture FLOAT_PROPS 1`] = ` -Map { - "Props.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -FloatPropNativeComponentProps::FloatPropNativeComponentProps( - const PropsParserContext &context, - const FloatPropNativeComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - blurRadius(convertRawProp(context, rawProps, \\"blurRadius\\", sourceProps.blurRadius, {0.0})), - blurRadius2(convertRawProp(context, rawProps, \\"blurRadius2\\", sourceProps.blurRadius2, {0.001})), - blurRadius3(convertRawProp(context, rawProps, \\"blurRadius3\\", sourceProps.blurRadius3, {2.1})), - blurRadius4(convertRawProp(context, rawProps, \\"blurRadius4\\", sourceProps.blurRadius4, {0.0})), - blurRadius5(convertRawProp(context, rawProps, \\"blurRadius5\\", sourceProps.blurRadius5, {1.0})), - blurRadius6(convertRawProp(context, rawProps, \\"blurRadius6\\", sourceProps.blurRadius6, {0.0})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate fixture IMAGE_PROP 1`] = ` -Map { - "Props.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include -#include - -namespace facebook { -namespace react { - -ImagePropNativeComponentProps::ImagePropNativeComponentProps( - const PropsParserContext &context, - const ImagePropNativeComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - thumbImage(convertRawProp(context, rawProps, \\"thumbImage\\", sourceProps.thumbImage, {})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate fixture INSETS_PROP 1`] = ` -Map { - "Props.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -InsetsPropNativeComponentProps::InsetsPropNativeComponentProps( - const PropsParserContext &context, - const InsetsPropNativeComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - contentInset(convertRawProp(context, rawProps, \\"contentInset\\", sourceProps.contentInset, {})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate fixture INT32_ENUM_PROP 1`] = ` -Map { - "Props.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -Int32EnumPropsNativeComponentProps::Int32EnumPropsNativeComponentProps( - const PropsParserContext &context, - const Int32EnumPropsNativeComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - maxInterval(convertRawProp(context, rawProps, \\"maxInterval\\", sourceProps.maxInterval, {Int32EnumPropsNativeComponentMaxInterval::MaxInterval0})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate fixture INTEGER_PROPS 1`] = ` -Map { - "Props.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -IntegerPropNativeComponentProps::IntegerPropNativeComponentProps( - const PropsParserContext &context, - const IntegerPropNativeComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - progress1(convertRawProp(context, rawProps, \\"progress1\\", sourceProps.progress1, {0})), - progress2(convertRawProp(context, rawProps, \\"progress2\\", sourceProps.progress2, {-1})), - progress3(convertRawProp(context, rawProps, \\"progress3\\", sourceProps.progress3, {10})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate fixture INTERFACE_ONLY 1`] = ` -Map { - "Props.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -InterfaceOnlyComponentProps::InterfaceOnlyComponentProps( - const PropsParserContext &context, - const InterfaceOnlyComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - accessibilityHint(convertRawProp(context, rawProps, \\"accessibilityHint\\", sourceProps.accessibilityHint, {\\"\\"})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate fixture MULTI_NATIVE_PROP 1`] = ` -Map { - "Props.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include -#include - -namespace facebook { -namespace react { - -ImageColorPropNativeComponentProps::ImageColorPropNativeComponentProps( - const PropsParserContext &context, - const ImageColorPropNativeComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - thumbImage(convertRawProp(context, rawProps, \\"thumbImage\\", sourceProps.thumbImage, {})), - color(convertRawProp(context, rawProps, \\"color\\", sourceProps.color, {})), - thumbTintColor(convertRawProp(context, rawProps, \\"thumbTintColor\\", sourceProps.thumbTintColor, {})), - point(convertRawProp(context, rawProps, \\"point\\", sourceProps.point, {})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate fixture NO_PROPS_NO_EVENTS 1`] = ` -Map { - "Props.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -NoPropsNoEventsComponentProps::NoPropsNoEventsComponentProps( - const PropsParserContext &context, - const NoPropsNoEventsComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps) - - - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate fixture OBJECT_PROPS 1`] = ` -Map { - "Props.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include -#include - -namespace facebook { -namespace react { - -ObjectPropsProps::ObjectPropsProps( - const PropsParserContext &context, - const ObjectPropsProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - objectProp(convertRawProp(context, rawProps, \\"objectProp\\", sourceProps.objectProp, {})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate fixture POINT_PROP 1`] = ` -Map { - "Props.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -PointPropNativeComponentProps::PointPropNativeComponentProps( - const PropsParserContext &context, - const PointPropNativeComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - startPoint(convertRawProp(context, rawProps, \\"startPoint\\", sourceProps.startPoint, {})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate fixture STRING_ENUM_PROP 1`] = ` -Map { - "Props.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -StringEnumPropsNativeComponentProps::StringEnumPropsNativeComponentProps( - const PropsParserContext &context, - const StringEnumPropsNativeComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - alignment(convertRawProp(context, rawProps, \\"alignment\\", sourceProps.alignment, {StringEnumPropsNativeComponentAlignment::Center})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate fixture STRING_PROP 1`] = ` -Map { - "Props.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -StringPropComponentProps::StringPropComponentProps( - const PropsParserContext &context, - const StringPropComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - accessibilityHint(convertRawProp(context, rawProps, \\"accessibilityHint\\", sourceProps.accessibilityHint, {\\"\\"})), - accessibilityRole(convertRawProp(context, rawProps, \\"accessibilityRole\\", sourceProps.accessibilityRole, {})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate fixture TWO_COMPONENTS_DIFFERENT_FILES 1`] = ` -Map { - "Props.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -MultiFile1NativeComponentProps::MultiFile1NativeComponentProps( - const PropsParserContext &context, - const MultiFile1NativeComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - disabled(convertRawProp(context, rawProps, \\"disabled\\", sourceProps.disabled, {false})) - {} -MultiFile2NativeComponentProps::MultiFile2NativeComponentProps( - const PropsParserContext &context, - const MultiFile2NativeComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - disabled(convertRawProp(context, rawProps, \\"disabled\\", sourceProps.disabled, {true})) - {} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsCpp can generate fixture TWO_COMPONENTS_SAME_FILE 1`] = ` -Map { - "Props.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsCpp.js - */ - -#include -#include -#include - -namespace facebook { -namespace react { - -MultiComponent1NativeComponentProps::MultiComponent1NativeComponentProps( - const PropsParserContext &context, - const MultiComponent1NativeComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - disabled(convertRawProp(context, rawProps, \\"disabled\\", sourceProps.disabled, {false})) - {} -MultiComponent2NativeComponentProps::MultiComponent2NativeComponentProps( - const PropsParserContext &context, - const MultiComponent2NativeComponentProps &sourceProps, - const RawProps &rawProps): ViewProps(context, sourceProps, rawProps), - - disabled(convertRawProp(context, rawProps, \\"disabled\\", sourceProps.disabled, {true})) - {} - -} // namespace react -} // namespace facebook -", -} -`; diff --git a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GeneratePropsH-test.js.snap b/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GeneratePropsH-test.js.snap deleted file mode 100644 index 30fd96825792..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GeneratePropsH-test.js.snap +++ /dev/null @@ -1,1515 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GeneratePropsH can generate fixture ARRAY_PROPS 1`] = ` -Map { - "Props.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -using ArrayPropsNativeComponentSizesMask = uint32_t; - -enum class ArrayPropsNativeComponentSizes: ArrayPropsNativeComponentSizesMask { - Small = 1 << 0, - Large = 1 << 1 -}; - -constexpr bool operator&( - ArrayPropsNativeComponentSizesMask const lhs, - enum ArrayPropsNativeComponentSizes const rhs) { - return lhs & static_cast(rhs); -} - -constexpr ArrayPropsNativeComponentSizesMask operator|( - ArrayPropsNativeComponentSizesMask const lhs, - enum ArrayPropsNativeComponentSizes const rhs) { - return lhs | static_cast(rhs); -} - -constexpr void operator|=( - ArrayPropsNativeComponentSizesMask &lhs, - enum ArrayPropsNativeComponentSizes const rhs) { - lhs = lhs | static_cast(rhs); -} - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ArrayPropsNativeComponentSizesMask &result) { - auto items = std::vector{value}; - for (const auto &item : items) { - if (item == \\"small\\") { - result |= ArrayPropsNativeComponentSizes::Small; - continue; - } - if (item == \\"large\\") { - result |= ArrayPropsNativeComponentSizes::Large; - continue; - } - abort(); - } -} - -static inline std::string toString(const ArrayPropsNativeComponentSizesMask &value) { - auto result = std::string{}; - auto separator = std::string{\\", \\"}; - - if (value & ArrayPropsNativeComponentSizes::Small) { - result += \\"small\\" + separator; - } - if (value & ArrayPropsNativeComponentSizes::Large) { - result += \\"large\\" + separator; - } - if (!result.empty()) { - result.erase(result.length() - separator.length()); - } - return result; -} -struct ArrayPropsNativeComponentObjectStruct { - std::string stringProp; -}; - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ArrayPropsNativeComponentObjectStruct &result) { - auto map = (butter::map)value; - - auto tmp_stringProp = map.find(\\"stringProp\\"); - if (tmp_stringProp != map.end()) { - fromRawValue(context, tmp_stringProp->second, result.stringProp); - } -} - -static inline std::string toString(const ArrayPropsNativeComponentObjectStruct &value) { - return \\"[Object ArrayPropsNativeComponentObjectStruct]\\"; -} - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, std::vector &result) { - auto items = (std::vector)value; - for (const auto &item : items) { - ArrayPropsNativeComponentObjectStruct newItem; - fromRawValue(context, item, newItem); - result.emplace_back(newItem); - } -} - - -struct ArrayPropsNativeComponentArrayObjectStruct { - std::string stringProp; -}; - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ArrayPropsNativeComponentArrayObjectStruct &result) { - auto map = (butter::map)value; - - auto tmp_stringProp = map.find(\\"stringProp\\"); - if (tmp_stringProp != map.end()) { - fromRawValue(context, tmp_stringProp->second, result.stringProp); - } -} - -static inline std::string toString(const ArrayPropsNativeComponentArrayObjectStruct &value) { - return \\"[Object ArrayPropsNativeComponentArrayObjectStruct]\\"; -} - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, std::vector &result) { - auto items = (std::vector)value; - for (const auto &item : items) { - ArrayPropsNativeComponentArrayObjectStruct newItem; - fromRawValue(context, item, newItem); - result.emplace_back(newItem); - } -} - - -struct ArrayPropsNativeComponentArrayStruct { - std::vector object; -}; - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ArrayPropsNativeComponentArrayStruct &result) { - auto map = (butter::map)value; - - auto tmp_object = map.find(\\"object\\"); - if (tmp_object != map.end()) { - fromRawValue(context, tmp_object->second, result.object); - } -} - -static inline std::string toString(const ArrayPropsNativeComponentArrayStruct &value) { - return \\"[Object ArrayPropsNativeComponentArrayStruct]\\"; -} - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, std::vector &result) { - auto items = (std::vector)value; - for (const auto &item : items) { - ArrayPropsNativeComponentArrayStruct newItem; - fromRawValue(context, item, newItem); - result.emplace_back(newItem); - } -} - - -struct ArrayPropsNativeComponentArrayOfArrayOfObjectStruct { - std::string stringProp; -}; - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ArrayPropsNativeComponentArrayOfArrayOfObjectStruct &result) { - auto map = (butter::map)value; - - auto tmp_stringProp = map.find(\\"stringProp\\"); - if (tmp_stringProp != map.end()) { - fromRawValue(context, tmp_stringProp->second, result.stringProp); - } -} - -static inline std::string toString(const ArrayPropsNativeComponentArrayOfArrayOfObjectStruct &value) { - return \\"[Object ArrayPropsNativeComponentArrayOfArrayOfObjectStruct]\\"; -} - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, std::vector> &result) { - auto items = (std::vector>)value; - for (const std::vector &item : items) { - auto nestedArray = std::vector{}; - for (const RawValue &nestedItem : item) { - ArrayPropsNativeComponentArrayOfArrayOfObjectStruct newItem; - fromRawValue(context, nestedItem, newItem); - nestedArray.emplace_back(newItem); - } - result.emplace_back(nestedArray); - } -} - -class JSI_EXPORT ArrayPropsNativeComponentProps final : public ViewProps { - public: - ArrayPropsNativeComponentProps() = default; - ArrayPropsNativeComponentProps(const PropsParserContext& context, const ArrayPropsNativeComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - std::vector names{}; - std::vector disableds{}; - std::vector progress{}; - std::vector radii{}; - std::vector colors{}; - std::vector srcs{}; - std::vector points{}; - ArrayPropsNativeComponentSizesMask sizes{static_cast(ArrayPropsNativeComponentSizes::Small)}; - std::vector object{}; - std::vector array{}; - std::vector> arrayOfArrayOfObject{}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate fixture ARRAY_PROPS_WITH_NESTED_OBJECT 1`] = ` -Map { - "Props.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -struct ArrayPropsNativeComponentNativePrimitivesStruct { - std::vector colors; - std::vector srcs; - std::vector points; -}; - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ArrayPropsNativeComponentNativePrimitivesStruct &result) { - auto map = (butter::map)value; - - auto tmp_colors = map.find(\\"colors\\"); - if (tmp_colors != map.end()) { - fromRawValue(context, tmp_colors->second, result.colors); - } - auto tmp_srcs = map.find(\\"srcs\\"); - if (tmp_srcs != map.end()) { - fromRawValue(context, tmp_srcs->second, result.srcs); - } - auto tmp_points = map.find(\\"points\\"); - if (tmp_points != map.end()) { - fromRawValue(context, tmp_points->second, result.points); - } -} - -static inline std::string toString(const ArrayPropsNativeComponentNativePrimitivesStruct &value) { - return \\"[Object ArrayPropsNativeComponentNativePrimitivesStruct]\\"; -} - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, std::vector &result) { - auto items = (std::vector)value; - for (const auto &item : items) { - ArrayPropsNativeComponentNativePrimitivesStruct newItem; - fromRawValue(context, item, newItem); - result.emplace_back(newItem); - } -} - -class JSI_EXPORT ArrayPropsNativeComponentProps final : public ViewProps { - public: - ArrayPropsNativeComponentProps() = default; - ArrayPropsNativeComponentProps(const PropsParserContext& context, const ArrayPropsNativeComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - std::vector nativePrimitives{}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate fixture BOOLEAN_PROP 1`] = ` -Map { - "Props.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT BooleanPropNativeComponentProps final : public ViewProps { - public: - BooleanPropNativeComponentProps() = default; - BooleanPropNativeComponentProps(const PropsParserContext& context, const BooleanPropNativeComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - bool disabled{false}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate fixture COLOR_PROP 1`] = ` -Map { - "Props.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT ColorPropNativeComponentProps final : public ViewProps { - public: - ColorPropNativeComponentProps() = default; - ColorPropNativeComponentProps(const PropsParserContext& context, const ColorPropNativeComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - SharedColor tintColor{}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate fixture COMMANDS 1`] = ` -Map { - "Props.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT CommandNativeComponentProps final : public ViewProps { - public: - CommandNativeComponentProps() = default; - CommandNativeComponentProps(const PropsParserContext& context, const CommandNativeComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate fixture COMMANDS_AND_PROPS 1`] = ` -Map { - "Props.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT CommandNativeComponentProps final : public ViewProps { - public: - CommandNativeComponentProps() = default; - CommandNativeComponentProps(const PropsParserContext& context, const CommandNativeComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - std::string accessibilityHint{\\"\\"}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate fixture DOUBLE_PROPS 1`] = ` -Map { - "Props.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT DoublePropNativeComponentProps final : public ViewProps { - public: - DoublePropNativeComponentProps() = default; - DoublePropNativeComponentProps(const PropsParserContext& context, const DoublePropNativeComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - double blurRadius{0.0}; - double blurRadius2{0.001}; - double blurRadius3{2.1}; - double blurRadius4{0.0}; - double blurRadius5{1.0}; - double blurRadius6{0.0}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate fixture EVENT_NESTED_OBJECT_PROPS 1`] = ` -Map { - "Props.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT EventsNestedObjectNativeComponentProps final : public ViewProps { - public: - EventsNestedObjectNativeComponentProps() = default; - EventsNestedObjectNativeComponentProps(const PropsParserContext& context, const EventsNestedObjectNativeComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - bool disabled{false}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate fixture EVENT_PROPS 1`] = ` -Map { - "Props.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT EventsNativeComponentProps final : public ViewProps { - public: - EventsNativeComponentProps() = default; - EventsNativeComponentProps(const PropsParserContext& context, const EventsNativeComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - bool disabled{false}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate fixture EVENTS_WITH_PAPER_NAME 1`] = ` -Map { - "Props.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT InterfaceOnlyComponentProps final : public ViewProps { - public: - InterfaceOnlyComponentProps() = default; - InterfaceOnlyComponentProps(const PropsParserContext& context, const InterfaceOnlyComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate fixture EXCLUDE_ANDROID 1`] = ` -Map { - "Props.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT ExcludedAndroidComponentProps final : public ViewProps { - public: - ExcludedAndroidComponentProps() = default; - ExcludedAndroidComponentProps(const PropsParserContext& context, const ExcludedAndroidComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate fixture EXCLUDE_ANDROID_IOS 1`] = ` -Map { - "Props.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT ExcludedAndroidIosComponentProps final : public ViewProps { - public: - ExcludedAndroidIosComponentProps() = default; - ExcludedAndroidIosComponentProps(const PropsParserContext& context, const ExcludedAndroidIosComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate fixture EXCLUDE_IOS_TWO_COMPONENTS_DIFFERENT_FILES 1`] = ` -Map { - "Props.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT ExcludedIosComponentProps final : public ViewProps { - public: - ExcludedIosComponentProps() = default; - ExcludedIosComponentProps(const PropsParserContext& context, const ExcludedIosComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - -}; - -class JSI_EXPORT MultiFileIncludedNativeComponentProps final : public ViewProps { - public: - MultiFileIncludedNativeComponentProps() = default; - MultiFileIncludedNativeComponentProps(const PropsParserContext& context, const MultiFileIncludedNativeComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - bool disabled{true}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate fixture FLOAT_PROPS 1`] = ` -Map { - "Props.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT FloatPropNativeComponentProps final : public ViewProps { - public: - FloatPropNativeComponentProps() = default; - FloatPropNativeComponentProps(const PropsParserContext& context, const FloatPropNativeComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - Float blurRadius{0.0}; - Float blurRadius2{0.001}; - Float blurRadius3{2.1}; - Float blurRadius4{0.0}; - Float blurRadius5{1.0}; - Float blurRadius6{0.0}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate fixture IMAGE_PROP 1`] = ` -Map { - "Props.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT ImagePropNativeComponentProps final : public ViewProps { - public: - ImagePropNativeComponentProps() = default; - ImagePropNativeComponentProps(const PropsParserContext& context, const ImagePropNativeComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - ImageSource thumbImage{}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate fixture INSETS_PROP 1`] = ` -Map { - "Props.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT InsetsPropNativeComponentProps final : public ViewProps { - public: - InsetsPropNativeComponentProps() = default; - InsetsPropNativeComponentProps(const PropsParserContext& context, const InsetsPropNativeComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - EdgeInsets contentInset{}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate fixture INT32_ENUM_PROP 1`] = ` -Map { - "Props.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -enum class Int32EnumPropsNativeComponentMaxInterval { MaxInterval0 = 0, MaxInterval1 = 1, MaxInterval2 = 2 }; - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, Int32EnumPropsNativeComponentMaxInterval &result) { - assert(value.hasType()); - auto integerValue = (int)value; - switch (integerValue) { - case 0: - result = Int32EnumPropsNativeComponentMaxInterval::MaxInterval0; - return; - case 1: - result = Int32EnumPropsNativeComponentMaxInterval::MaxInterval1; - return; - case 2: - result = Int32EnumPropsNativeComponentMaxInterval::MaxInterval2; - return; - } - abort(); -} - -static inline std::string toString(const Int32EnumPropsNativeComponentMaxInterval &value) { - switch (value) { - case Int32EnumPropsNativeComponentMaxInterval::MaxInterval0: return \\"0\\"; - case Int32EnumPropsNativeComponentMaxInterval::MaxInterval1: return \\"1\\"; - case Int32EnumPropsNativeComponentMaxInterval::MaxInterval2: return \\"2\\"; - } -} - -class JSI_EXPORT Int32EnumPropsNativeComponentProps final : public ViewProps { - public: - Int32EnumPropsNativeComponentProps() = default; - Int32EnumPropsNativeComponentProps(const PropsParserContext& context, const Int32EnumPropsNativeComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - Int32EnumPropsNativeComponentMaxInterval maxInterval{Int32EnumPropsNativeComponentMaxInterval::MaxInterval0}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate fixture INTEGER_PROPS 1`] = ` -Map { - "Props.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT IntegerPropNativeComponentProps final : public ViewProps { - public: - IntegerPropNativeComponentProps() = default; - IntegerPropNativeComponentProps(const PropsParserContext& context, const IntegerPropNativeComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - int progress1{0}; - int progress2{-1}; - int progress3{10}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate fixture INTERFACE_ONLY 1`] = ` -Map { - "Props.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT InterfaceOnlyComponentProps final : public ViewProps { - public: - InterfaceOnlyComponentProps() = default; - InterfaceOnlyComponentProps(const PropsParserContext& context, const InterfaceOnlyComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - std::string accessibilityHint{\\"\\"}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate fixture MULTI_NATIVE_PROP 1`] = ` -Map { - "Props.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT ImageColorPropNativeComponentProps final : public ViewProps { - public: - ImageColorPropNativeComponentProps() = default; - ImageColorPropNativeComponentProps(const PropsParserContext& context, const ImageColorPropNativeComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - ImageSource thumbImage{}; - SharedColor color{}; - SharedColor thumbTintColor{}; - Point point{}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate fixture NO_PROPS_NO_EVENTS 1`] = ` -Map { - "Props.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT NoPropsNoEventsComponentProps final : public ViewProps { - public: - NoPropsNoEventsComponentProps() = default; - NoPropsNoEventsComponentProps(const PropsParserContext& context, const NoPropsNoEventsComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate fixture OBJECT_PROPS 1`] = ` -Map { - "Props.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -enum class ObjectPropsStringEnumProp { Option1 }; - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ObjectPropsStringEnumProp &result) { - auto string = (std::string)value; - if (string == \\"option1\\") { result = ObjectPropsStringEnumProp::Option1; return; } - abort(); -} - -static inline std::string toString(const ObjectPropsStringEnumProp &value) { - switch (value) { - case ObjectPropsStringEnumProp::Option1: return \\"option1\\"; - } -} -enum class ObjectPropsIntEnumProp { IntEnumProp0 = 0 }; - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ObjectPropsIntEnumProp &result) { - assert(value.hasType()); - auto integerValue = (int)value; - switch (integerValue) { - case 0: - result = ObjectPropsIntEnumProp::IntEnumProp0; - return; - } - abort(); -} - -static inline std::string toString(const ObjectPropsIntEnumProp &value) { - switch (value) { - case ObjectPropsIntEnumProp::IntEnumProp0: return \\"0\\"; - } -} -struct ObjectPropsObjectPropObjectArrayPropStruct { - std::vector array; -}; - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ObjectPropsObjectPropObjectArrayPropStruct &result) { - auto map = (butter::map)value; - - auto tmp_array = map.find(\\"array\\"); - if (tmp_array != map.end()) { - fromRawValue(context, tmp_array->second, result.array); - } -} - -static inline std::string toString(const ObjectPropsObjectPropObjectArrayPropStruct &value) { - return \\"[Object ObjectPropsObjectPropObjectArrayPropStruct]\\"; -} - -struct ObjectPropsObjectPropObjectPrimitiveRequiredPropStruct { - ImageSource image; - SharedColor color; - Point point; -}; - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ObjectPropsObjectPropObjectPrimitiveRequiredPropStruct &result) { - auto map = (butter::map)value; - - auto tmp_image = map.find(\\"image\\"); - if (tmp_image != map.end()) { - fromRawValue(context, tmp_image->second, result.image); - } - auto tmp_color = map.find(\\"color\\"); - if (tmp_color != map.end()) { - fromRawValue(context, tmp_color->second, result.color); - } - auto tmp_point = map.find(\\"point\\"); - if (tmp_point != map.end()) { - fromRawValue(context, tmp_point->second, result.point); - } -} - -static inline std::string toString(const ObjectPropsObjectPropObjectPrimitiveRequiredPropStruct &value) { - return \\"[Object ObjectPropsObjectPropObjectPrimitiveRequiredPropStruct]\\"; -} - -struct ObjectPropsObjectPropNestedPropANestedPropBStruct { - std::string nestedPropC; -}; - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ObjectPropsObjectPropNestedPropANestedPropBStruct &result) { - auto map = (butter::map)value; - - auto tmp_nestedPropC = map.find(\\"nestedPropC\\"); - if (tmp_nestedPropC != map.end()) { - fromRawValue(context, tmp_nestedPropC->second, result.nestedPropC); - } -} - -static inline std::string toString(const ObjectPropsObjectPropNestedPropANestedPropBStruct &value) { - return \\"[Object ObjectPropsObjectPropNestedPropANestedPropBStruct]\\"; -} - -struct ObjectPropsObjectPropNestedPropAStruct { - ObjectPropsObjectPropNestedPropANestedPropBStruct nestedPropB; -}; - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ObjectPropsObjectPropNestedPropAStruct &result) { - auto map = (butter::map)value; - - auto tmp_nestedPropB = map.find(\\"nestedPropB\\"); - if (tmp_nestedPropB != map.end()) { - fromRawValue(context, tmp_nestedPropB->second, result.nestedPropB); - } -} - -static inline std::string toString(const ObjectPropsObjectPropNestedPropAStruct &value) { - return \\"[Object ObjectPropsObjectPropNestedPropAStruct]\\"; -} - -struct ObjectPropsObjectPropNestedArrayAsPropertyArrayPropStruct { - std::string stringProp; -}; - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ObjectPropsObjectPropNestedArrayAsPropertyArrayPropStruct &result) { - auto map = (butter::map)value; - - auto tmp_stringProp = map.find(\\"stringProp\\"); - if (tmp_stringProp != map.end()) { - fromRawValue(context, tmp_stringProp->second, result.stringProp); - } -} - -static inline std::string toString(const ObjectPropsObjectPropNestedArrayAsPropertyArrayPropStruct &value) { - return \\"[Object ObjectPropsObjectPropNestedArrayAsPropertyArrayPropStruct]\\"; -} - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, std::vector &result) { - auto items = (std::vector)value; - for (const auto &item : items) { - ObjectPropsObjectPropNestedArrayAsPropertyArrayPropStruct newItem; - fromRawValue(context, item, newItem); - result.emplace_back(newItem); - } -} - - -struct ObjectPropsObjectPropNestedArrayAsPropertyStruct { - std::vector arrayProp; -}; - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ObjectPropsObjectPropNestedArrayAsPropertyStruct &result) { - auto map = (butter::map)value; - - auto tmp_arrayProp = map.find(\\"arrayProp\\"); - if (tmp_arrayProp != map.end()) { - fromRawValue(context, tmp_arrayProp->second, result.arrayProp); - } -} - -static inline std::string toString(const ObjectPropsObjectPropNestedArrayAsPropertyStruct &value) { - return \\"[Object ObjectPropsObjectPropNestedArrayAsPropertyStruct]\\"; -} - -struct ObjectPropsObjectPropStruct { - std::string stringProp; - bool booleanProp; - Float floatProp; - int intProp; - ObjectPropsStringEnumProp stringEnumProp; - ObjectPropsIntEnumProp intEnumProp; - ObjectPropsObjectPropObjectArrayPropStruct objectArrayProp; - ObjectPropsObjectPropObjectPrimitiveRequiredPropStruct objectPrimitiveRequiredProp; - ObjectPropsObjectPropNestedPropAStruct nestedPropA; - ObjectPropsObjectPropNestedArrayAsPropertyStruct nestedArrayAsProperty; -}; - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ObjectPropsObjectPropStruct &result) { - auto map = (butter::map)value; - - auto tmp_stringProp = map.find(\\"stringProp\\"); - if (tmp_stringProp != map.end()) { - fromRawValue(context, tmp_stringProp->second, result.stringProp); - } - auto tmp_booleanProp = map.find(\\"booleanProp\\"); - if (tmp_booleanProp != map.end()) { - fromRawValue(context, tmp_booleanProp->second, result.booleanProp); - } - auto tmp_floatProp = map.find(\\"floatProp\\"); - if (tmp_floatProp != map.end()) { - fromRawValue(context, tmp_floatProp->second, result.floatProp); - } - auto tmp_intProp = map.find(\\"intProp\\"); - if (tmp_intProp != map.end()) { - fromRawValue(context, tmp_intProp->second, result.intProp); - } - auto tmp_stringEnumProp = map.find(\\"stringEnumProp\\"); - if (tmp_stringEnumProp != map.end()) { - fromRawValue(context, tmp_stringEnumProp->second, result.stringEnumProp); - } - auto tmp_intEnumProp = map.find(\\"intEnumProp\\"); - if (tmp_intEnumProp != map.end()) { - fromRawValue(context, tmp_intEnumProp->second, result.intEnumProp); - } - auto tmp_objectArrayProp = map.find(\\"objectArrayProp\\"); - if (tmp_objectArrayProp != map.end()) { - fromRawValue(context, tmp_objectArrayProp->second, result.objectArrayProp); - } - auto tmp_objectPrimitiveRequiredProp = map.find(\\"objectPrimitiveRequiredProp\\"); - if (tmp_objectPrimitiveRequiredProp != map.end()) { - fromRawValue(context, tmp_objectPrimitiveRequiredProp->second, result.objectPrimitiveRequiredProp); - } - auto tmp_nestedPropA = map.find(\\"nestedPropA\\"); - if (tmp_nestedPropA != map.end()) { - fromRawValue(context, tmp_nestedPropA->second, result.nestedPropA); - } - auto tmp_nestedArrayAsProperty = map.find(\\"nestedArrayAsProperty\\"); - if (tmp_nestedArrayAsProperty != map.end()) { - fromRawValue(context, tmp_nestedArrayAsProperty->second, result.nestedArrayAsProperty); - } -} - -static inline std::string toString(const ObjectPropsObjectPropStruct &value) { - return \\"[Object ObjectPropsObjectPropStruct]\\"; -} -class JSI_EXPORT ObjectPropsProps final : public ViewProps { - public: - ObjectPropsProps() = default; - ObjectPropsProps(const PropsParserContext& context, const ObjectPropsProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - ObjectPropsObjectPropStruct objectProp{}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate fixture POINT_PROP 1`] = ` -Map { - "Props.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT PointPropNativeComponentProps final : public ViewProps { - public: - PointPropNativeComponentProps() = default; - PointPropNativeComponentProps(const PropsParserContext& context, const PointPropNativeComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - Point startPoint{}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate fixture STRING_ENUM_PROP 1`] = ` -Map { - "Props.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -enum class StringEnumPropsNativeComponentAlignment { Top, Center, BottomRight }; - -static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, StringEnumPropsNativeComponentAlignment &result) { - auto string = (std::string)value; - if (string == \\"top\\") { result = StringEnumPropsNativeComponentAlignment::Top; return; } - if (string == \\"center\\") { result = StringEnumPropsNativeComponentAlignment::Center; return; } - if (string == \\"bottom-right\\") { result = StringEnumPropsNativeComponentAlignment::BottomRight; return; } - abort(); -} - -static inline std::string toString(const StringEnumPropsNativeComponentAlignment &value) { - switch (value) { - case StringEnumPropsNativeComponentAlignment::Top: return \\"top\\"; - case StringEnumPropsNativeComponentAlignment::Center: return \\"center\\"; - case StringEnumPropsNativeComponentAlignment::BottomRight: return \\"bottom-right\\"; - } -} - -class JSI_EXPORT StringEnumPropsNativeComponentProps final : public ViewProps { - public: - StringEnumPropsNativeComponentProps() = default; - StringEnumPropsNativeComponentProps(const PropsParserContext& context, const StringEnumPropsNativeComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - StringEnumPropsNativeComponentAlignment alignment{StringEnumPropsNativeComponentAlignment::Center}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate fixture STRING_PROP 1`] = ` -Map { - "Props.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT StringPropComponentProps final : public ViewProps { - public: - StringPropComponentProps() = default; - StringPropComponentProps(const PropsParserContext& context, const StringPropComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - std::string accessibilityHint{\\"\\"}; - std::string accessibilityRole{}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate fixture TWO_COMPONENTS_DIFFERENT_FILES 1`] = ` -Map { - "Props.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT MultiFile1NativeComponentProps final : public ViewProps { - public: - MultiFile1NativeComponentProps() = default; - MultiFile1NativeComponentProps(const PropsParserContext& context, const MultiFile1NativeComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - bool disabled{false}; -}; - -class JSI_EXPORT MultiFile2NativeComponentProps final : public ViewProps { - public: - MultiFile2NativeComponentProps() = default; - MultiFile2NativeComponentProps(const PropsParserContext& context, const MultiFile2NativeComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - bool disabled{true}; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GeneratePropsH can generate fixture TWO_COMPONENTS_SAME_FILE 1`] = ` -Map { - "Props.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GeneratePropsH.js - */ -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT MultiComponent1NativeComponentProps final : public ViewProps { - public: - MultiComponent1NativeComponentProps() = default; - MultiComponent1NativeComponentProps(const PropsParserContext& context, const MultiComponent1NativeComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - bool disabled{false}; -}; - -class JSI_EXPORT MultiComponent2NativeComponentProps final : public ViewProps { - public: - MultiComponent2NativeComponentProps() = default; - MultiComponent2NativeComponentProps(const PropsParserContext& context, const MultiComponent2NativeComponentProps &sourceProps, const RawProps &rawProps); - -#pragma mark - Props - - bool disabled{true}; -}; - -} // namespace react -} // namespace facebook -", -} -`; diff --git a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GeneratePropsJavaDelegate-test.js.snap b/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GeneratePropsJavaDelegate-test.js.snap deleted file mode 100644 index 6c5dd2dbb4f7..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GeneratePropsJavaDelegate-test.js.snap +++ /dev/null @@ -1,1115 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GeneratePropsJavaDelegate can generate fixture ARRAY_PROPS 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/ArrayPropsNativeComponentManagerDelegate.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.bridge.ReadableArray; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class ArrayPropsNativeComponentManagerDelegate & ArrayPropsNativeComponentManagerInterface> extends BaseViewManagerDelegate { - public ArrayPropsNativeComponentManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"names\\": - mViewManager.setNames(view, (ReadableArray) value); - break; - case \\"disableds\\": - mViewManager.setDisableds(view, (ReadableArray) value); - break; - case \\"progress\\": - mViewManager.setProgress(view, (ReadableArray) value); - break; - case \\"radii\\": - mViewManager.setRadii(view, (ReadableArray) value); - break; - case \\"colors\\": - mViewManager.setColors(view, (ReadableArray) value); - break; - case \\"srcs\\": - mViewManager.setSrcs(view, (ReadableArray) value); - break; - case \\"points\\": - mViewManager.setPoints(view, (ReadableArray) value); - break; - case \\"sizes\\": - mViewManager.setSizes(view, (ReadableArray) value); - break; - case \\"object\\": - mViewManager.setObject(view, (ReadableArray) value); - break; - case \\"array\\": - mViewManager.setArray(view, (ReadableArray) value); - break; - case \\"arrayOfArrayOfObject\\": - mViewManager.setArrayOfArrayOfObject(view, (ReadableArray) value); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate fixture ARRAY_PROPS_WITH_NESTED_OBJECT 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/ArrayPropsNativeComponentManagerDelegate.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.bridge.ReadableArray; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class ArrayPropsNativeComponentManagerDelegate & ArrayPropsNativeComponentManagerInterface> extends BaseViewManagerDelegate { - public ArrayPropsNativeComponentManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"nativePrimitives\\": - mViewManager.setNativePrimitives(view, (ReadableArray) value); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate fixture BOOLEAN_PROP 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/BooleanPropNativeComponentManagerDelegate.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class BooleanPropNativeComponentManagerDelegate & BooleanPropNativeComponentManagerInterface> extends BaseViewManagerDelegate { - public BooleanPropNativeComponentManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"disabled\\": - mViewManager.setDisabled(view, value == null ? false : (boolean) value); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate fixture COLOR_PROP 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/ColorPropNativeComponentManagerDelegate.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.bridge.ColorPropConverter; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class ColorPropNativeComponentManagerDelegate & ColorPropNativeComponentManagerInterface> extends BaseViewManagerDelegate { - public ColorPropNativeComponentManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"tintColor\\": - mViewManager.setTintColor(view, ColorPropConverter.getColor(value, view.getContext())); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate fixture COMMANDS 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/CommandNativeComponentManagerDelegate.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.bridge.ReadableArray; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class CommandNativeComponentManagerDelegate & CommandNativeComponentManagerInterface> extends BaseViewManagerDelegate { - public CommandNativeComponentManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - super.setProperty(view, propName, value); - } - - @Override - public void receiveCommand(T view, String commandName, ReadableArray args) { - switch (commandName) { - case \\"flashScrollIndicators\\": - mViewManager.flashScrollIndicators(view); - break; - case \\"allTypes\\": - mViewManager.allTypes(view, args.getInt(0), (float) args.getDouble(1), args.getDouble(2), args.getString(3), args.getBoolean(4)); - break; - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate fixture COMMANDS_AND_PROPS 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/CommandNativeComponentManagerDelegate.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.bridge.ReadableArray; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class CommandNativeComponentManagerDelegate & CommandNativeComponentManagerInterface> extends BaseViewManagerDelegate { - public CommandNativeComponentManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"accessibilityHint\\": - mViewManager.setAccessibilityHint(view, value == null ? \\"\\" : (String) value); - break; - default: - super.setProperty(view, propName, value); - } - } - - @Override - public void receiveCommand(T view, String commandName, ReadableArray args) { - switch (commandName) { - case \\"handleRootTag\\": - mViewManager.handleRootTag(view, args.getDouble(0)); - break; - case \\"hotspotUpdate\\": - mViewManager.hotspotUpdate(view, args.getInt(0), args.getInt(1)); - break; - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate fixture DOUBLE_PROPS 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/DoublePropNativeComponentManagerDelegate.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class DoublePropNativeComponentManagerDelegate & DoublePropNativeComponentManagerInterface> extends BaseViewManagerDelegate { - public DoublePropNativeComponentManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"blurRadius\\": - mViewManager.setBlurRadius(view, value == null ? Double.NaN : ((Double) value).doubleValue()); - break; - case \\"blurRadius2\\": - mViewManager.setBlurRadius2(view, value == null ? 0.001f : ((Double) value).doubleValue()); - break; - case \\"blurRadius3\\": - mViewManager.setBlurRadius3(view, value == null ? 2.1f : ((Double) value).doubleValue()); - break; - case \\"blurRadius4\\": - mViewManager.setBlurRadius4(view, value == null ? 0f : ((Double) value).doubleValue()); - break; - case \\"blurRadius5\\": - mViewManager.setBlurRadius5(view, value == null ? 1f : ((Double) value).doubleValue()); - break; - case \\"blurRadius6\\": - mViewManager.setBlurRadius6(view, value == null ? 0f : ((Double) value).doubleValue()); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate fixture EVENT_NESTED_OBJECT_PROPS 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/EventsNestedObjectNativeComponentManagerDelegate.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class EventsNestedObjectNativeComponentManagerDelegate & EventsNestedObjectNativeComponentManagerInterface> extends BaseViewManagerDelegate { - public EventsNestedObjectNativeComponentManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"disabled\\": - mViewManager.setDisabled(view, value == null ? false : (boolean) value); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate fixture EVENT_PROPS 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/EventsNativeComponentManagerDelegate.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class EventsNativeComponentManagerDelegate & EventsNativeComponentManagerInterface> extends BaseViewManagerDelegate { - public EventsNativeComponentManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"disabled\\": - mViewManager.setDisabled(view, value == null ? false : (boolean) value); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate fixture EVENTS_WITH_PAPER_NAME 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/InterfaceOnlyComponentManagerDelegate.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class InterfaceOnlyComponentManagerDelegate & InterfaceOnlyComponentManagerInterface> extends BaseViewManagerDelegate { - public InterfaceOnlyComponentManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - super.setProperty(view, propName, value); - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate fixture EXCLUDE_ANDROID 1`] = `Map {}`; - -exports[`GeneratePropsJavaDelegate can generate fixture EXCLUDE_ANDROID_IOS 1`] = `Map {}`; - -exports[`GeneratePropsJavaDelegate can generate fixture EXCLUDE_IOS_TWO_COMPONENTS_DIFFERENT_FILES 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/ExcludedIosComponentManagerDelegate.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class ExcludedIosComponentManagerDelegate & ExcludedIosComponentManagerInterface> extends BaseViewManagerDelegate { - public ExcludedIosComponentManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - super.setProperty(view, propName, value); - } -} -", - "java/com/facebook/react/viewmanagers/MultiFileIncludedNativeComponentManagerDelegate.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class MultiFileIncludedNativeComponentManagerDelegate & MultiFileIncludedNativeComponentManagerInterface> extends BaseViewManagerDelegate { - public MultiFileIncludedNativeComponentManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"disabled\\": - mViewManager.setDisabled(view, value == null ? true : (boolean) value); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate fixture FLOAT_PROPS 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/FloatPropNativeComponentManagerDelegate.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class FloatPropNativeComponentManagerDelegate & FloatPropNativeComponentManagerInterface> extends BaseViewManagerDelegate { - public FloatPropNativeComponentManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"blurRadius\\": - mViewManager.setBlurRadius(view, value == null ? Float.NaN : ((Double) value).floatValue()); - break; - case \\"blurRadius2\\": - mViewManager.setBlurRadius2(view, value == null ? 0.001f : ((Double) value).floatValue()); - break; - case \\"blurRadius3\\": - mViewManager.setBlurRadius3(view, value == null ? 2.1f : ((Double) value).floatValue()); - break; - case \\"blurRadius4\\": - mViewManager.setBlurRadius4(view, value == null ? 0f : ((Double) value).floatValue()); - break; - case \\"blurRadius5\\": - mViewManager.setBlurRadius5(view, value == null ? 1f : ((Double) value).floatValue()); - break; - case \\"blurRadius6\\": - mViewManager.setBlurRadius6(view, value == null ? 0f : ((Double) value).floatValue()); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate fixture IMAGE_PROP 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/ImagePropNativeComponentManagerDelegate.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class ImagePropNativeComponentManagerDelegate & ImagePropNativeComponentManagerInterface> extends BaseViewManagerDelegate { - public ImagePropNativeComponentManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"thumbImage\\": - mViewManager.setThumbImage(view, (ReadableMap) value); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate fixture INSETS_PROP 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/InsetsPropNativeComponentManagerDelegate.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class InsetsPropNativeComponentManagerDelegate & InsetsPropNativeComponentManagerInterface> extends BaseViewManagerDelegate { - public InsetsPropNativeComponentManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"contentInset\\": - mViewManager.setContentInset(view, (ReadableMap) value); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate fixture INT32_ENUM_PROP 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/Int32EnumPropsNativeComponentManagerDelegate.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class Int32EnumPropsNativeComponentManagerDelegate & Int32EnumPropsNativeComponentManagerInterface> extends BaseViewManagerDelegate { - public Int32EnumPropsNativeComponentManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"maxInterval\\": - mViewManager.setMaxInterval(view, value == null ? 0 : ((Double) value).intValue()); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate fixture INTEGER_PROPS 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/IntegerPropNativeComponentManagerDelegate.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class IntegerPropNativeComponentManagerDelegate & IntegerPropNativeComponentManagerInterface> extends BaseViewManagerDelegate { - public IntegerPropNativeComponentManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"progress1\\": - mViewManager.setProgress1(view, value == null ? 0 : ((Double) value).intValue()); - break; - case \\"progress2\\": - mViewManager.setProgress2(view, value == null ? -1 : ((Double) value).intValue()); - break; - case \\"progress3\\": - mViewManager.setProgress3(view, value == null ? 10 : ((Double) value).intValue()); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate fixture INTERFACE_ONLY 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/InterfaceOnlyComponentManagerDelegate.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class InterfaceOnlyComponentManagerDelegate & InterfaceOnlyComponentManagerInterface> extends BaseViewManagerDelegate { - public InterfaceOnlyComponentManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"accessibilityHint\\": - mViewManager.setAccessibilityHint(view, value == null ? \\"\\" : (String) value); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate fixture MULTI_NATIVE_PROP 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/ImageColorPropNativeComponentManagerDelegate.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.bridge.ColorPropConverter; -import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class ImageColorPropNativeComponentManagerDelegate & ImageColorPropNativeComponentManagerInterface> extends BaseViewManagerDelegate { - public ImageColorPropNativeComponentManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"thumbImage\\": - mViewManager.setThumbImage(view, (ReadableMap) value); - break; - case \\"color\\": - mViewManager.setColor(view, ColorPropConverter.getColor(value, view.getContext())); - break; - case \\"thumbTintColor\\": - mViewManager.setThumbTintColor(view, ColorPropConverter.getColor(value, view.getContext())); - break; - case \\"point\\": - mViewManager.setPoint(view, (ReadableMap) value); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate fixture NO_PROPS_NO_EVENTS 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/NoPropsNoEventsComponentManagerDelegate.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class NoPropsNoEventsComponentManagerDelegate & NoPropsNoEventsComponentManagerInterface> extends BaseViewManagerDelegate { - public NoPropsNoEventsComponentManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - super.setProperty(view, propName, value); - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate fixture OBJECT_PROPS 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/ObjectPropsManagerDelegate.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class ObjectPropsManagerDelegate & ObjectPropsManagerInterface> extends BaseViewManagerDelegate { - public ObjectPropsManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"objectProp\\": - mViewManager.setObjectProp(view, (ReadableMap) value); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate fixture POINT_PROP 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/PointPropNativeComponentManagerDelegate.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class PointPropNativeComponentManagerDelegate & PointPropNativeComponentManagerInterface> extends BaseViewManagerDelegate { - public PointPropNativeComponentManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"startPoint\\": - mViewManager.setStartPoint(view, (ReadableMap) value); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate fixture STRING_ENUM_PROP 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/StringEnumPropsNativeComponentManagerDelegate.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class StringEnumPropsNativeComponentManagerDelegate & StringEnumPropsNativeComponentManagerInterface> extends BaseViewManagerDelegate { - public StringEnumPropsNativeComponentManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"alignment\\": - mViewManager.setAlignment(view, (String) value); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate fixture STRING_PROP 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/StringPropComponentManagerDelegate.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class StringPropComponentManagerDelegate & StringPropComponentManagerInterface> extends BaseViewManagerDelegate { - public StringPropComponentManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"accessibilityHint\\": - mViewManager.setAccessibilityHint(view, value == null ? \\"\\" : (String) value); - break; - case \\"accessibilityRole\\": - mViewManager.setAccessibilityRole(view, value == null ? null : (String) value); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate fixture TWO_COMPONENTS_DIFFERENT_FILES 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/MultiFile1NativeComponentManagerDelegate.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class MultiFile1NativeComponentManagerDelegate & MultiFile1NativeComponentManagerInterface> extends BaseViewManagerDelegate { - public MultiFile1NativeComponentManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"disabled\\": - mViewManager.setDisabled(view, value == null ? false : (boolean) value); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", - "java/com/facebook/react/viewmanagers/MultiFile2NativeComponentManagerDelegate.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class MultiFile2NativeComponentManagerDelegate & MultiFile2NativeComponentManagerInterface> extends BaseViewManagerDelegate { - public MultiFile2NativeComponentManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"disabled\\": - mViewManager.setDisabled(view, value == null ? true : (boolean) value); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; - -exports[`GeneratePropsJavaDelegate can generate fixture TWO_COMPONENTS_SAME_FILE 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/MultiComponent1NativeComponentManagerDelegate.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class MultiComponent1NativeComponentManagerDelegate & MultiComponent1NativeComponentManagerInterface> extends BaseViewManagerDelegate { - public MultiComponent1NativeComponentManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"disabled\\": - mViewManager.setDisabled(view, value == null ? false : (boolean) value); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", - "java/com/facebook/react/viewmanagers/MultiComponent2NativeComponentManagerDelegate.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaDelegate.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.uimanager.BaseViewManagerDelegate; -import com.facebook.react.uimanager.BaseViewManagerInterface; - -public class MultiComponent2NativeComponentManagerDelegate & MultiComponent2NativeComponentManagerInterface> extends BaseViewManagerDelegate { - public MultiComponent2NativeComponentManagerDelegate(U viewManager) { - super(viewManager); - } - @Override - public void setProperty(T view, String propName, @Nullable Object value) { - switch (propName) { - case \\"disabled\\": - mViewManager.setDisabled(view, value == null ? true : (boolean) value); - break; - default: - super.setProperty(view, propName, value); - } - } -} -", -} -`; diff --git a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GeneratePropsJavaInterface-test.js.snap b/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GeneratePropsJavaInterface-test.js.snap deleted file mode 100644 index c4e652f19a38..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GeneratePropsJavaInterface-test.js.snap +++ /dev/null @@ -1,656 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GeneratePropsJavaInterface can generate fixture ARRAY_PROPS 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/ArrayPropsNativeComponentManagerInterface.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.bridge.ReadableArray; - -public interface ArrayPropsNativeComponentManagerInterface { - void setNames(T view, @Nullable ReadableArray value); - void setDisableds(T view, @Nullable ReadableArray value); - void setProgress(T view, @Nullable ReadableArray value); - void setRadii(T view, @Nullable ReadableArray value); - void setColors(T view, @Nullable ReadableArray value); - void setSrcs(T view, @Nullable ReadableArray value); - void setPoints(T view, @Nullable ReadableArray value); - void setSizes(T view, @Nullable ReadableArray value); - void setObject(T view, @Nullable ReadableArray value); - void setArray(T view, @Nullable ReadableArray value); - void setArrayOfArrayOfObject(T view, @Nullable ReadableArray value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate fixture ARRAY_PROPS_WITH_NESTED_OBJECT 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/ArrayPropsNativeComponentManagerInterface.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.bridge.ReadableArray; - -public interface ArrayPropsNativeComponentManagerInterface { - void setNativePrimitives(T view, @Nullable ReadableArray value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate fixture BOOLEAN_PROP 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/BooleanPropNativeComponentManagerInterface.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; - -public interface BooleanPropNativeComponentManagerInterface { - void setDisabled(T view, boolean value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate fixture COLOR_PROP 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/ColorPropNativeComponentManagerInterface.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; - -public interface ColorPropNativeComponentManagerInterface { - void setTintColor(T view, @Nullable Integer value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate fixture COMMANDS 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/CommandNativeComponentManagerInterface.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; - -public interface CommandNativeComponentManagerInterface { - // No props - void flashScrollIndicators(T view); - void allTypes(T view, int x, float y, double z, String message, boolean animated); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate fixture COMMANDS_AND_PROPS 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/CommandNativeComponentManagerInterface.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; - -public interface CommandNativeComponentManagerInterface { - void setAccessibilityHint(T view, @Nullable String value); - void handleRootTag(T view, double rootTag); - void hotspotUpdate(T view, int x, int y); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate fixture DOUBLE_PROPS 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/DoublePropNativeComponentManagerInterface.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; - -public interface DoublePropNativeComponentManagerInterface { - void setBlurRadius(T view, double value); - void setBlurRadius2(T view, double value); - void setBlurRadius3(T view, double value); - void setBlurRadius4(T view, double value); - void setBlurRadius5(T view, double value); - void setBlurRadius6(T view, double value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate fixture EVENT_NESTED_OBJECT_PROPS 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/EventsNestedObjectNativeComponentManagerInterface.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; - -public interface EventsNestedObjectNativeComponentManagerInterface { - void setDisabled(T view, boolean value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate fixture EVENT_PROPS 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/EventsNativeComponentManagerInterface.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; - -public interface EventsNativeComponentManagerInterface { - void setDisabled(T view, boolean value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate fixture EVENTS_WITH_PAPER_NAME 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/InterfaceOnlyComponentManagerInterface.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; - -public interface InterfaceOnlyComponentManagerInterface { - // No props -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate fixture EXCLUDE_ANDROID 1`] = `Map {}`; - -exports[`GeneratePropsJavaInterface can generate fixture EXCLUDE_ANDROID_IOS 1`] = `Map {}`; - -exports[`GeneratePropsJavaInterface can generate fixture EXCLUDE_IOS_TWO_COMPONENTS_DIFFERENT_FILES 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/ExcludedIosComponentManagerInterface.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; - -public interface ExcludedIosComponentManagerInterface { - // No props -} -", - "java/com/facebook/react/viewmanagers/MultiFileIncludedNativeComponentManagerInterface.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; - -public interface MultiFileIncludedNativeComponentManagerInterface { - void setDisabled(T view, boolean value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate fixture FLOAT_PROPS 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/FloatPropNativeComponentManagerInterface.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; - -public interface FloatPropNativeComponentManagerInterface { - void setBlurRadius(T view, float value); - void setBlurRadius2(T view, float value); - void setBlurRadius3(T view, float value); - void setBlurRadius4(T view, float value); - void setBlurRadius5(T view, float value); - void setBlurRadius6(T view, float value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate fixture IMAGE_PROP 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/ImagePropNativeComponentManagerInterface.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.bridge.ReadableMap; - -public interface ImagePropNativeComponentManagerInterface { - void setThumbImage(T view, @Nullable ReadableMap value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate fixture INSETS_PROP 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/InsetsPropNativeComponentManagerInterface.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.bridge.ReadableMap; - -public interface InsetsPropNativeComponentManagerInterface { - void setContentInset(T view, @Nullable ReadableMap value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate fixture INT32_ENUM_PROP 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/Int32EnumPropsNativeComponentManagerInterface.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; - -public interface Int32EnumPropsNativeComponentManagerInterface { - void setMaxInterval(T view, @Nullable Integer value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate fixture INTEGER_PROPS 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/IntegerPropNativeComponentManagerInterface.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; - -public interface IntegerPropNativeComponentManagerInterface { - void setProgress1(T view, int value); - void setProgress2(T view, int value); - void setProgress3(T view, int value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate fixture INTERFACE_ONLY 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/InterfaceOnlyComponentManagerInterface.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; - -public interface InterfaceOnlyComponentManagerInterface { - void setAccessibilityHint(T view, @Nullable String value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate fixture MULTI_NATIVE_PROP 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/ImageColorPropNativeComponentManagerInterface.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.bridge.ReadableMap; - -public interface ImageColorPropNativeComponentManagerInterface { - void setThumbImage(T view, @Nullable ReadableMap value); - void setColor(T view, @Nullable Integer value); - void setThumbTintColor(T view, @Nullable Integer value); - void setPoint(T view, @Nullable ReadableMap value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate fixture NO_PROPS_NO_EVENTS 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/NoPropsNoEventsComponentManagerInterface.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; - -public interface NoPropsNoEventsComponentManagerInterface { - // No props -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate fixture OBJECT_PROPS 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/ObjectPropsManagerInterface.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.bridge.ReadableMap; - -public interface ObjectPropsManagerInterface { - void setObjectProp(T view, @Nullable ReadableMap value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate fixture POINT_PROP 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/PointPropNativeComponentManagerInterface.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; -import com.facebook.react.bridge.ReadableMap; - -public interface PointPropNativeComponentManagerInterface { - void setStartPoint(T view, @Nullable ReadableMap value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate fixture STRING_ENUM_PROP 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/StringEnumPropsNativeComponentManagerInterface.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; - -public interface StringEnumPropsNativeComponentManagerInterface { - void setAlignment(T view, @Nullable String value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate fixture STRING_PROP 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/StringPropComponentManagerInterface.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; -import androidx.annotation.Nullable; - -public interface StringPropComponentManagerInterface { - void setAccessibilityHint(T view, @Nullable String value); - void setAccessibilityRole(T view, @Nullable String value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate fixture TWO_COMPONENTS_DIFFERENT_FILES 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/MultiFile1NativeComponentManagerInterface.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; - -public interface MultiFile1NativeComponentManagerInterface { - void setDisabled(T view, boolean value); -} -", - "java/com/facebook/react/viewmanagers/MultiFile2NativeComponentManagerInterface.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; - -public interface MultiFile2NativeComponentManagerInterface { - void setDisabled(T view, boolean value); -} -", -} -`; - -exports[`GeneratePropsJavaInterface can generate fixture TWO_COMPONENTS_SAME_FILE 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/MultiComponent1NativeComponentManagerInterface.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; - -public interface MultiComponent1NativeComponentManagerInterface { - void setDisabled(T view, boolean value); -} -", - "java/com/facebook/react/viewmanagers/MultiComponent2NativeComponentManagerInterface.java" => "/** -* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). -* -* Do not edit this file as changes may cause incorrect behavior and will be lost -* once the code is regenerated. -* -* @generated by codegen project: GeneratePropsJavaInterface.js -*/ - -package com.facebook.react.viewmanagers; - -import android.view.View; - -public interface MultiComponent2NativeComponentManagerInterface { - void setDisabled(T view, boolean value); -} -", -} -`; diff --git a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GeneratePropsJavaPojo-test.js.snap b/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GeneratePropsJavaPojo-test.js.snap deleted file mode 100644 index 9cb2b17fe2b3..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GeneratePropsJavaPojo-test.js.snap +++ /dev/null @@ -1,1223 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GeneratePropsJavaPojo can generate fixture ARRAY_PROPS 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/Slider/ArrayPropsNativeComponentPropsObjectElement.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.Slider; - -import androidx.annotation.Nullable; -import com.facebook.proguard.annotations.DoNotStrip; - -@DoNotStrip -public class ArrayPropsNativeComponentPropsObjectElement { - private @Nullable String mStringProp; - @DoNotStrip - public @Nullable String getStringProp() { - return mStringProp; - } -} -", - "java/com/facebook/react/viewmanagers/Slider/ArrayPropsNativeComponentPropsArrayElementObjectElement.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.Slider; - -import androidx.annotation.Nullable; -import com.facebook.proguard.annotations.DoNotStrip; - -@DoNotStrip -public class ArrayPropsNativeComponentPropsArrayElementObjectElement { - private @Nullable String mStringProp; - @DoNotStrip - public @Nullable String getStringProp() { - return mStringProp; - } -} -", - "java/com/facebook/react/viewmanagers/Slider/ArrayPropsNativeComponentPropsArrayElement.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.Slider; - -import com.facebook.proguard.annotations.DoNotStrip; -import java.util.ArrayList; - -@DoNotStrip -public class ArrayPropsNativeComponentPropsArrayElement { - private ArrayList mObject; - @DoNotStrip - public ArrayList getObject() { - return mObject; - } -} -", - "java/com/facebook/react/viewmanagers/Slider/ArrayPropsNativeComponentPropsArrayOfArrayOfObjectElementElement.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.Slider; - -import androidx.annotation.Nullable; -import com.facebook.proguard.annotations.DoNotStrip; - -@DoNotStrip -public class ArrayPropsNativeComponentPropsArrayOfArrayOfObjectElementElement { - private @Nullable String mStringProp; - @DoNotStrip - public @Nullable String getStringProp() { - return mStringProp; - } -} -", - "java/com/facebook/react/viewmanagers/Slider/ArrayPropsNativeComponentProps.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.Slider; - -import com.facebook.proguard.annotations.DoNotStrip; -import com.facebook.react.bridge.ReadableMap; -import java.util.ArrayList; - -@DoNotStrip -public class ArrayPropsNativeComponentProps { - private ArrayList mNames; - private ArrayList mDisableds; - private ArrayList mProgress; - private ArrayList mRadii; - private ArrayList mColors; - private ArrayList mSrcs; - private ArrayList mPoints; - private ArrayList mSizes; - private ArrayList mObject; - private ArrayList mArray; - private ArrayList> mArrayOfArrayOfObject; - @DoNotStrip - public ArrayList getNames() { - return mNames; - } - @DoNotStrip - public ArrayList getDisableds() { - return mDisableds; - } - @DoNotStrip - public ArrayList getProgress() { - return mProgress; - } - @DoNotStrip - public ArrayList getRadii() { - return mRadii; - } - @DoNotStrip - public ArrayList getColors() { - return mColors; - } - @DoNotStrip - public ArrayList getSrcs() { - return mSrcs; - } - @DoNotStrip - public ArrayList getPoints() { - return mPoints; - } - @DoNotStrip - public ArrayList getSizes() { - return mSizes; - } - @DoNotStrip - public ArrayList getObject() { - return mObject; - } - @DoNotStrip - public ArrayList getArray() { - return mArray; - } - @DoNotStrip - public ArrayList> getArrayOfArrayOfObject() { - return mArrayOfArrayOfObject; - } -} -", -} -`; - -exports[`GeneratePropsJavaPojo can generate fixture ARRAY_PROPS_WITH_NESTED_OBJECT 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/Slider/ArrayPropsNativeComponentPropsNativePrimitivesElement.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.Slider; - -import com.facebook.proguard.annotations.DoNotStrip; -import com.facebook.react.bridge.ReadableMap; -import java.util.ArrayList; - -@DoNotStrip -public class ArrayPropsNativeComponentPropsNativePrimitivesElement { - private ArrayList mColors; - private ArrayList mSrcs; - private ArrayList mPoints; - @DoNotStrip - public ArrayList getColors() { - return mColors; - } - @DoNotStrip - public ArrayList getSrcs() { - return mSrcs; - } - @DoNotStrip - public ArrayList getPoints() { - return mPoints; - } -} -", - "java/com/facebook/react/viewmanagers/Slider/ArrayPropsNativeComponentProps.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.Slider; - -import com.facebook.proguard.annotations.DoNotStrip; -import java.util.ArrayList; - -@DoNotStrip -public class ArrayPropsNativeComponentProps { - private ArrayList mNativePrimitives; - @DoNotStrip - public ArrayList getNativePrimitives() { - return mNativePrimitives; - } -} -", -} -`; - -exports[`GeneratePropsJavaPojo can generate fixture BOOLEAN_PROP 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/Switch/BooleanPropNativeComponentProps.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.Switch; - -import com.facebook.proguard.annotations.DoNotStrip; - -@DoNotStrip -public class BooleanPropNativeComponentProps { - private boolean mDisabled; - @DoNotStrip - public boolean getDisabled() { - return mDisabled; - } -} -", -} -`; - -exports[`GeneratePropsJavaPojo can generate fixture COLOR_PROP 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/Switch/ColorPropNativeComponentProps.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.Switch; - -import androidx.annotation.Nullable; -import com.facebook.proguard.annotations.DoNotStrip; - -@DoNotStrip -public class ColorPropNativeComponentProps { - private @Nullable Integer mTintColor; - @DoNotStrip - public @Nullable Integer getTintColor() { - return mTintColor; - } -} -", -} -`; - -exports[`GeneratePropsJavaPojo can generate fixture COMMANDS 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/Switch/CommandNativeComponentProps.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.Switch; - -import com.facebook.proguard.annotations.DoNotStrip; - -@DoNotStrip -public class CommandNativeComponentProps { - - -} -", -} -`; - -exports[`GeneratePropsJavaPojo can generate fixture COMMANDS_AND_PROPS 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/Switch/CommandNativeComponentProps.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.Switch; - -import androidx.annotation.Nullable; -import com.facebook.proguard.annotations.DoNotStrip; - -@DoNotStrip -public class CommandNativeComponentProps { - private @Nullable String mAccessibilityHint; - @DoNotStrip - public @Nullable String getAccessibilityHint() { - return mAccessibilityHint; - } -} -", -} -`; - -exports[`GeneratePropsJavaPojo can generate fixture DOUBLE_PROPS 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/Switch/DoublePropNativeComponentProps.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.Switch; - -import com.facebook.proguard.annotations.DoNotStrip; - -@DoNotStrip -public class DoublePropNativeComponentProps { - private double mBlurRadius; - private double mBlurRadius2; - private double mBlurRadius3; - private double mBlurRadius4; - private double mBlurRadius5; - private double mBlurRadius6; - @DoNotStrip - public double getBlurRadius() { - return mBlurRadius; - } - @DoNotStrip - public double getBlurRadius2() { - return mBlurRadius2; - } - @DoNotStrip - public double getBlurRadius3() { - return mBlurRadius3; - } - @DoNotStrip - public double getBlurRadius4() { - return mBlurRadius4; - } - @DoNotStrip - public double getBlurRadius5() { - return mBlurRadius5; - } - @DoNotStrip - public double getBlurRadius6() { - return mBlurRadius6; - } -} -", -} -`; - -exports[`GeneratePropsJavaPojo can generate fixture EVENT_NESTED_OBJECT_PROPS 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/Switch/EventsNestedObjectNativeComponentProps.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.Switch; - -import com.facebook.proguard.annotations.DoNotStrip; - -@DoNotStrip -public class EventsNestedObjectNativeComponentProps { - private boolean mDisabled; - @DoNotStrip - public boolean getDisabled() { - return mDisabled; - } -} -", -} -`; - -exports[`GeneratePropsJavaPojo can generate fixture EVENT_PROPS 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/Switch/EventsNativeComponentProps.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.Switch; - -import com.facebook.proguard.annotations.DoNotStrip; - -@DoNotStrip -public class EventsNativeComponentProps { - private boolean mDisabled; - @DoNotStrip - public boolean getDisabled() { - return mDisabled; - } -} -", -} -`; - -exports[`GeneratePropsJavaPojo can generate fixture EVENTS_WITH_PAPER_NAME 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/Switch/InterfaceOnlyComponentProps.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.Switch; - -import com.facebook.proguard.annotations.DoNotStrip; - -@DoNotStrip -public class InterfaceOnlyComponentProps { - - -} -", -} -`; - -exports[`GeneratePropsJavaPojo can generate fixture EXCLUDE_ANDROID 1`] = `Map {}`; - -exports[`GeneratePropsJavaPojo can generate fixture EXCLUDE_ANDROID_IOS 1`] = `Map {}`; - -exports[`GeneratePropsJavaPojo can generate fixture EXCLUDE_IOS_TWO_COMPONENTS_DIFFERENT_FILES 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/ComponentFile1/ExcludedIosComponentProps.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.ComponentFile1; - -import com.facebook.proguard.annotations.DoNotStrip; - -@DoNotStrip -public class ExcludedIosComponentProps { - - -} -", - "java/com/facebook/react/viewmanagers/ComponentFile2/MultiFileIncludedNativeComponentProps.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.ComponentFile2; - -import com.facebook.proguard.annotations.DoNotStrip; - -@DoNotStrip -public class MultiFileIncludedNativeComponentProps { - private boolean mDisabled; - @DoNotStrip - public boolean getDisabled() { - return mDisabled; - } -} -", -} -`; - -exports[`GeneratePropsJavaPojo can generate fixture FLOAT_PROPS 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/Switch/FloatPropNativeComponentProps.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.Switch; - -import com.facebook.proguard.annotations.DoNotStrip; - -@DoNotStrip -public class FloatPropNativeComponentProps { - private float mBlurRadius; - private float mBlurRadius2; - private float mBlurRadius3; - private float mBlurRadius4; - private float mBlurRadius5; - private float mBlurRadius6; - @DoNotStrip - public float getBlurRadius() { - return mBlurRadius; - } - @DoNotStrip - public float getBlurRadius2() { - return mBlurRadius2; - } - @DoNotStrip - public float getBlurRadius3() { - return mBlurRadius3; - } - @DoNotStrip - public float getBlurRadius4() { - return mBlurRadius4; - } - @DoNotStrip - public float getBlurRadius5() { - return mBlurRadius5; - } - @DoNotStrip - public float getBlurRadius6() { - return mBlurRadius6; - } -} -", -} -`; - -exports[`GeneratePropsJavaPojo can generate fixture IMAGE_PROP 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/Slider/ImagePropNativeComponentProps.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.Slider; - -import androidx.annotation.Nullable; -import com.facebook.proguard.annotations.DoNotStrip; -import com.facebook.react.bridge.ReadableMap; - -@DoNotStrip -public class ImagePropNativeComponentProps { - private @Nullable ReadableMap mThumbImage; - @DoNotStrip - public @Nullable ReadableMap getThumbImage() { - return mThumbImage; - } -} -", -} -`; - -exports[`GeneratePropsJavaPojo can generate fixture INSETS_PROP 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/ScrollView/InsetsPropNativeComponentProps.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.ScrollView; - -import androidx.annotation.Nullable; -import com.facebook.proguard.annotations.DoNotStrip; -import com.facebook.react.bridge.ReadableMap; - -@DoNotStrip -public class InsetsPropNativeComponentProps { - private @Nullable ReadableMap mContentInset; - @DoNotStrip - public @Nullable ReadableMap getContentInset() { - return mContentInset; - } -} -", -} -`; - -exports[`GeneratePropsJavaPojo can generate fixture INT32_ENUM_PROP 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/Switch/Int32EnumPropsNativeComponentProps.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.Switch; - -import androidx.annotation.Nullable; -import com.facebook.proguard.annotations.DoNotStrip; - -@DoNotStrip -public class Int32EnumPropsNativeComponentProps { - private @Nullable Integer mMaxInterval; - @DoNotStrip - public @Nullable Integer getMaxInterval() { - return mMaxInterval; - } -} -", -} -`; - -exports[`GeneratePropsJavaPojo can generate fixture INTEGER_PROPS 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/Switch/IntegerPropNativeComponentProps.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.Switch; - -import com.facebook.proguard.annotations.DoNotStrip; - -@DoNotStrip -public class IntegerPropNativeComponentProps { - private int mProgress1; - private int mProgress2; - private int mProgress3; - @DoNotStrip - public int getProgress1() { - return mProgress1; - } - @DoNotStrip - public int getProgress2() { - return mProgress2; - } - @DoNotStrip - public int getProgress3() { - return mProgress3; - } -} -", -} -`; - -exports[`GeneratePropsJavaPojo can generate fixture INTERFACE_ONLY 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/Switch/InterfaceOnlyComponentProps.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.Switch; - -import androidx.annotation.Nullable; -import com.facebook.proguard.annotations.DoNotStrip; - -@DoNotStrip -public class InterfaceOnlyComponentProps { - private @Nullable String mAccessibilityHint; - @DoNotStrip - public @Nullable String getAccessibilityHint() { - return mAccessibilityHint; - } -} -", -} -`; - -exports[`GeneratePropsJavaPojo can generate fixture MULTI_NATIVE_PROP 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/Slider/ImageColorPropNativeComponentProps.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.Slider; - -import androidx.annotation.Nullable; -import com.facebook.proguard.annotations.DoNotStrip; -import com.facebook.react.bridge.ReadableMap; - -@DoNotStrip -public class ImageColorPropNativeComponentProps { - private @Nullable ReadableMap mThumbImage; - private @Nullable Integer mColor; - private @Nullable Integer mThumbTintColor; - private @Nullable ReadableMap mPoint; - @DoNotStrip - public @Nullable ReadableMap getThumbImage() { - return mThumbImage; - } - @DoNotStrip - public @Nullable Integer getColor() { - return mColor; - } - @DoNotStrip - public @Nullable Integer getThumbTintColor() { - return mThumbTintColor; - } - @DoNotStrip - public @Nullable ReadableMap getPoint() { - return mPoint; - } -} -", -} -`; - -exports[`GeneratePropsJavaPojo can generate fixture NO_PROPS_NO_EVENTS 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/NoPropsNoEvents/NoPropsNoEventsComponentProps.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.NoPropsNoEvents; - -import com.facebook.proguard.annotations.DoNotStrip; - -@DoNotStrip -public class NoPropsNoEventsComponentProps { - - -} -", -} -`; - -exports[`GeneratePropsJavaPojo can generate fixture OBJECT_PROPS 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/ObjectPropsNativeComponent/ObjectPropsPropsObjectPropObjectArrayProp.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.ObjectPropsNativeComponent; - -import com.facebook.proguard.annotations.DoNotStrip; -import java.util.ArrayList; - -@DoNotStrip -public class ObjectPropsPropsObjectPropObjectArrayProp { - private ArrayList mArray; - @DoNotStrip - public ArrayList getArray() { - return mArray; - } -} -", - "java/com/facebook/react/viewmanagers/ObjectPropsNativeComponent/ObjectPropsPropsObjectPropObjectPrimitiveRequiredProp.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.ObjectPropsNativeComponent; - -import androidx.annotation.Nullable; -import com.facebook.proguard.annotations.DoNotStrip; -import com.facebook.react.bridge.ReadableMap; - -@DoNotStrip -public class ObjectPropsPropsObjectPropObjectPrimitiveRequiredProp { - private @Nullable ReadableMap mImage; - private @Nullable Integer mColor; - private @Nullable ReadableMap mPoint; - @DoNotStrip - public @Nullable ReadableMap getImage() { - return mImage; - } - @DoNotStrip - public @Nullable Integer getColor() { - return mColor; - } - @DoNotStrip - public @Nullable ReadableMap getPoint() { - return mPoint; - } -} -", - "java/com/facebook/react/viewmanagers/ObjectPropsNativeComponent/ObjectPropsPropsObjectPropNestedPropANestedPropB.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.ObjectPropsNativeComponent; - -import androidx.annotation.Nullable; -import com.facebook.proguard.annotations.DoNotStrip; - -@DoNotStrip -public class ObjectPropsPropsObjectPropNestedPropANestedPropB { - private @Nullable String mNestedPropC; - @DoNotStrip - public @Nullable String getNestedPropC() { - return mNestedPropC; - } -} -", - "java/com/facebook/react/viewmanagers/ObjectPropsNativeComponent/ObjectPropsPropsObjectPropNestedPropA.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.ObjectPropsNativeComponent; - -import com.facebook.proguard.annotations.DoNotStrip; - -@DoNotStrip -public class ObjectPropsPropsObjectPropNestedPropA { - private ObjectPropsPropsObjectPropNestedPropANestedPropB mNestedPropB; - @DoNotStrip - public ObjectPropsPropsObjectPropNestedPropANestedPropB getNestedPropB() { - return mNestedPropB; - } -} -", - "java/com/facebook/react/viewmanagers/ObjectPropsNativeComponent/ObjectPropsPropsObjectPropNestedArrayAsPropertyArrayPropElement.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.ObjectPropsNativeComponent; - -import androidx.annotation.Nullable; -import com.facebook.proguard.annotations.DoNotStrip; - -@DoNotStrip -public class ObjectPropsPropsObjectPropNestedArrayAsPropertyArrayPropElement { - private @Nullable String mStringProp; - @DoNotStrip - public @Nullable String getStringProp() { - return mStringProp; - } -} -", - "java/com/facebook/react/viewmanagers/ObjectPropsNativeComponent/ObjectPropsPropsObjectPropNestedArrayAsProperty.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.ObjectPropsNativeComponent; - -import com.facebook.proguard.annotations.DoNotStrip; -import java.util.ArrayList; - -@DoNotStrip -public class ObjectPropsPropsObjectPropNestedArrayAsProperty { - private ArrayList mArrayProp; - @DoNotStrip - public ArrayList getArrayProp() { - return mArrayProp; - } -} -", - "java/com/facebook/react/viewmanagers/ObjectPropsNativeComponent/ObjectPropsPropsObjectProp.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.ObjectPropsNativeComponent; - -import androidx.annotation.Nullable; -import com.facebook.proguard.annotations.DoNotStrip; - -@DoNotStrip -public class ObjectPropsPropsObjectProp { - private @Nullable String mStringProp; - private boolean mBooleanProp; - private float mFloatProp; - private int mIntProp; - private @Nullable String mStringEnumProp; - private @Nullable Integer mIntEnumProp; - private ObjectPropsPropsObjectPropObjectArrayProp mObjectArrayProp; - private ObjectPropsPropsObjectPropObjectPrimitiveRequiredProp mObjectPrimitiveRequiredProp; - private ObjectPropsPropsObjectPropNestedPropA mNestedPropA; - private ObjectPropsPropsObjectPropNestedArrayAsProperty mNestedArrayAsProperty; - @DoNotStrip - public @Nullable String getStringProp() { - return mStringProp; - } - @DoNotStrip - public boolean getBooleanProp() { - return mBooleanProp; - } - @DoNotStrip - public float getFloatProp() { - return mFloatProp; - } - @DoNotStrip - public int getIntProp() { - return mIntProp; - } - @DoNotStrip - public @Nullable String getStringEnumProp() { - return mStringEnumProp; - } - @DoNotStrip - public @Nullable Integer getIntEnumProp() { - return mIntEnumProp; - } - @DoNotStrip - public ObjectPropsPropsObjectPropObjectArrayProp getObjectArrayProp() { - return mObjectArrayProp; - } - @DoNotStrip - public ObjectPropsPropsObjectPropObjectPrimitiveRequiredProp getObjectPrimitiveRequiredProp() { - return mObjectPrimitiveRequiredProp; - } - @DoNotStrip - public ObjectPropsPropsObjectPropNestedPropA getNestedPropA() { - return mNestedPropA; - } - @DoNotStrip - public ObjectPropsPropsObjectPropNestedArrayAsProperty getNestedArrayAsProperty() { - return mNestedArrayAsProperty; - } -} -", - "java/com/facebook/react/viewmanagers/ObjectPropsNativeComponent/ObjectPropsProps.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.ObjectPropsNativeComponent; - -import com.facebook.proguard.annotations.DoNotStrip; - -@DoNotStrip -public class ObjectPropsProps { - private ObjectPropsPropsObjectProp mObjectProp; - @DoNotStrip - public ObjectPropsPropsObjectProp getObjectProp() { - return mObjectProp; - } -} -", -} -`; - -exports[`GeneratePropsJavaPojo can generate fixture POINT_PROP 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/Switch/PointPropNativeComponentProps.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.Switch; - -import androidx.annotation.Nullable; -import com.facebook.proguard.annotations.DoNotStrip; -import com.facebook.react.bridge.ReadableMap; - -@DoNotStrip -public class PointPropNativeComponentProps { - private @Nullable ReadableMap mStartPoint; - @DoNotStrip - public @Nullable ReadableMap getStartPoint() { - return mStartPoint; - } -} -", -} -`; - -exports[`GeneratePropsJavaPojo can generate fixture STRING_ENUM_PROP 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/Switch/StringEnumPropsNativeComponentProps.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.Switch; - -import androidx.annotation.Nullable; -import com.facebook.proguard.annotations.DoNotStrip; - -@DoNotStrip -public class StringEnumPropsNativeComponentProps { - private @Nullable String mAlignment; - @DoNotStrip - public @Nullable String getAlignment() { - return mAlignment; - } -} -", -} -`; - -exports[`GeneratePropsJavaPojo can generate fixture STRING_PROP 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/Switch/StringPropComponentProps.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.Switch; - -import androidx.annotation.Nullable; -import com.facebook.proguard.annotations.DoNotStrip; - -@DoNotStrip -public class StringPropComponentProps { - private @Nullable String mAccessibilityHint; - private @Nullable String mAccessibilityRole; - @DoNotStrip - public @Nullable String getAccessibilityHint() { - return mAccessibilityHint; - } - @DoNotStrip - public @Nullable String getAccessibilityRole() { - return mAccessibilityRole; - } -} -", -} -`; - -exports[`GeneratePropsJavaPojo can generate fixture TWO_COMPONENTS_DIFFERENT_FILES 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/ComponentFile1/MultiFile1NativeComponentProps.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.ComponentFile1; - -import com.facebook.proguard.annotations.DoNotStrip; - -@DoNotStrip -public class MultiFile1NativeComponentProps { - private boolean mDisabled; - @DoNotStrip - public boolean getDisabled() { - return mDisabled; - } -} -", - "java/com/facebook/react/viewmanagers/ComponentFile2/MultiFile2NativeComponentProps.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.ComponentFile2; - -import com.facebook.proguard.annotations.DoNotStrip; - -@DoNotStrip -public class MultiFile2NativeComponentProps { - private boolean mDisabled; - @DoNotStrip - public boolean getDisabled() { - return mDisabled; - } -} -", -} -`; - -exports[`GeneratePropsJavaPojo can generate fixture TWO_COMPONENTS_SAME_FILE 1`] = ` -Map { - "java/com/facebook/react/viewmanagers/MyComponents/MultiComponent1NativeComponentProps.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.MyComponents; - -import com.facebook.proguard.annotations.DoNotStrip; - -@DoNotStrip -public class MultiComponent1NativeComponentProps { - private boolean mDisabled; - @DoNotStrip - public boolean getDisabled() { - return mDisabled; - } -} -", - "java/com/facebook/react/viewmanagers/MyComponents/MultiComponent2NativeComponentProps.java" => "/** -* 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. -* -* @generated by codegen project: GeneratePropsJavaPojo.js -*/ - -package com.facebook.react.viewmanagers.MyComponents; - -import com.facebook.proguard.annotations.DoNotStrip; - -@DoNotStrip -public class MultiComponent2NativeComponentProps { - private boolean mDisabled; - @DoNotStrip - public boolean getDisabled() { - return mDisabled; - } -} -", -} -`; diff --git a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateShadowNodeCpp-test.js.snap b/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateShadowNodeCpp-test.js.snap deleted file mode 100644 index b09ab9ea8beb..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateShadowNodeCpp-test.js.snap +++ /dev/null @@ -1,679 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GenerateShadowNodeCpp can generate fixture ARRAY_PROPS 1`] = ` -Map { - "ShadowNodes.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char ArrayPropsNativeComponentComponentName[] = \\"ArrayPropsNativeComponent\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate fixture ARRAY_PROPS_WITH_NESTED_OBJECT 1`] = ` -Map { - "ShadowNodes.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char ArrayPropsNativeComponentComponentName[] = \\"ArrayPropsNativeComponent\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate fixture BOOLEAN_PROP 1`] = ` -Map { - "ShadowNodes.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char BooleanPropNativeComponentComponentName[] = \\"BooleanPropNativeComponent\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate fixture COLOR_PROP 1`] = ` -Map { - "ShadowNodes.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char ColorPropNativeComponentComponentName[] = \\"ColorPropNativeComponent\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate fixture COMMANDS 1`] = ` -Map { - "ShadowNodes.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char CommandNativeComponentComponentName[] = \\"CommandNativeComponent\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate fixture COMMANDS_AND_PROPS 1`] = ` -Map { - "ShadowNodes.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char CommandNativeComponentComponentName[] = \\"CommandNativeComponent\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate fixture DOUBLE_PROPS 1`] = ` -Map { - "ShadowNodes.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char DoublePropNativeComponentComponentName[] = \\"DoublePropNativeComponent\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate fixture EVENT_NESTED_OBJECT_PROPS 1`] = ` -Map { - "ShadowNodes.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char EventsNestedObjectNativeComponentComponentName[] = \\"EventsNestedObjectNativeComponent\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate fixture EVENT_PROPS 1`] = ` -Map { - "ShadowNodes.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char EventsNativeComponentComponentName[] = \\"EventsNativeComponent\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate fixture EVENTS_WITH_PAPER_NAME 1`] = ` -Map { - "ShadowNodes.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate fixture EXCLUDE_ANDROID 1`] = ` -Map { - "ShadowNodes.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char ExcludedAndroidComponentComponentName[] = \\"ExcludedAndroidComponent\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate fixture EXCLUDE_ANDROID_IOS 1`] = ` -Map { - "ShadowNodes.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char ExcludedAndroidIosComponentComponentName[] = \\"ExcludedAndroidIosComponent\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate fixture EXCLUDE_IOS_TWO_COMPONENTS_DIFFERENT_FILES 1`] = ` -Map { - "ShadowNodes.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char ExcludedIosComponentComponentName[] = \\"ExcludedIosComponent\\"; -extern const char MultiFileIncludedNativeComponentComponentName[] = \\"MultiFileIncludedNativeComponent\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate fixture FLOAT_PROPS 1`] = ` -Map { - "ShadowNodes.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char FloatPropNativeComponentComponentName[] = \\"FloatPropNativeComponent\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate fixture IMAGE_PROP 1`] = ` -Map { - "ShadowNodes.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char ImagePropNativeComponentComponentName[] = \\"ImagePropNativeComponent\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate fixture INSETS_PROP 1`] = ` -Map { - "ShadowNodes.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char InsetsPropNativeComponentComponentName[] = \\"InsetsPropNativeComponent\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate fixture INT32_ENUM_PROP 1`] = ` -Map { - "ShadowNodes.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char Int32EnumPropsNativeComponentComponentName[] = \\"Int32EnumPropsNativeComponent\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate fixture INTEGER_PROPS 1`] = ` -Map { - "ShadowNodes.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char IntegerPropNativeComponentComponentName[] = \\"IntegerPropNativeComponent\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate fixture INTERFACE_ONLY 1`] = ` -Map { - "ShadowNodes.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate fixture MULTI_NATIVE_PROP 1`] = ` -Map { - "ShadowNodes.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char ImageColorPropNativeComponentComponentName[] = \\"ImageColorPropNativeComponent\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate fixture NO_PROPS_NO_EVENTS 1`] = ` -Map { - "ShadowNodes.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char NoPropsNoEventsComponentComponentName[] = \\"NoPropsNoEventsComponent\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate fixture OBJECT_PROPS 1`] = ` -Map { - "ShadowNodes.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char ObjectPropsComponentName[] = \\"ObjectProps\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate fixture POINT_PROP 1`] = ` -Map { - "ShadowNodes.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char PointPropNativeComponentComponentName[] = \\"PointPropNativeComponent\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate fixture STRING_ENUM_PROP 1`] = ` -Map { - "ShadowNodes.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char StringEnumPropsNativeComponentComponentName[] = \\"StringEnumPropsNativeComponent\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate fixture STRING_PROP 1`] = ` -Map { - "ShadowNodes.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char StringPropComponentComponentName[] = \\"StringPropComponent\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate fixture TWO_COMPONENTS_DIFFERENT_FILES 1`] = ` -Map { - "ShadowNodes.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char MultiFile1NativeComponentComponentName[] = \\"MultiFile1NativeComponent\\"; -extern const char MultiFile2NativeComponentComponentName[] = \\"MultiFile2NativeComponent\\"; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeCpp can generate fixture TWO_COMPONENTS_SAME_FILE 1`] = ` -Map { - "ShadowNodes.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeCpp.js - */ - -#include - -namespace facebook { -namespace react { - -extern const char MultiComponent1NativeComponentComponentName[] = \\"MultiComponent1NativeComponent\\"; -extern const char MultiComponent2NativeComponentComponentName[] = \\"MultiComponent2NativeComponent\\"; - -} // namespace react -} // namespace facebook -", -} -`; diff --git a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateShadowNodeH-test.js.snap b/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateShadowNodeH-test.js.snap deleted file mode 100644 index 86226abbbd72..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateShadowNodeH-test.js.snap +++ /dev/null @@ -1,1096 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GenerateShadowNodeH can generate fixture ARRAY_PROPS 1`] = ` -Map { - "ShadowNodes.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char ArrayPropsNativeComponentComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using ArrayPropsNativeComponentShadowNode = ConcreteViewShadowNode< - ArrayPropsNativeComponentComponentName, - ArrayPropsNativeComponentProps, - ArrayPropsNativeComponentEventEmitter, - ArrayPropsNativeComponentState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate fixture ARRAY_PROPS_WITH_NESTED_OBJECT 1`] = ` -Map { - "ShadowNodes.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char ArrayPropsNativeComponentComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using ArrayPropsNativeComponentShadowNode = ConcreteViewShadowNode< - ArrayPropsNativeComponentComponentName, - ArrayPropsNativeComponentProps, - ArrayPropsNativeComponentEventEmitter, - ArrayPropsNativeComponentState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate fixture BOOLEAN_PROP 1`] = ` -Map { - "ShadowNodes.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char BooleanPropNativeComponentComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using BooleanPropNativeComponentShadowNode = ConcreteViewShadowNode< - BooleanPropNativeComponentComponentName, - BooleanPropNativeComponentProps, - BooleanPropNativeComponentEventEmitter, - BooleanPropNativeComponentState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate fixture COLOR_PROP 1`] = ` -Map { - "ShadowNodes.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char ColorPropNativeComponentComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using ColorPropNativeComponentShadowNode = ConcreteViewShadowNode< - ColorPropNativeComponentComponentName, - ColorPropNativeComponentProps, - ColorPropNativeComponentEventEmitter, - ColorPropNativeComponentState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate fixture COMMANDS 1`] = ` -Map { - "ShadowNodes.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char CommandNativeComponentComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using CommandNativeComponentShadowNode = ConcreteViewShadowNode< - CommandNativeComponentComponentName, - CommandNativeComponentProps, - CommandNativeComponentEventEmitter, - CommandNativeComponentState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate fixture COMMANDS_AND_PROPS 1`] = ` -Map { - "ShadowNodes.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char CommandNativeComponentComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using CommandNativeComponentShadowNode = ConcreteViewShadowNode< - CommandNativeComponentComponentName, - CommandNativeComponentProps, - CommandNativeComponentEventEmitter, - CommandNativeComponentState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate fixture DOUBLE_PROPS 1`] = ` -Map { - "ShadowNodes.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char DoublePropNativeComponentComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using DoublePropNativeComponentShadowNode = ConcreteViewShadowNode< - DoublePropNativeComponentComponentName, - DoublePropNativeComponentProps, - DoublePropNativeComponentEventEmitter, - DoublePropNativeComponentState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate fixture EVENT_NESTED_OBJECT_PROPS 1`] = ` -Map { - "ShadowNodes.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char EventsNestedObjectNativeComponentComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using EventsNestedObjectNativeComponentShadowNode = ConcreteViewShadowNode< - EventsNestedObjectNativeComponentComponentName, - EventsNestedObjectNativeComponentProps, - EventsNestedObjectNativeComponentEventEmitter, - EventsNestedObjectNativeComponentState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate fixture EVENT_PROPS 1`] = ` -Map { - "ShadowNodes.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char EventsNativeComponentComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using EventsNativeComponentShadowNode = ConcreteViewShadowNode< - EventsNativeComponentComponentName, - EventsNativeComponentProps, - EventsNativeComponentEventEmitter, - EventsNativeComponentState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate fixture EVENTS_WITH_PAPER_NAME 1`] = ` -Map { - "ShadowNodes.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate fixture EXCLUDE_ANDROID 1`] = ` -Map { - "ShadowNodes.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char ExcludedAndroidComponentComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using ExcludedAndroidComponentShadowNode = ConcreteViewShadowNode< - ExcludedAndroidComponentComponentName, - ExcludedAndroidComponentProps, - ExcludedAndroidComponentEventEmitter, - ExcludedAndroidComponentState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate fixture EXCLUDE_ANDROID_IOS 1`] = ` -Map { - "ShadowNodes.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char ExcludedAndroidIosComponentComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using ExcludedAndroidIosComponentShadowNode = ConcreteViewShadowNode< - ExcludedAndroidIosComponentComponentName, - ExcludedAndroidIosComponentProps, - ExcludedAndroidIosComponentEventEmitter, - ExcludedAndroidIosComponentState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate fixture EXCLUDE_IOS_TWO_COMPONENTS_DIFFERENT_FILES 1`] = ` -Map { - "ShadowNodes.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char ExcludedIosComponentComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using ExcludedIosComponentShadowNode = ConcreteViewShadowNode< - ExcludedIosComponentComponentName, - ExcludedIosComponentProps, - ExcludedIosComponentEventEmitter, - ExcludedIosComponentState>; - -JSI_EXPORT extern const char MultiFileIncludedNativeComponentComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using MultiFileIncludedNativeComponentShadowNode = ConcreteViewShadowNode< - MultiFileIncludedNativeComponentComponentName, - MultiFileIncludedNativeComponentProps, - MultiFileIncludedNativeComponentEventEmitter, - MultiFileIncludedNativeComponentState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate fixture FLOAT_PROPS 1`] = ` -Map { - "ShadowNodes.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char FloatPropNativeComponentComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using FloatPropNativeComponentShadowNode = ConcreteViewShadowNode< - FloatPropNativeComponentComponentName, - FloatPropNativeComponentProps, - FloatPropNativeComponentEventEmitter, - FloatPropNativeComponentState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate fixture IMAGE_PROP 1`] = ` -Map { - "ShadowNodes.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char ImagePropNativeComponentComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using ImagePropNativeComponentShadowNode = ConcreteViewShadowNode< - ImagePropNativeComponentComponentName, - ImagePropNativeComponentProps, - ImagePropNativeComponentEventEmitter, - ImagePropNativeComponentState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate fixture INSETS_PROP 1`] = ` -Map { - "ShadowNodes.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char InsetsPropNativeComponentComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using InsetsPropNativeComponentShadowNode = ConcreteViewShadowNode< - InsetsPropNativeComponentComponentName, - InsetsPropNativeComponentProps, - InsetsPropNativeComponentEventEmitter, - InsetsPropNativeComponentState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate fixture INT32_ENUM_PROP 1`] = ` -Map { - "ShadowNodes.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char Int32EnumPropsNativeComponentComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using Int32EnumPropsNativeComponentShadowNode = ConcreteViewShadowNode< - Int32EnumPropsNativeComponentComponentName, - Int32EnumPropsNativeComponentProps, - Int32EnumPropsNativeComponentEventEmitter, - Int32EnumPropsNativeComponentState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate fixture INTEGER_PROPS 1`] = ` -Map { - "ShadowNodes.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char IntegerPropNativeComponentComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using IntegerPropNativeComponentShadowNode = ConcreteViewShadowNode< - IntegerPropNativeComponentComponentName, - IntegerPropNativeComponentProps, - IntegerPropNativeComponentEventEmitter, - IntegerPropNativeComponentState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate fixture INTERFACE_ONLY 1`] = ` -Map { - "ShadowNodes.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate fixture MULTI_NATIVE_PROP 1`] = ` -Map { - "ShadowNodes.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char ImageColorPropNativeComponentComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using ImageColorPropNativeComponentShadowNode = ConcreteViewShadowNode< - ImageColorPropNativeComponentComponentName, - ImageColorPropNativeComponentProps, - ImageColorPropNativeComponentEventEmitter, - ImageColorPropNativeComponentState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate fixture NO_PROPS_NO_EVENTS 1`] = ` -Map { - "ShadowNodes.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char NoPropsNoEventsComponentComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using NoPropsNoEventsComponentShadowNode = ConcreteViewShadowNode< - NoPropsNoEventsComponentComponentName, - NoPropsNoEventsComponentProps, - NoPropsNoEventsComponentEventEmitter, - NoPropsNoEventsComponentState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate fixture OBJECT_PROPS 1`] = ` -Map { - "ShadowNodes.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char ObjectPropsComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using ObjectPropsShadowNode = ConcreteViewShadowNode< - ObjectPropsComponentName, - ObjectPropsProps, - ObjectPropsEventEmitter, - ObjectPropsState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate fixture POINT_PROP 1`] = ` -Map { - "ShadowNodes.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char PointPropNativeComponentComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using PointPropNativeComponentShadowNode = ConcreteViewShadowNode< - PointPropNativeComponentComponentName, - PointPropNativeComponentProps, - PointPropNativeComponentEventEmitter, - PointPropNativeComponentState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate fixture STRING_ENUM_PROP 1`] = ` -Map { - "ShadowNodes.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char StringEnumPropsNativeComponentComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using StringEnumPropsNativeComponentShadowNode = ConcreteViewShadowNode< - StringEnumPropsNativeComponentComponentName, - StringEnumPropsNativeComponentProps, - StringEnumPropsNativeComponentEventEmitter, - StringEnumPropsNativeComponentState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate fixture STRING_PROP 1`] = ` -Map { - "ShadowNodes.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char StringPropComponentComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using StringPropComponentShadowNode = ConcreteViewShadowNode< - StringPropComponentComponentName, - StringPropComponentProps, - StringPropComponentEventEmitter, - StringPropComponentState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate fixture TWO_COMPONENTS_DIFFERENT_FILES 1`] = ` -Map { - "ShadowNodes.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char MultiFile1NativeComponentComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using MultiFile1NativeComponentShadowNode = ConcreteViewShadowNode< - MultiFile1NativeComponentComponentName, - MultiFile1NativeComponentProps, - MultiFile1NativeComponentEventEmitter, - MultiFile1NativeComponentState>; - -JSI_EXPORT extern const char MultiFile2NativeComponentComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using MultiFile2NativeComponentShadowNode = ConcreteViewShadowNode< - MultiFile2NativeComponentComponentName, - MultiFile2NativeComponentProps, - MultiFile2NativeComponentEventEmitter, - MultiFile2NativeComponentState>; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateShadowNodeH can generate fixture TWO_COMPONENTS_SAME_FILE 1`] = ` -Map { - "ShadowNodes.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateShadowNodeH.js - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -JSI_EXPORT extern const char MultiComponent1NativeComponentComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using MultiComponent1NativeComponentShadowNode = ConcreteViewShadowNode< - MultiComponent1NativeComponentComponentName, - MultiComponent1NativeComponentProps, - MultiComponent1NativeComponentEventEmitter, - MultiComponent1NativeComponentState>; - -JSI_EXPORT extern const char MultiComponent2NativeComponentComponentName[]; - -/* - * \`ShadowNode\` for component. - */ -using MultiComponent2NativeComponentShadowNode = ConcreteViewShadowNode< - MultiComponent2NativeComponentComponentName, - MultiComponent2NativeComponentProps, - MultiComponent2NativeComponentEventEmitter, - MultiComponent2NativeComponentState>; - -} // namespace react -} // namespace facebook -", -} -`; diff --git a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateStateCpp-test.js.snap b/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateStateCpp-test.js.snap deleted file mode 100644 index 04084fb1b5a0..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateStateCpp-test.js.snap +++ /dev/null @@ -1,649 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GenerateStateCpp can generate fixture ARRAY_PROPS 1`] = ` -Map { - "States.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateCpp.js - */ -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateStateCpp can generate fixture ARRAY_PROPS_WITH_NESTED_OBJECT 1`] = ` -Map { - "States.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateCpp.js - */ -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateStateCpp can generate fixture BOOLEAN_PROP 1`] = ` -Map { - "States.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateCpp.js - */ -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateStateCpp can generate fixture COLOR_PROP 1`] = ` -Map { - "States.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateCpp.js - */ -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateStateCpp can generate fixture COMMANDS 1`] = ` -Map { - "States.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateCpp.js - */ -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateStateCpp can generate fixture COMMANDS_AND_PROPS 1`] = ` -Map { - "States.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateCpp.js - */ -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateStateCpp can generate fixture DOUBLE_PROPS 1`] = ` -Map { - "States.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateCpp.js - */ -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateStateCpp can generate fixture EVENT_NESTED_OBJECT_PROPS 1`] = ` -Map { - "States.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateCpp.js - */ -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateStateCpp can generate fixture EVENT_PROPS 1`] = ` -Map { - "States.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateCpp.js - */ -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateStateCpp can generate fixture EVENTS_WITH_PAPER_NAME 1`] = ` -Map { - "States.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateCpp.js - */ -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateStateCpp can generate fixture EXCLUDE_ANDROID 1`] = ` -Map { - "States.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateCpp.js - */ -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateStateCpp can generate fixture EXCLUDE_ANDROID_IOS 1`] = ` -Map { - "States.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateCpp.js - */ -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateStateCpp can generate fixture EXCLUDE_IOS_TWO_COMPONENTS_DIFFERENT_FILES 1`] = ` -Map { - "States.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateCpp.js - */ -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateStateCpp can generate fixture FLOAT_PROPS 1`] = ` -Map { - "States.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateCpp.js - */ -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateStateCpp can generate fixture IMAGE_PROP 1`] = ` -Map { - "States.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateCpp.js - */ -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateStateCpp can generate fixture INSETS_PROP 1`] = ` -Map { - "States.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateCpp.js - */ -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateStateCpp can generate fixture INT32_ENUM_PROP 1`] = ` -Map { - "States.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateCpp.js - */ -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateStateCpp can generate fixture INTEGER_PROPS 1`] = ` -Map { - "States.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateCpp.js - */ -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateStateCpp can generate fixture INTERFACE_ONLY 1`] = ` -Map { - "States.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateCpp.js - */ -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateStateCpp can generate fixture MULTI_NATIVE_PROP 1`] = ` -Map { - "States.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateCpp.js - */ -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateStateCpp can generate fixture NO_PROPS_NO_EVENTS 1`] = ` -Map { - "States.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateCpp.js - */ -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateStateCpp can generate fixture OBJECT_PROPS 1`] = ` -Map { - "States.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateCpp.js - */ -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateStateCpp can generate fixture POINT_PROP 1`] = ` -Map { - "States.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateCpp.js - */ -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateStateCpp can generate fixture STRING_ENUM_PROP 1`] = ` -Map { - "States.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateCpp.js - */ -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateStateCpp can generate fixture STRING_PROP 1`] = ` -Map { - "States.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateCpp.js - */ -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateStateCpp can generate fixture TWO_COMPONENTS_DIFFERENT_FILES 1`] = ` -Map { - "States.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateCpp.js - */ -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateStateCpp can generate fixture TWO_COMPONENTS_SAME_FILE 1`] = ` -Map { - "States.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateCpp.js - */ -#include - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook -", -} -`; diff --git a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateStateH-test.js.snap b/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateStateH-test.js.snap deleted file mode 100644 index a0bb2f075a0a..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateStateH-test.js.snap +++ /dev/null @@ -1,1127 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GenerateStateH can generate fixture ARRAY_PROPS 1`] = ` -Map { - "States.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateH.js - */ -#pragma once - -#ifdef ANDROID -#include -#include -#include -#endif - -namespace facebook { -namespace react { - -class ArrayPropsNativeComponentState { -public: - ArrayPropsNativeComponentState() = default; - -#ifdef ANDROID - ArrayPropsNativeComponentState(ArrayPropsNativeComponentState const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; - MapBuffer getMapBuffer() const { - return MapBufferBuilder::EMPTY(); - }; -#endif -}; - -} // namespace react -} // namespace facebook", -} -`; - -exports[`GenerateStateH can generate fixture ARRAY_PROPS_WITH_NESTED_OBJECT 1`] = ` -Map { - "States.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateH.js - */ -#pragma once - -#ifdef ANDROID -#include -#include -#include -#endif - -namespace facebook { -namespace react { - -class ArrayPropsNativeComponentState { -public: - ArrayPropsNativeComponentState() = default; - -#ifdef ANDROID - ArrayPropsNativeComponentState(ArrayPropsNativeComponentState const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; - MapBuffer getMapBuffer() const { - return MapBufferBuilder::EMPTY(); - }; -#endif -}; - -} // namespace react -} // namespace facebook", -} -`; - -exports[`GenerateStateH can generate fixture BOOLEAN_PROP 1`] = ` -Map { - "States.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateH.js - */ -#pragma once - -#ifdef ANDROID -#include -#include -#include -#endif - -namespace facebook { -namespace react { - -class BooleanPropNativeComponentState { -public: - BooleanPropNativeComponentState() = default; - -#ifdef ANDROID - BooleanPropNativeComponentState(BooleanPropNativeComponentState const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; - MapBuffer getMapBuffer() const { - return MapBufferBuilder::EMPTY(); - }; -#endif -}; - -} // namespace react -} // namespace facebook", -} -`; - -exports[`GenerateStateH can generate fixture COLOR_PROP 1`] = ` -Map { - "States.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateH.js - */ -#pragma once - -#ifdef ANDROID -#include -#include -#include -#endif - -namespace facebook { -namespace react { - -class ColorPropNativeComponentState { -public: - ColorPropNativeComponentState() = default; - -#ifdef ANDROID - ColorPropNativeComponentState(ColorPropNativeComponentState const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; - MapBuffer getMapBuffer() const { - return MapBufferBuilder::EMPTY(); - }; -#endif -}; - -} // namespace react -} // namespace facebook", -} -`; - -exports[`GenerateStateH can generate fixture COMMANDS 1`] = ` -Map { - "States.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateH.js - */ -#pragma once - -#ifdef ANDROID -#include -#include -#include -#endif - -namespace facebook { -namespace react { - -class CommandNativeComponentState { -public: - CommandNativeComponentState() = default; - -#ifdef ANDROID - CommandNativeComponentState(CommandNativeComponentState const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; - MapBuffer getMapBuffer() const { - return MapBufferBuilder::EMPTY(); - }; -#endif -}; - -} // namespace react -} // namespace facebook", -} -`; - -exports[`GenerateStateH can generate fixture COMMANDS_AND_PROPS 1`] = ` -Map { - "States.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateH.js - */ -#pragma once - -#ifdef ANDROID -#include -#include -#include -#endif - -namespace facebook { -namespace react { - -class CommandNativeComponentState { -public: - CommandNativeComponentState() = default; - -#ifdef ANDROID - CommandNativeComponentState(CommandNativeComponentState const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; - MapBuffer getMapBuffer() const { - return MapBufferBuilder::EMPTY(); - }; -#endif -}; - -} // namespace react -} // namespace facebook", -} -`; - -exports[`GenerateStateH can generate fixture DOUBLE_PROPS 1`] = ` -Map { - "States.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateH.js - */ -#pragma once - -#ifdef ANDROID -#include -#include -#include -#endif - -namespace facebook { -namespace react { - -class DoublePropNativeComponentState { -public: - DoublePropNativeComponentState() = default; - -#ifdef ANDROID - DoublePropNativeComponentState(DoublePropNativeComponentState const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; - MapBuffer getMapBuffer() const { - return MapBufferBuilder::EMPTY(); - }; -#endif -}; - -} // namespace react -} // namespace facebook", -} -`; - -exports[`GenerateStateH can generate fixture EVENT_NESTED_OBJECT_PROPS 1`] = ` -Map { - "States.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateH.js - */ -#pragma once - -#ifdef ANDROID -#include -#include -#include -#endif - -namespace facebook { -namespace react { - -class EventsNestedObjectNativeComponentState { -public: - EventsNestedObjectNativeComponentState() = default; - -#ifdef ANDROID - EventsNestedObjectNativeComponentState(EventsNestedObjectNativeComponentState const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; - MapBuffer getMapBuffer() const { - return MapBufferBuilder::EMPTY(); - }; -#endif -}; - -} // namespace react -} // namespace facebook", -} -`; - -exports[`GenerateStateH can generate fixture EVENT_PROPS 1`] = ` -Map { - "States.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateH.js - */ -#pragma once - -#ifdef ANDROID -#include -#include -#include -#endif - -namespace facebook { -namespace react { - -class EventsNativeComponentState { -public: - EventsNativeComponentState() = default; - -#ifdef ANDROID - EventsNativeComponentState(EventsNativeComponentState const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; - MapBuffer getMapBuffer() const { - return MapBufferBuilder::EMPTY(); - }; -#endif -}; - -} // namespace react -} // namespace facebook", -} -`; - -exports[`GenerateStateH can generate fixture EVENTS_WITH_PAPER_NAME 1`] = ` -Map { - "States.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateH.js - */ -#pragma once - -#ifdef ANDROID -#include -#include -#include -#endif - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook", -} -`; - -exports[`GenerateStateH can generate fixture EXCLUDE_ANDROID 1`] = ` -Map { - "States.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateH.js - */ -#pragma once - -#ifdef ANDROID -#include -#include -#include -#endif - -namespace facebook { -namespace react { - -class ExcludedAndroidComponentState { -public: - ExcludedAndroidComponentState() = default; - -#ifdef ANDROID - ExcludedAndroidComponentState(ExcludedAndroidComponentState const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; - MapBuffer getMapBuffer() const { - return MapBufferBuilder::EMPTY(); - }; -#endif -}; - -} // namespace react -} // namespace facebook", -} -`; - -exports[`GenerateStateH can generate fixture EXCLUDE_ANDROID_IOS 1`] = ` -Map { - "States.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateH.js - */ -#pragma once - -#ifdef ANDROID -#include -#include -#include -#endif - -namespace facebook { -namespace react { - -class ExcludedAndroidIosComponentState { -public: - ExcludedAndroidIosComponentState() = default; - -#ifdef ANDROID - ExcludedAndroidIosComponentState(ExcludedAndroidIosComponentState const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; - MapBuffer getMapBuffer() const { - return MapBufferBuilder::EMPTY(); - }; -#endif -}; - -} // namespace react -} // namespace facebook", -} -`; - -exports[`GenerateStateH can generate fixture EXCLUDE_IOS_TWO_COMPONENTS_DIFFERENT_FILES 1`] = ` -Map { - "States.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateH.js - */ -#pragma once - -#ifdef ANDROID -#include -#include -#include -#endif - -namespace facebook { -namespace react { - -class ExcludedIosComponentState { -public: - ExcludedIosComponentState() = default; - -#ifdef ANDROID - ExcludedIosComponentState(ExcludedIosComponentState const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; - MapBuffer getMapBuffer() const { - return MapBufferBuilder::EMPTY(); - }; -#endif -}; - -class MultiFileIncludedNativeComponentState { -public: - MultiFileIncludedNativeComponentState() = default; - -#ifdef ANDROID - MultiFileIncludedNativeComponentState(MultiFileIncludedNativeComponentState const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; - MapBuffer getMapBuffer() const { - return MapBufferBuilder::EMPTY(); - }; -#endif -}; - -} // namespace react -} // namespace facebook", -} -`; - -exports[`GenerateStateH can generate fixture FLOAT_PROPS 1`] = ` -Map { - "States.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateH.js - */ -#pragma once - -#ifdef ANDROID -#include -#include -#include -#endif - -namespace facebook { -namespace react { - -class FloatPropNativeComponentState { -public: - FloatPropNativeComponentState() = default; - -#ifdef ANDROID - FloatPropNativeComponentState(FloatPropNativeComponentState const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; - MapBuffer getMapBuffer() const { - return MapBufferBuilder::EMPTY(); - }; -#endif -}; - -} // namespace react -} // namespace facebook", -} -`; - -exports[`GenerateStateH can generate fixture IMAGE_PROP 1`] = ` -Map { - "States.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateH.js - */ -#pragma once - -#ifdef ANDROID -#include -#include -#include -#endif - -namespace facebook { -namespace react { - -class ImagePropNativeComponentState { -public: - ImagePropNativeComponentState() = default; - -#ifdef ANDROID - ImagePropNativeComponentState(ImagePropNativeComponentState const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; - MapBuffer getMapBuffer() const { - return MapBufferBuilder::EMPTY(); - }; -#endif -}; - -} // namespace react -} // namespace facebook", -} -`; - -exports[`GenerateStateH can generate fixture INSETS_PROP 1`] = ` -Map { - "States.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateH.js - */ -#pragma once - -#ifdef ANDROID -#include -#include -#include -#endif - -namespace facebook { -namespace react { - -class InsetsPropNativeComponentState { -public: - InsetsPropNativeComponentState() = default; - -#ifdef ANDROID - InsetsPropNativeComponentState(InsetsPropNativeComponentState const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; - MapBuffer getMapBuffer() const { - return MapBufferBuilder::EMPTY(); - }; -#endif -}; - -} // namespace react -} // namespace facebook", -} -`; - -exports[`GenerateStateH can generate fixture INT32_ENUM_PROP 1`] = ` -Map { - "States.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateH.js - */ -#pragma once - -#ifdef ANDROID -#include -#include -#include -#endif - -namespace facebook { -namespace react { - -class Int32EnumPropsNativeComponentState { -public: - Int32EnumPropsNativeComponentState() = default; - -#ifdef ANDROID - Int32EnumPropsNativeComponentState(Int32EnumPropsNativeComponentState const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; - MapBuffer getMapBuffer() const { - return MapBufferBuilder::EMPTY(); - }; -#endif -}; - -} // namespace react -} // namespace facebook", -} -`; - -exports[`GenerateStateH can generate fixture INTEGER_PROPS 1`] = ` -Map { - "States.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateH.js - */ -#pragma once - -#ifdef ANDROID -#include -#include -#include -#endif - -namespace facebook { -namespace react { - -class IntegerPropNativeComponentState { -public: - IntegerPropNativeComponentState() = default; - -#ifdef ANDROID - IntegerPropNativeComponentState(IntegerPropNativeComponentState const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; - MapBuffer getMapBuffer() const { - return MapBufferBuilder::EMPTY(); - }; -#endif -}; - -} // namespace react -} // namespace facebook", -} -`; - -exports[`GenerateStateH can generate fixture INTERFACE_ONLY 1`] = ` -Map { - "States.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateH.js - */ -#pragma once - -#ifdef ANDROID -#include -#include -#include -#endif - -namespace facebook { -namespace react { - - - -} // namespace react -} // namespace facebook", -} -`; - -exports[`GenerateStateH can generate fixture MULTI_NATIVE_PROP 1`] = ` -Map { - "States.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateH.js - */ -#pragma once - -#ifdef ANDROID -#include -#include -#include -#endif - -namespace facebook { -namespace react { - -class ImageColorPropNativeComponentState { -public: - ImageColorPropNativeComponentState() = default; - -#ifdef ANDROID - ImageColorPropNativeComponentState(ImageColorPropNativeComponentState const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; - MapBuffer getMapBuffer() const { - return MapBufferBuilder::EMPTY(); - }; -#endif -}; - -} // namespace react -} // namespace facebook", -} -`; - -exports[`GenerateStateH can generate fixture NO_PROPS_NO_EVENTS 1`] = ` -Map { - "States.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateH.js - */ -#pragma once - -#ifdef ANDROID -#include -#include -#include -#endif - -namespace facebook { -namespace react { - -class NoPropsNoEventsComponentState { -public: - NoPropsNoEventsComponentState() = default; - -#ifdef ANDROID - NoPropsNoEventsComponentState(NoPropsNoEventsComponentState const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; - MapBuffer getMapBuffer() const { - return MapBufferBuilder::EMPTY(); - }; -#endif -}; - -} // namespace react -} // namespace facebook", -} -`; - -exports[`GenerateStateH can generate fixture OBJECT_PROPS 1`] = ` -Map { - "States.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateH.js - */ -#pragma once - -#ifdef ANDROID -#include -#include -#include -#endif - -namespace facebook { -namespace react { - -class ObjectPropsState { -public: - ObjectPropsState() = default; - -#ifdef ANDROID - ObjectPropsState(ObjectPropsState const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; - MapBuffer getMapBuffer() const { - return MapBufferBuilder::EMPTY(); - }; -#endif -}; - -} // namespace react -} // namespace facebook", -} -`; - -exports[`GenerateStateH can generate fixture POINT_PROP 1`] = ` -Map { - "States.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateH.js - */ -#pragma once - -#ifdef ANDROID -#include -#include -#include -#endif - -namespace facebook { -namespace react { - -class PointPropNativeComponentState { -public: - PointPropNativeComponentState() = default; - -#ifdef ANDROID - PointPropNativeComponentState(PointPropNativeComponentState const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; - MapBuffer getMapBuffer() const { - return MapBufferBuilder::EMPTY(); - }; -#endif -}; - -} // namespace react -} // namespace facebook", -} -`; - -exports[`GenerateStateH can generate fixture STRING_ENUM_PROP 1`] = ` -Map { - "States.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateH.js - */ -#pragma once - -#ifdef ANDROID -#include -#include -#include -#endif - -namespace facebook { -namespace react { - -class StringEnumPropsNativeComponentState { -public: - StringEnumPropsNativeComponentState() = default; - -#ifdef ANDROID - StringEnumPropsNativeComponentState(StringEnumPropsNativeComponentState const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; - MapBuffer getMapBuffer() const { - return MapBufferBuilder::EMPTY(); - }; -#endif -}; - -} // namespace react -} // namespace facebook", -} -`; - -exports[`GenerateStateH can generate fixture STRING_PROP 1`] = ` -Map { - "States.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateH.js - */ -#pragma once - -#ifdef ANDROID -#include -#include -#include -#endif - -namespace facebook { -namespace react { - -class StringPropComponentState { -public: - StringPropComponentState() = default; - -#ifdef ANDROID - StringPropComponentState(StringPropComponentState const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; - MapBuffer getMapBuffer() const { - return MapBufferBuilder::EMPTY(); - }; -#endif -}; - -} // namespace react -} // namespace facebook", -} -`; - -exports[`GenerateStateH can generate fixture TWO_COMPONENTS_DIFFERENT_FILES 1`] = ` -Map { - "States.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateH.js - */ -#pragma once - -#ifdef ANDROID -#include -#include -#include -#endif - -namespace facebook { -namespace react { - -class MultiFile1NativeComponentState { -public: - MultiFile1NativeComponentState() = default; - -#ifdef ANDROID - MultiFile1NativeComponentState(MultiFile1NativeComponentState const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; - MapBuffer getMapBuffer() const { - return MapBufferBuilder::EMPTY(); - }; -#endif -}; - -class MultiFile2NativeComponentState { -public: - MultiFile2NativeComponentState() = default; - -#ifdef ANDROID - MultiFile2NativeComponentState(MultiFile2NativeComponentState const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; - MapBuffer getMapBuffer() const { - return MapBufferBuilder::EMPTY(); - }; -#endif -}; - -} // namespace react -} // namespace facebook", -} -`; - -exports[`GenerateStateH can generate fixture TWO_COMPONENTS_SAME_FILE 1`] = ` -Map { - "States.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateStateH.js - */ -#pragma once - -#ifdef ANDROID -#include -#include -#include -#endif - -namespace facebook { -namespace react { - -class MultiComponent1NativeComponentState { -public: - MultiComponent1NativeComponentState() = default; - -#ifdef ANDROID - MultiComponent1NativeComponentState(MultiComponent1NativeComponentState const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; - MapBuffer getMapBuffer() const { - return MapBufferBuilder::EMPTY(); - }; -#endif -}; - -class MultiComponent2NativeComponentState { -public: - MultiComponent2NativeComponentState() = default; - -#ifdef ANDROID - MultiComponent2NativeComponentState(MultiComponent2NativeComponentState const &previousState, folly::dynamic data){}; - folly::dynamic getDynamic() const { - return {}; - }; - MapBuffer getMapBuffer() const { - return MapBufferBuilder::EMPTY(); - }; -#endif -}; - -} // namespace react -} // namespace facebook", -} -`; diff --git a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateTests-test.js.snap b/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateTests-test.js.snap deleted file mode 100644 index e8f46ea1f104..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateTests-test.js.snap +++ /dev/null @@ -1,1353 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GenerateTests can generate fixture ARRAY_PROPS 1`] = ` -Map { - "Tests.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateTests.js - * */ - -#include -#include -#include -#include -#include -#include -#include - -using namespace facebook::react; - -TEST(ArrayPropsNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = ArrayPropsNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - ArrayPropsNativeComponentProps(parserContext, sourceProps, rawProps); -}", -} -`; - -exports[`GenerateTests can generate fixture ARRAY_PROPS_WITH_NESTED_OBJECT 1`] = ` -Map { - "Tests.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateTests.js - * */ - -#include -#include -#include -#include -#include -#include - -using namespace facebook::react; - -TEST(ArrayPropsNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = ArrayPropsNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - ArrayPropsNativeComponentProps(parserContext, sourceProps, rawProps); -}", -} -`; - -exports[`GenerateTests can generate fixture BOOLEAN_PROP 1`] = ` -Map { - "Tests.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateTests.js - * */ - -#include -#include -#include -#include -#include -#include - -using namespace facebook::react; - -TEST(BooleanPropNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = BooleanPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - BooleanPropNativeComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(BooleanPropNativeComponentProps_disabled, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = BooleanPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"disabled\\", false)); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - BooleanPropNativeComponentProps(parserContext, sourceProps, rawProps); -}", -} -`; - -exports[`GenerateTests can generate fixture COLOR_PROP 1`] = ` -Map { - "Tests.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateTests.js - * */ - -#include -#include -#include -#include -#include -#include - -using namespace facebook::react; - -TEST(ColorPropNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = ColorPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - ColorPropNativeComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(ColorPropNativeComponentProps_tintColor, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = ColorPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"tintColor\\", 1)); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - ColorPropNativeComponentProps(parserContext, sourceProps, rawProps); -}", -} -`; - -exports[`GenerateTests can generate fixture COMMANDS 1`] = ` -Map { - "Tests.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateTests.js - * */ - -#include -#include -#include -#include -#include -#include - -using namespace facebook::react; - -TEST(CommandNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = CommandNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - CommandNativeComponentProps(parserContext, sourceProps, rawProps); -}", -} -`; - -exports[`GenerateTests can generate fixture COMMANDS_AND_PROPS 1`] = ` -Map { - "Tests.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateTests.js - * */ - -#include -#include -#include -#include -#include -#include - -using namespace facebook::react; - -TEST(CommandNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = CommandNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - CommandNativeComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(CommandNativeComponentProps_accessibilityHint, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = CommandNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"accessibilityHint\\", \\"foo\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - CommandNativeComponentProps(parserContext, sourceProps, rawProps); -}", -} -`; - -exports[`GenerateTests can generate fixture DOUBLE_PROPS 1`] = ` -Map { - "Tests.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateTests.js - * */ - -#include -#include -#include -#include -#include -#include - -using namespace facebook::react; - -TEST(DoublePropNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = DoublePropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - DoublePropNativeComponentProps(parserContext, sourceProps, rawProps); -}", -} -`; - -exports[`GenerateTests can generate fixture EVENT_NESTED_OBJECT_PROPS 1`] = ` -Map { - "Tests.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateTests.js - * */ - -#include -#include -#include -#include -#include -#include - -using namespace facebook::react; - -TEST(EventsNestedObjectNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = EventsNestedObjectNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - EventsNestedObjectNativeComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(EventsNestedObjectNativeComponentProps_disabled, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = EventsNestedObjectNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"disabled\\", false)); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - EventsNestedObjectNativeComponentProps(parserContext, sourceProps, rawProps); -}", -} -`; - -exports[`GenerateTests can generate fixture EVENT_PROPS 1`] = ` -Map { - "Tests.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateTests.js - * */ - -#include -#include -#include -#include -#include -#include - -using namespace facebook::react; - -TEST(EventsNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = EventsNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - EventsNativeComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(EventsNativeComponentProps_disabled, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = EventsNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"disabled\\", false)); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - EventsNativeComponentProps(parserContext, sourceProps, rawProps); -}", -} -`; - -exports[`GenerateTests can generate fixture EVENTS_WITH_PAPER_NAME 1`] = ` -Map { - "Tests.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateTests.js - * */ - -#include -#include -#include -#include -#include -#include - -using namespace facebook::react; - -TEST(InterfaceOnlyComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = InterfaceOnlyComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - InterfaceOnlyComponentProps(parserContext, sourceProps, rawProps); -}", -} -`; - -exports[`GenerateTests can generate fixture EXCLUDE_ANDROID 1`] = ` -Map { - "Tests.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateTests.js - * */ - -#include -#include -#include -#include -#include -#include - -using namespace facebook::react; - -TEST(ExcludedAndroidComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = ExcludedAndroidComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - ExcludedAndroidComponentProps(parserContext, sourceProps, rawProps); -}", -} -`; - -exports[`GenerateTests can generate fixture EXCLUDE_ANDROID_IOS 1`] = ` -Map { - "Tests.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateTests.js - * */ - -#include -#include -#include -#include -#include -#include - -using namespace facebook::react; - -TEST(ExcludedAndroidIosComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = ExcludedAndroidIosComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - ExcludedAndroidIosComponentProps(parserContext, sourceProps, rawProps); -}", -} -`; - -exports[`GenerateTests can generate fixture EXCLUDE_IOS_TWO_COMPONENTS_DIFFERENT_FILES 1`] = ` -Map { - "Tests.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateTests.js - * */ - -#include -#include -#include -#include -#include -#include - -using namespace facebook::react; - -TEST(ExcludedIosComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = ExcludedIosComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - ExcludedIosComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(MultiFileIncludedNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = MultiFileIncludedNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - MultiFileIncludedNativeComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(MultiFileIncludedNativeComponentProps_disabled, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = MultiFileIncludedNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"disabled\\", true)); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - MultiFileIncludedNativeComponentProps(parserContext, sourceProps, rawProps); -}", -} -`; - -exports[`GenerateTests can generate fixture FLOAT_PROPS 1`] = ` -Map { - "Tests.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateTests.js - * */ - -#include -#include -#include -#include -#include -#include - -using namespace facebook::react; - -TEST(FloatPropNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = FloatPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - FloatPropNativeComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(FloatPropNativeComponentProps_blurRadius, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = FloatPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"blurRadius\\", 0)); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - FloatPropNativeComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(FloatPropNativeComponentProps_blurRadius2, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = FloatPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"blurRadius2\\", 0.001)); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - FloatPropNativeComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(FloatPropNativeComponentProps_blurRadius3, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = FloatPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"blurRadius3\\", 2.1)); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - FloatPropNativeComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(FloatPropNativeComponentProps_blurRadius4, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = FloatPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"blurRadius4\\", 0)); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - FloatPropNativeComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(FloatPropNativeComponentProps_blurRadius5, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = FloatPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"blurRadius5\\", 1)); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - FloatPropNativeComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(FloatPropNativeComponentProps_blurRadius6, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = FloatPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"blurRadius6\\", 0)); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - FloatPropNativeComponentProps(parserContext, sourceProps, rawProps); -}", -} -`; - -exports[`GenerateTests can generate fixture IMAGE_PROP 1`] = ` -Map { - "Tests.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateTests.js - * */ - -#include -#include -#include -#include -#include -#include -#include - -using namespace facebook::react; - -TEST(ImagePropNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = ImagePropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - ImagePropNativeComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(ImagePropNativeComponentProps_thumbImage, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = ImagePropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"thumbImage\\", folly::dynamic::object(\\"url\\", \\"testurl\\"))); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - ImagePropNativeComponentProps(parserContext, sourceProps, rawProps); -}", -} -`; - -exports[`GenerateTests can generate fixture INSETS_PROP 1`] = ` -Map { - "Tests.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateTests.js - * */ - -#include -#include -#include -#include -#include -#include - -using namespace facebook::react; - -TEST(InsetsPropNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = InsetsPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - InsetsPropNativeComponentProps(parserContext, sourceProps, rawProps); -}", -} -`; - -exports[`GenerateTests can generate fixture INT32_ENUM_PROP 1`] = ` -Map { - "Tests.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateTests.js - * */ - -#include -#include -#include -#include -#include -#include - -using namespace facebook::react; - -TEST(Int32EnumPropsNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = Int32EnumPropsNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - Int32EnumPropsNativeComponentProps(parserContext, sourceProps, rawProps); -}", -} -`; - -exports[`GenerateTests can generate fixture INTEGER_PROPS 1`] = ` -Map { - "Tests.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateTests.js - * */ - -#include -#include -#include -#include -#include -#include - -using namespace facebook::react; - -TEST(IntegerPropNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = IntegerPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - IntegerPropNativeComponentProps(parserContext, sourceProps, rawProps); -}", -} -`; - -exports[`GenerateTests can generate fixture INTERFACE_ONLY 1`] = ` -Map { - "Tests.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateTests.js - * */ - -#include -#include -#include -#include -#include -#include - -using namespace facebook::react; - -TEST(InterfaceOnlyComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = InterfaceOnlyComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - InterfaceOnlyComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(InterfaceOnlyComponentProps_accessibilityHint, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = InterfaceOnlyComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"accessibilityHint\\", \\"foo\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - InterfaceOnlyComponentProps(parserContext, sourceProps, rawProps); -}", -} -`; - -exports[`GenerateTests can generate fixture MULTI_NATIVE_PROP 1`] = ` -Map { - "Tests.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateTests.js - * */ - -#include -#include -#include -#include -#include -#include -#include - -using namespace facebook::react; - -TEST(ImageColorPropNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = ImageColorPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - ImageColorPropNativeComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(ImageColorPropNativeComponentProps_thumbImage, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = ImageColorPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"thumbImage\\", folly::dynamic::object(\\"url\\", \\"testurl\\"))); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - ImageColorPropNativeComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(ImageColorPropNativeComponentProps_color, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = ImageColorPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"color\\", 1)); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - ImageColorPropNativeComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(ImageColorPropNativeComponentProps_thumbTintColor, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = ImageColorPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"thumbTintColor\\", 1)); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - ImageColorPropNativeComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(ImageColorPropNativeComponentProps_point, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = ImageColorPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"point\\", folly::dynamic::object(\\"x\\", 1)(\\"y\\", 1))); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - ImageColorPropNativeComponentProps(parserContext, sourceProps, rawProps); -}", -} -`; - -exports[`GenerateTests can generate fixture NO_PROPS_NO_EVENTS 1`] = ` -Map { - "Tests.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateTests.js - * */ - -#include -#include -#include -#include -#include -#include - -using namespace facebook::react; - -TEST(NoPropsNoEventsComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = NoPropsNoEventsComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - NoPropsNoEventsComponentProps(parserContext, sourceProps, rawProps); -}", -} -`; - -exports[`GenerateTests can generate fixture OBJECT_PROPS 1`] = ` -Map { - "Tests.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateTests.js - * */ - -#include -#include -#include -#include -#include -#include -#include - -using namespace facebook::react; - -TEST(ObjectPropsProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = ObjectPropsProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - ObjectPropsProps(parserContext, sourceProps, rawProps); -}", -} -`; - -exports[`GenerateTests can generate fixture POINT_PROP 1`] = ` -Map { - "Tests.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateTests.js - * */ - -#include -#include -#include -#include -#include -#include - -using namespace facebook::react; - -TEST(PointPropNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = PointPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - PointPropNativeComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(PointPropNativeComponentProps_startPoint, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = PointPropNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"startPoint\\", folly::dynamic::object(\\"x\\", 1)(\\"y\\", 1))); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - PointPropNativeComponentProps(parserContext, sourceProps, rawProps); -}", -} -`; - -exports[`GenerateTests can generate fixture STRING_ENUM_PROP 1`] = ` -Map { - "Tests.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateTests.js - * */ - -#include -#include -#include -#include -#include -#include - -using namespace facebook::react; - -TEST(StringEnumPropsNativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = StringEnumPropsNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - StringEnumPropsNativeComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(StringEnumPropsNativeComponentProps_alignment_Top, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = StringEnumPropsNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"alignment\\", \\"top\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - StringEnumPropsNativeComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(StringEnumPropsNativeComponentProps_alignment_Center, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = StringEnumPropsNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"alignment\\", \\"center\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - StringEnumPropsNativeComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(StringEnumPropsNativeComponentProps_alignment_BottomRight, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = StringEnumPropsNativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"alignment\\", \\"bottom-right\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - StringEnumPropsNativeComponentProps(parserContext, sourceProps, rawProps); -}", -} -`; - -exports[`GenerateTests can generate fixture STRING_PROP 1`] = ` -Map { - "Tests.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateTests.js - * */ - -#include -#include -#include -#include -#include -#include - -using namespace facebook::react; - -TEST(StringPropComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = StringPropComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - StringPropComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(StringPropComponentProps_accessibilityHint, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = StringPropComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"accessibilityHint\\", \\"foo\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - StringPropComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(StringPropComponentProps_accessibilityRole, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = StringPropComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"accessibilityRole\\", \\"foo\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - StringPropComponentProps(parserContext, sourceProps, rawProps); -}", -} -`; - -exports[`GenerateTests can generate fixture TWO_COMPONENTS_DIFFERENT_FILES 1`] = ` -Map { - "Tests.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateTests.js - * */ - -#include -#include -#include -#include -#include -#include - -using namespace facebook::react; - -TEST(MultiFile1NativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = MultiFile1NativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - MultiFile1NativeComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(MultiFile1NativeComponentProps_disabled, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = MultiFile1NativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"disabled\\", false)); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - MultiFile1NativeComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(MultiFile2NativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = MultiFile2NativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - MultiFile2NativeComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(MultiFile2NativeComponentProps_disabled, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = MultiFile2NativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"disabled\\", true)); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - MultiFile2NativeComponentProps(parserContext, sourceProps, rawProps); -}", -} -`; - -exports[`GenerateTests can generate fixture TWO_COMPONENTS_SAME_FILE 1`] = ` -Map { - "Tests.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateTests.js - * */ - -#include -#include -#include -#include -#include -#include - -using namespace facebook::react; - -TEST(MultiComponent1NativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = MultiComponent1NativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - MultiComponent1NativeComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(MultiComponent1NativeComponentProps_disabled, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = MultiComponent1NativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"disabled\\", false)); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - MultiComponent1NativeComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(MultiComponent2NativeComponentProps_DoesNotDie, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = MultiComponent2NativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"xx_invalid_xx\\", \\"xx_invalid_xx\\")); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - MultiComponent2NativeComponentProps(parserContext, sourceProps, rawProps); -} - -TEST(MultiComponent2NativeComponentProps_disabled, etc) { - auto propParser = RawPropsParser(); - propParser.prepare(); - auto const &sourceProps = MultiComponent2NativeComponentProps(); - auto const &rawProps = RawProps(folly::dynamic::object(\\"disabled\\", true)); - - ContextContainer contextContainer{}; - PropsParserContext parserContext{-1, contextContainer}; - - rawProps.parse(propParser, parserContext); - MultiComponent2NativeComponentProps(parserContext, sourceProps, rawProps); -}", -} -`; diff --git a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateThirdPartyFabricComponentsProviderH-test.js.snap b/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateThirdPartyFabricComponentsProviderH-test.js.snap deleted file mode 100644 index 4cab36433d24..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateThirdPartyFabricComponentsProviderH-test.js.snap +++ /dev/null @@ -1,64 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GenerateThirdPartyFabricComponentsProviderH can generate fixtures 1`] = ` -Map { - "RCTThirdPartyFabricComponentsProvider.h" => " -/* - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by GenerateRCTThirdPartyFabricComponentsProviderH - */ - -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored \\"-Wreturn-type-c-linkage\\" - -#import - -#ifdef __cplusplus -extern \\"C\\" { -#endif - -Class RCTThirdPartyFabricComponentsProvider(const char *name); - -Class NoPropsNoEventsComponentCls(void) __attribute__((used)); // NO_PROPS_NO_EVENTS -Class InterfaceOnlyComponentCls(void) __attribute__((used)); // INTERFACE_ONLY -Class BooleanPropNativeComponentCls(void) __attribute__((used)); // BOOLEAN_PROP -Class StringPropComponentCls(void) __attribute__((used)); // STRING_PROP -Class IntegerPropNativeComponentCls(void) __attribute__((used)); // INTEGER_PROPS -Class DoublePropNativeComponentCls(void) __attribute__((used)); // DOUBLE_PROPS -Class FloatPropNativeComponentCls(void) __attribute__((used)); // FLOAT_PROPS -Class ColorPropNativeComponentCls(void) __attribute__((used)); // COLOR_PROP -Class ImagePropNativeComponentCls(void) __attribute__((used)); // IMAGE_PROP -Class PointPropNativeComponentCls(void) __attribute__((used)); // POINT_PROP -Class InsetsPropNativeComponentCls(void) __attribute__((used)); // INSETS_PROP -Class ArrayPropsNativeComponentCls(void) __attribute__((used)); // ARRAY_PROPS -Class ArrayPropsNativeComponentCls(void) __attribute__((used)); // ARRAY_PROPS_WITH_NESTED_OBJECT -Class ObjectPropsCls(void) __attribute__((used)); // OBJECT_PROPS -Class ImageColorPropNativeComponentCls(void) __attribute__((used)); // MULTI_NATIVE_PROP -Class StringEnumPropsNativeComponentCls(void) __attribute__((used)); // STRING_ENUM_PROP -Class Int32EnumPropsNativeComponentCls(void) __attribute__((used)); // INT32_ENUM_PROP -Class EventsNativeComponentCls(void) __attribute__((used)); // EVENT_PROPS -Class InterfaceOnlyComponentCls(void) __attribute__((used)); // EVENTS_WITH_PAPER_NAME -Class EventsNestedObjectNativeComponentCls(void) __attribute__((used)); // EVENT_NESTED_OBJECT_PROPS -Class MultiComponent1NativeComponentCls(void) __attribute__((used)); // TWO_COMPONENTS_SAME_FILE -Class MultiComponent2NativeComponentCls(void) __attribute__((used)); // TWO_COMPONENTS_SAME_FILE -Class MultiFile1NativeComponentCls(void) __attribute__((used)); // TWO_COMPONENTS_DIFFERENT_FILES -Class MultiFile2NativeComponentCls(void) __attribute__((used)); // TWO_COMPONENTS_DIFFERENT_FILES -Class CommandNativeComponentCls(void) __attribute__((used)); // COMMANDS -Class CommandNativeComponentCls(void) __attribute__((used)); // COMMANDS_AND_PROPS -Class ExcludedAndroidComponentCls(void) __attribute__((used)); // EXCLUDE_ANDROID - -Class MultiFileIncludedNativeComponentCls(void) __attribute__((used)); // EXCLUDE_IOS_TWO_COMPONENTS_DIFFERENT_FILES - -#ifdef __cplusplus -} -#endif - -#pragma GCC diagnostic pop - -", -} -`; diff --git a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateThirdPartyFabricComponentsProviderObjCpp-test.js.snap b/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateThirdPartyFabricComponentsProviderObjCpp-test.js.snap deleted file mode 100644 index 0fa2add3459f..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateThirdPartyFabricComponentsProviderObjCpp-test.js.snap +++ /dev/null @@ -1,90 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GenerateThirdPartyFabricComponentsProviderObjCpp can generate fixtures 1`] = ` -Map { - "RCTThirdPartyFabricComponentsProvider.mm" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by GenerateRCTThirdPartyFabricComponentsProviderCpp - */ - -// OSS-compatibility layer - -#import \\"RCTThirdPartyFabricComponentsProvider.h\\" - -#import -#import - -Class RCTThirdPartyFabricComponentsProvider(const char *name) { - static std::unordered_map sFabricComponentsClassMap = { - - {\\"NoPropsNoEventsComponent\\", NoPropsNoEventsComponentCls}, // NO_PROPS_NO_EVENTS - - {\\"InterfaceOnlyComponent\\", InterfaceOnlyComponentCls}, // INTERFACE_ONLY - - {\\"BooleanPropNativeComponent\\", BooleanPropNativeComponentCls}, // BOOLEAN_PROP - - {\\"StringPropComponent\\", StringPropComponentCls}, // STRING_PROP - - {\\"IntegerPropNativeComponent\\", IntegerPropNativeComponentCls}, // INTEGER_PROPS - - {\\"DoublePropNativeComponent\\", DoublePropNativeComponentCls}, // DOUBLE_PROPS - - {\\"FloatPropNativeComponent\\", FloatPropNativeComponentCls}, // FLOAT_PROPS - - {\\"ColorPropNativeComponent\\", ColorPropNativeComponentCls}, // COLOR_PROP - - {\\"ImagePropNativeComponent\\", ImagePropNativeComponentCls}, // IMAGE_PROP - - {\\"PointPropNativeComponent\\", PointPropNativeComponentCls}, // POINT_PROP - - {\\"InsetsPropNativeComponent\\", InsetsPropNativeComponentCls}, // INSETS_PROP - - {\\"ArrayPropsNativeComponent\\", ArrayPropsNativeComponentCls}, // ARRAY_PROPS - - {\\"ArrayPropsNativeComponent\\", ArrayPropsNativeComponentCls}, // ARRAY_PROPS_WITH_NESTED_OBJECT - - {\\"ObjectProps\\", ObjectPropsCls}, // OBJECT_PROPS - - {\\"ImageColorPropNativeComponent\\", ImageColorPropNativeComponentCls}, // MULTI_NATIVE_PROP - - {\\"StringEnumPropsNativeComponent\\", StringEnumPropsNativeComponentCls}, // STRING_ENUM_PROP - - {\\"Int32EnumPropsNativeComponent\\", Int32EnumPropsNativeComponentCls}, // INT32_ENUM_PROP - - {\\"EventsNativeComponent\\", EventsNativeComponentCls}, // EVENT_PROPS - - {\\"InterfaceOnlyComponent\\", InterfaceOnlyComponentCls}, // EVENTS_WITH_PAPER_NAME - - {\\"EventsNestedObjectNativeComponent\\", EventsNestedObjectNativeComponentCls}, // EVENT_NESTED_OBJECT_PROPS - - {\\"MultiComponent1NativeComponent\\", MultiComponent1NativeComponentCls}, // TWO_COMPONENTS_SAME_FILE, - {\\"MultiComponent2NativeComponent\\", MultiComponent2NativeComponentCls}, // TWO_COMPONENTS_SAME_FILE - - {\\"MultiFile1NativeComponent\\", MultiFile1NativeComponentCls}, // TWO_COMPONENTS_DIFFERENT_FILES, - {\\"MultiFile2NativeComponent\\", MultiFile2NativeComponentCls}, // TWO_COMPONENTS_DIFFERENT_FILES - - {\\"CommandNativeComponent\\", CommandNativeComponentCls}, // COMMANDS - - {\\"CommandNativeComponent\\", CommandNativeComponentCls}, // COMMANDS_AND_PROPS - - {\\"ExcludedAndroidComponent\\", ExcludedAndroidComponentCls}, // EXCLUDE_ANDROID - - - {\\"MultiFileIncludedNativeComponent\\", MultiFileIncludedNativeComponentCls}, // EXCLUDE_IOS_TWO_COMPONENTS_DIFFERENT_FILES - }; - - auto p = sFabricComponentsClassMap.find(name); - if (p != sFabricComponentsClassMap.end()) { - auto classFunc = p->second; - return classFunc(); - } - return nil; -} -", -} -`; diff --git a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateViewConfigJs-test.js.snap b/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateViewConfigJs-test.js.snap deleted file mode 100644 index a48a2426a815..000000000000 --- a/packages/react-native-codegen/src/generators/components/__tests__/__snapshots__/GenerateViewConfigJs-test.js.snap +++ /dev/null @@ -1,1133 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GenerateViewConfigJs can generate fixture ARRAY_PROPS 1`] = ` -Map { - "ARRAY_PROPSNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'ArrayPropsNativeComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'ArrayPropsNativeComponent', - - validAttributes: { - names: true, - disableds: true, - progress: true, - radii: true, - - colors: { - process: require('react-native/Libraries/StyleSheet/processColorArray'), - }, - - srcs: true, - points: true, - sizes: true, - object: true, - array: true, - arrayOfArrayOfObject: true, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate fixture ARRAY_PROPS_WITH_NESTED_OBJECT 1`] = ` -Map { - "ARRAY_PROPS_WITH_NESTED_OBJECTNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'ArrayPropsNativeComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'ArrayPropsNativeComponent', - - validAttributes: { - nativePrimitives: true, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate fixture BOOLEAN_PROP 1`] = ` -Map { - "BOOLEAN_PROPNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'BooleanPropNativeComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'BooleanPropNativeComponent', - - validAttributes: { - disabled: true, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate fixture COLOR_PROP 1`] = ` -Map { - "COLOR_PROPNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'ColorPropNativeComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'ColorPropNativeComponent', - - validAttributes: { - tintColor: { - process: require('react-native/Libraries/StyleSheet/processColor'), - }, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate fixture COMMANDS 1`] = ` -Map { - "COMMANDSNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); -const {dispatchCommand} = require(\\"react-native/Libraries/ReactNative/RendererProxy\\"); - -let nativeComponentName = 'CommandNativeComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'CommandNativeComponent', - validAttributes: {}, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); - -export const Commands = { - flashScrollIndicators(ref) { - dispatchCommand(ref, \\"flashScrollIndicators\\", []); - }, - - allTypes(ref, x, y, z, message, animated) { - dispatchCommand(ref, \\"allTypes\\", [x, y, z, message, animated]); - } -}; -", -} -`; - -exports[`GenerateViewConfigJs can generate fixture COMMANDS_AND_PROPS 1`] = ` -Map { - "COMMANDS_AND_PROPSNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); -const {dispatchCommand} = require(\\"react-native/Libraries/ReactNative/RendererProxy\\"); - -let nativeComponentName = 'CommandNativeComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'CommandNativeComponent', - - validAttributes: { - accessibilityHint: true, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); - -export const Commands = { - handleRootTag(ref, rootTag) { - dispatchCommand(ref, \\"handleRootTag\\", [rootTag]); - }, - - hotspotUpdate(ref, x, y) { - dispatchCommand(ref, \\"hotspotUpdate\\", [x, y]); - } -}; -", -} -`; - -exports[`GenerateViewConfigJs can generate fixture DOUBLE_PROPS 1`] = ` -Map { - "DOUBLE_PROPSNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'DoublePropNativeComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'DoublePropNativeComponent', - - validAttributes: { - blurRadius: true, - blurRadius2: true, - blurRadius3: true, - blurRadius4: true, - blurRadius5: true, - blurRadius6: true, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate fixture EVENT_NESTED_OBJECT_PROPS 1`] = ` -Map { - "EVENT_NESTED_OBJECT_PROPSNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); -const {ConditionallyIgnoredEventHandlers} = require('react-native/Libraries/NativeComponent/ViewConfigIgnore'); - -let nativeComponentName = 'EventsNestedObjectNativeComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'EventsNestedObjectNativeComponent', - - bubblingEventTypes: { - topChange: { - phasedRegistrationNames: { - captured: 'onChangeCapture', - bubbled: 'onChange', - }, - }, - }, - - validAttributes: { - disabled: true, - - ...ConditionallyIgnoredEventHandlers({ - onChange: true, - }), - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate fixture EVENT_PROPS 1`] = ` -Map { - "EVENT_PROPSNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); -const {ConditionallyIgnoredEventHandlers} = require('react-native/Libraries/NativeComponent/ViewConfigIgnore'); - -let nativeComponentName = 'EventsNativeComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'EventsNativeComponent', - - bubblingEventTypes: { - topChange: { - phasedRegistrationNames: { - captured: 'onChangeCapture', - bubbled: 'onChange', - }, - }, - - topEnd: { - phasedRegistrationNames: { - captured: 'onEndCapture', - bubbled: 'onEnd', - }, - }, - }, - - directEventTypes: { - topEventDirect: { - registrationName: 'onEventDirect', - }, - - topOrientationChange: { - registrationName: 'onOrientationChange', - }, - }, - - validAttributes: { - disabled: true, - - ...ConditionallyIgnoredEventHandlers({ - onChange: true, - onEventDirect: true, - onOrientationChange: true, - onEnd: true, - }), - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate fixture EVENTS_WITH_PAPER_NAME 1`] = ` -Map { - "EVENTS_WITH_PAPER_NAMENativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); -const {ConditionallyIgnoredEventHandlers} = require('react-native/Libraries/NativeComponent/ViewConfigIgnore'); - -let nativeComponentName = 'RCTInterfaceOnlyComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'RCTInterfaceOnlyComponent', - - bubblingEventTypes: { - paperChange: { - phasedRegistrationNames: { - captured: 'onChangeCapture', - bubbled: 'onChange', - }, - }, - }, - - directEventTypes: { - paperDirectChange: { - registrationName: 'onDire tChange', - }, - }, - - validAttributes: { - ...ConditionallyIgnoredEventHandlers({ - onChange: true, - onDire tChange: true, - }), - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate fixture EXCLUDE_ANDROID 1`] = ` -Map { - "EXCLUDE_ANDROIDNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'ExcludedAndroidComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'ExcludedAndroidComponent', - validAttributes: {}, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate fixture EXCLUDE_ANDROID_IOS 1`] = ` -Map { - "EXCLUDE_ANDROID_IOSNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'ExcludedAndroidIosComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'ExcludedAndroidIosComponent', - validAttributes: {}, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate fixture EXCLUDE_IOS_TWO_COMPONENTS_DIFFERENT_FILES 1`] = ` -Map { - "EXCLUDE_IOS_TWO_COMPONENTS_DIFFERENT_FILESNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'ExcludedIosComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'ExcludedIosComponent', - validAttributes: {}, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); - -let nativeComponentName = 'MultiFileIncludedNativeComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'MultiFileIncludedNativeComponent', - - validAttributes: { - disabled: true, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate fixture FLOAT_PROPS 1`] = ` -Map { - "FLOAT_PROPSNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'FloatPropNativeComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'FloatPropNativeComponent', - - validAttributes: { - blurRadius: true, - blurRadius2: true, - blurRadius3: true, - blurRadius4: true, - blurRadius5: true, - blurRadius6: true, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate fixture IMAGE_PROP 1`] = ` -Map { - "IMAGE_PROPNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'ImagePropNativeComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'ImagePropNativeComponent', - - validAttributes: { - thumbImage: { - process: require('react-native/Libraries/Image/resolveAssetSource'), - }, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate fixture INSETS_PROP 1`] = ` -Map { - "INSETS_PROPNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'InsetsPropNativeComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'InsetsPropNativeComponent', - - validAttributes: { - contentInset: { - diff: require('react-native/Libraries/Utilities/differ/insetsDiffer'), - }, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate fixture INT32_ENUM_PROP 1`] = ` -Map { - "INT32_ENUM_PROPNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'Int32EnumPropsNativeComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'Int32EnumPropsNativeComponent', - - validAttributes: { - maxInterval: true, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate fixture INTEGER_PROPS 1`] = ` -Map { - "INTEGER_PROPSNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'IntegerPropNativeComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'IntegerPropNativeComponent', - - validAttributes: { - progress1: true, - progress2: true, - progress3: true, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate fixture INTERFACE_ONLY 1`] = ` -Map { - "INTERFACE_ONLYNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); -const {ConditionallyIgnoredEventHandlers} = require('react-native/Libraries/NativeComponent/ViewConfigIgnore'); - -let nativeComponentName = 'RCTInterfaceOnlyComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'RCTInterfaceOnlyComponent', - - bubblingEventTypes: { - topChange: { - phasedRegistrationNames: { - captured: 'onChangeCapture', - bubbled: 'onChange', - }, - }, - }, - - validAttributes: { - accessibilityHint: true, - - ...ConditionallyIgnoredEventHandlers({ - onChange: true, - }), - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate fixture MULTI_NATIVE_PROP 1`] = ` -Map { - "MULTI_NATIVE_PROPNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'ImageColorPropNativeComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'ImageColorPropNativeComponent', - - validAttributes: { - thumbImage: { - process: require('react-native/Libraries/Image/resolveAssetSource'), - }, - - color: { - process: require('react-native/Libraries/StyleSheet/processColor'), - }, - - thumbTintColor: { - process: require('react-native/Libraries/StyleSheet/processColor'), - }, - - point: { - diff: require('react-native/Libraries/Utilities/differ/pointsDiffer'), - }, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate fixture NO_PROPS_NO_EVENTS 1`] = ` -Map { - "NO_PROPS_NO_EVENTSNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'NoPropsNoEventsComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'NoPropsNoEventsComponent', - validAttributes: {}, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate fixture OBJECT_PROPS 1`] = ` -Map { - "OBJECT_PROPSNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'ObjectProps'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'ObjectProps', - - validAttributes: { - objectProp: true, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate fixture POINT_PROP 1`] = ` -Map { - "POINT_PROPNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'PointPropNativeComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'PointPropNativeComponent', - - validAttributes: { - startPoint: { - diff: require('react-native/Libraries/Utilities/differ/pointsDiffer'), - }, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate fixture STRING_ENUM_PROP 1`] = ` -Map { - "STRING_ENUM_PROPNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'StringEnumPropsNativeComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'StringEnumPropsNativeComponent', - - validAttributes: { - alignment: true, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate fixture STRING_PROP 1`] = ` -Map { - "STRING_PROPNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'StringPropComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'StringPropComponent', - - validAttributes: { - accessibilityHint: true, - accessibilityRole: true, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate fixture TWO_COMPONENTS_DIFFERENT_FILES 1`] = ` -Map { - "TWO_COMPONENTS_DIFFERENT_FILESNativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'MultiFile1NativeComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'MultiFile1NativeComponent', - - validAttributes: { - disabled: true, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); - -let nativeComponentName = 'MultiFile2NativeComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'MultiFile2NativeComponent', - - validAttributes: { - disabled: true, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate fixture TWO_COMPONENTS_SAME_FILE 1`] = ` -Map { - "TWO_COMPONENTS_SAME_FILENativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); - -let nativeComponentName = 'MultiComponent1NativeComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'MultiComponent1NativeComponent', - - validAttributes: { - disabled: true, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); - -let nativeComponentName = 'MultiComponent2NativeComponent'; - - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'MultiComponent2NativeComponent', - - validAttributes: { - disabled: true, - }, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; - -exports[`GenerateViewConfigJs can generate fixture with a deprecated view config name 1`] = ` -Map { - "DEPRECATED_VIEW_CONFIG_NAMENativeViewConfig.js" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @flow - * - * @generated by codegen project: GenerateViewConfigJs.js - */ - -'use strict'; - -const NativeComponentRegistry = require('react-native/Libraries/NativeComponent/NativeComponentRegistry'); -const {UIManager} = require(\\"react-native\\") - -let nativeComponentName = 'NativeComponentName'; -if (UIManager.hasViewManagerConfig('NativeComponentName')) { - nativeComponentName = 'NativeComponentName'; -} else if (UIManager.hasViewManagerConfig('DeprecatedNativeComponentName')) { - nativeComponentName = 'DeprecatedNativeComponentName'; -} else { - throw new Error('Failed to find native component for either \\"NativeComponentName\\" or \\"DeprecatedNativeComponentName\\"'); -} - -export const __INTERNAL_VIEW_CONFIG = { - uiViewClassName: 'NativeComponentName', - validAttributes: {}, -}; - -export default NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG); -", -} -`; diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleCpp.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleCpp.js deleted file mode 100644 index 159c05f13006..000000000000 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleCpp.js +++ /dev/null @@ -1,279 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type { - SchemaType, - Nullable, - NamedShape, - NativeModulePropertyShape, - NativeModuleFunctionTypeAnnotation, - NativeModuleParamTypeAnnotation, - NativeModuleTypeAnnotation, -} from '../../CodegenSchema'; - -import type {AliasResolver} from './Utils'; -const {createAliasResolver, getModules} = require('./Utils'); -const {unwrapNullable} = require('../../parsers/parsers-commons'); - -type FilesOutput = Map; - -const HostFunctionTemplate = ({ - hasteModuleName, - methodName, - returnTypeAnnotation, - args, -}: $ReadOnly<{ - hasteModuleName: string, - methodName: string, - returnTypeAnnotation: Nullable, - args: Array, -}>) => { - const isNullable = returnTypeAnnotation.type === 'NullableTypeAnnotation'; - const isVoid = returnTypeAnnotation.type === 'VoidTypeAnnotation'; - const methodCallArgs = ['rt', ...args].join(', '); - const methodCall = `static_cast<${hasteModuleName}CxxSpecJSI *>(&turboModule)->${methodName}(${methodCallArgs})`; - - return `static jsi::Value __hostFunction_${hasteModuleName}CxxSpecJSI_${methodName}(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) {${ - isVoid - ? `\n ${methodCall};` - : isNullable - ? `\n auto result = ${methodCall};` - : '' - } - return ${ - isVoid - ? 'jsi::Value::undefined()' - : isNullable - ? 'result ? jsi::Value(std::move(*result)) : jsi::Value::null()' - : methodCall - }; -}`; -}; - -const ModuleTemplate = ({ - hasteModuleName, - hostFunctions, - moduleName, - methods, -}: $ReadOnly<{ - hasteModuleName: string, - hostFunctions: $ReadOnlyArray, - moduleName: string, - methods: $ReadOnlyArray<$ReadOnly<{methodName: string, paramCount: number}>>, -}>) => { - return `${hostFunctions.join('\n')} - -${hasteModuleName}CxxSpecJSI::${hasteModuleName}CxxSpecJSI(std::shared_ptr jsInvoker) - : TurboModule("${moduleName}", jsInvoker) { -${methods - .map(({methodName, paramCount}) => { - return ` methodMap_["${methodName}"] = MethodMetadata {${paramCount}, __hostFunction_${hasteModuleName}CxxSpecJSI_${methodName}};`; - }) - .join('\n')} -}`; -}; - -const FileTemplate = ({ - libraryName, - modules, -}: $ReadOnly<{ - libraryName: string, - modules: string, -}>) => { - return `/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * ${'@'}generated by codegen project: GenerateModuleH.js - */ - -#include "${libraryName}JSI.h" - -namespace facebook { -namespace react { - -${modules} - - -} // namespace react -} // namespace facebook -`; -}; - -type Param = NamedShape>; - -function serializeArg( - arg: Param, - index: number, - resolveAlias: AliasResolver, -): string { - const {typeAnnotation: nullableTypeAnnotation, optional} = arg; - const [typeAnnotation, nullable] = - unwrapNullable(nullableTypeAnnotation); - const isRequired = !optional && !nullable; - - let realTypeAnnotation = typeAnnotation; - if (realTypeAnnotation.type === 'TypeAliasTypeAnnotation') { - realTypeAnnotation = resolveAlias(realTypeAnnotation.name); - } - - function wrap(callback: (val: string) => string) { - const val = `args[${index}]`; - const expression = callback(val); - if (isRequired) { - return expression; - } else { - let condition = `${val}.isNull() || ${val}.isUndefined()`; - if (optional) { - condition = `count < ${index} || ${condition}`; - } - return `${condition} ? std::nullopt : std::make_optional(${expression})`; - } - } - - switch (realTypeAnnotation.type) { - case 'ReservedTypeAnnotation': - switch (realTypeAnnotation.name) { - case 'RootTag': - return wrap(val => `${val}.getNumber()`); - default: - (realTypeAnnotation.name: empty); - throw new Error( - `Unknown prop type for "${arg.name}, found: ${realTypeAnnotation.name}"`, - ); - } - case 'StringTypeAnnotation': - return wrap(val => `${val}.asString(rt)`); - case 'BooleanTypeAnnotation': - return wrap(val => `${val}.asBool()`); - case 'EnumDeclaration': - switch (realTypeAnnotation.memberType) { - case 'NumberTypeAnnotation': - return wrap(val => `${val}.asNumber()`); - case 'StringTypeAnnotation': - return wrap(val => `${val}.asString(rt)`); - default: - throw new Error( - `Unknown enum type for "${arg.name}, found: ${realTypeAnnotation.type}"`, - ); - } - case 'NumberTypeAnnotation': - return wrap(val => `${val}.asNumber()`); - case 'FloatTypeAnnotation': - return wrap(val => `${val}.asNumber()`); - case 'DoubleTypeAnnotation': - return wrap(val => `${val}.asNumber()`); - case 'Int32TypeAnnotation': - return wrap(val => `${val}.asNumber()`); - case 'ArrayTypeAnnotation': - return wrap(val => `${val}.asObject(rt).asArray(rt)`); - case 'FunctionTypeAnnotation': - return wrap(val => `${val}.asObject(rt).asFunction(rt)`); - case 'GenericObjectTypeAnnotation': - return wrap(val => `${val}.asObject(rt)`); - case 'UnionTypeAnnotation': - switch (typeAnnotation.memberType) { - case 'NumberTypeAnnotation': - return wrap(val => `${val}.asNumber()`); - case 'ObjectTypeAnnotation': - return wrap(val => `${val}.asObject(rt)`); - case 'StringTypeAnnotation': - return wrap(val => `${val}.asString(rt)`); - default: - throw new Error( - `Unsupported union member type for param "${arg.name}, found: ${realTypeAnnotation.memberType}"`, - ); - } - case 'ObjectTypeAnnotation': - return wrap(val => `${val}.asObject(rt)`); - case 'MixedTypeAnnotation': - return wrap(val => `jsi::Value(rt, ${val})`); - default: - (realTypeAnnotation.type: empty); - throw new Error( - `Unknown prop type for "${arg.name}, found: ${realTypeAnnotation.type}"`, - ); - } -} - -function serializePropertyIntoHostFunction( - hasteModuleName: string, - property: NativeModulePropertyShape, - resolveAlias: AliasResolver, -): string { - const [propertyTypeAnnotation] = - unwrapNullable(property.typeAnnotation); - - return HostFunctionTemplate({ - hasteModuleName, - methodName: property.name, - returnTypeAnnotation: propertyTypeAnnotation.returnTypeAnnotation, - args: propertyTypeAnnotation.params.map((p, i) => - serializeArg(p, i, resolveAlias), - ), - }); -} - -module.exports = { - generate( - libraryName: string, - schema: SchemaType, - packageName?: string, - assumeNonnull: boolean = false, - ): FilesOutput { - const nativeModules = getModules(schema); - - const modules = Object.keys(nativeModules) - .map((hasteModuleName: string) => { - const nativeModule = nativeModules[hasteModuleName]; - const { - aliases, - spec: {properties}, - moduleNames, - } = nativeModule; - const resolveAlias = createAliasResolver(aliases); - const hostFunctions = properties.map(property => - serializePropertyIntoHostFunction( - hasteModuleName, - property, - resolveAlias, - ), - ); - - return ModuleTemplate({ - hasteModuleName, - hostFunctions, - // TODO: What happens when there are more than one NativeModule requires? - moduleName: moduleNames[0], - methods: properties.map( - ({name: propertyName, typeAnnotation: nullableTypeAnnotation}) => { - const [{params}] = unwrapNullable(nullableTypeAnnotation); - return { - methodName: propertyName, - paramCount: params.length, - }; - }, - ), - }); - }) - .join('\n'); - - const fileName = `${libraryName}JSI-generated.cpp`; - const replacedTemplate = FileTemplate({ - modules, - libraryName, - }); - return new Map([[fileName, replacedTemplate]]); - }, -}; diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleH.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleH.js deleted file mode 100644 index 7076ab941311..000000000000 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleH.js +++ /dev/null @@ -1,355 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type { - Nullable, - SchemaType, - NativeModuleTypeAnnotation, - NativeModuleFunctionTypeAnnotation, - NativeModulePropertyShape, - NativeModuleAliasMap, -} from '../../CodegenSchema'; - -import type {AliasResolver} from './Utils'; -const {createAliasResolver, getModules} = require('./Utils'); -const {indent} = require('../Utils'); -const {unwrapNullable} = require('../../parsers/parsers-commons'); - -type FilesOutput = Map; - -const ModuleClassDeclarationTemplate = ({ - hasteModuleName, - moduleProperties, - structs, -}: $ReadOnly<{ - hasteModuleName: string, - moduleProperties: string[], - structs: string, -}>) => { - return `${structs}class JSI_EXPORT ${hasteModuleName}CxxSpecJSI : public TurboModule { -protected: - ${hasteModuleName}CxxSpecJSI(std::shared_ptr jsInvoker); - -public: - ${indent(moduleProperties.join('\n'), 2)} - -};`; -}; - -const ModuleSpecClassDeclarationTemplate = ({ - hasteModuleName, - moduleName, - moduleProperties, -}: $ReadOnly<{ - hasteModuleName: string, - moduleName: string, - moduleProperties: string[], -}>) => { - return `template -class JSI_EXPORT ${hasteModuleName}CxxSpec : public TurboModule { -public: - jsi::Value get(jsi::Runtime &rt, const jsi::PropNameID &propName) override { - return delegate_.get(rt, propName); - } - -protected: - ${hasteModuleName}CxxSpec(std::shared_ptr jsInvoker) - : TurboModule("${moduleName}", jsInvoker), - delegate_(static_cast(this), jsInvoker) {} - -private: - class Delegate : public ${hasteModuleName}CxxSpecJSI { - public: - Delegate(T *instance, std::shared_ptr jsInvoker) : - ${hasteModuleName}CxxSpecJSI(std::move(jsInvoker)), instance_(instance) {} - - ${indent(moduleProperties.join('\n'), 4)} - - private: - T *instance_; - }; - - Delegate delegate_; -};`; -}; - -const FileTemplate = ({ - modules, -}: $ReadOnly<{ - modules: string[], -}>) => { - return `/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * ${'@'}generated by codegen project: GenerateModuleH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -${modules.join('\n\n')} - -} // namespace react -} // namespace facebook -`; -}; - -function translatePrimitiveJSTypeToCpp( - nullableTypeAnnotation: Nullable, - optional: boolean, - createErrorMessage: (typeName: string) => string, - resolveAlias: AliasResolver, -) { - const [typeAnnotation, nullable] = unwrapNullable( - nullableTypeAnnotation, - ); - const isRequired = !optional && !nullable; - - let realTypeAnnotation = typeAnnotation; - if (realTypeAnnotation.type === 'TypeAliasTypeAnnotation') { - realTypeAnnotation = resolveAlias(realTypeAnnotation.name); - } - - function wrap(type: string) { - return isRequired ? type : `std::optional<${type}>`; - } - - switch (realTypeAnnotation.type) { - case 'ReservedTypeAnnotation': - switch (realTypeAnnotation.name) { - case 'RootTag': - return wrap('double'); - default: - (realTypeAnnotation.name: empty); - throw new Error(createErrorMessage(realTypeAnnotation.name)); - } - case 'VoidTypeAnnotation': - return 'void'; - case 'StringTypeAnnotation': - return wrap('jsi::String'); - case 'NumberTypeAnnotation': - return wrap('double'); - case 'DoubleTypeAnnotation': - return wrap('double'); - case 'FloatTypeAnnotation': - return wrap('double'); - case 'Int32TypeAnnotation': - return wrap('int'); - case 'BooleanTypeAnnotation': - return wrap('bool'); - case 'EnumDeclaration': - switch (realTypeAnnotation.memberType) { - case 'NumberTypeAnnotation': - return wrap('double'); - case 'StringTypeAnnotation': - return wrap('jsi::String'); - default: - throw new Error(createErrorMessage(realTypeAnnotation.type)); - } - case 'GenericObjectTypeAnnotation': - return wrap('jsi::Object'); - case 'UnionTypeAnnotation': - switch (typeAnnotation.memberType) { - case 'NumberTypeAnnotation': - return wrap('double'); - case 'ObjectTypeAnnotation': - return wrap('jsi::Object'); - case 'StringTypeAnnotation': - return wrap('jsi::String'); - default: - throw new Error(createErrorMessage(realTypeAnnotation.type)); - } - case 'ObjectTypeAnnotation': - return wrap('jsi::Object'); - case 'ArrayTypeAnnotation': - return wrap('jsi::Array'); - case 'FunctionTypeAnnotation': - return wrap('jsi::Function'); - case 'PromiseTypeAnnotation': - return wrap('jsi::Value'); - case 'MixedTypeAnnotation': - return wrap('jsi::Value'); - default: - (realTypeAnnotation.type: empty); - throw new Error(createErrorMessage(realTypeAnnotation.type)); - } -} - -function createStructs( - moduleName: string, - aliasMap: NativeModuleAliasMap, - resolveAlias: AliasResolver, -): string { - return Object.keys(aliasMap) - .map(alias => { - const value = aliasMap[alias]; - if (value.properties.length === 0) { - return ''; - } - const structName = `${moduleName}Base${alias}`; - const templateParameterWithTypename = value.properties - .map((v, i) => 'typename P' + i) - .join(', '); - const templateParameter = value.properties - .map((v, i) => 'P' + i) - .join(', '); - return `#pragma mark - ${structName} - -template <${templateParameterWithTypename}> -struct ${structName} { -${value.properties.map((v, i) => ' P' + i + ' ' + v.name).join(';\n')}; - bool operator==(const ${structName} &other) const { - return ${value.properties - .map(v => `${v.name} == other.${v.name}`) - .join(' && ')}; - } -}; - -template <${templateParameterWithTypename}> -struct ${structName}Bridging { - static ${structName}<${templateParameter}> fromJs( - jsi::Runtime &rt, - const jsi::Object &value, - const std::shared_ptr &jsInvoker) { - ${structName}<${templateParameter}> result{ -${value.properties - .map( - (v, i) => - ` bridging::fromJs(rt, value.getProperty(rt, "${v.name}"), jsInvoker)`, - ) - .join(',\n')}}; - return result; - } - - static jsi::Object toJs( - jsi::Runtime &rt, - const ${structName}<${templateParameter}> &value) { - auto result = facebook::jsi::Object(rt); -${value.properties - .map((v, i) => { - if (v.optional) { - return ` if (value.${v.name}) { - result.setProperty(rt, "${v.name}", bridging::toJs(rt, value.${v.name}.value())); - }`; - } else { - return ` result.setProperty(rt, "${v.name}", bridging::toJs(rt, value.${v.name}));`; - } - }) - .join('\n')} - return result; - } -}; - -`; - }) - .join('\n'); -} - -function translatePropertyToCpp( - prop: NativeModulePropertyShape, - resolveAlias: AliasResolver, - abstract: boolean = false, -) { - const [propTypeAnnotation] = - unwrapNullable(prop.typeAnnotation); - - const params = propTypeAnnotation.params.map( - param => `std::move(${param.name})`, - ); - - const paramTypes = propTypeAnnotation.params.map(param => { - const translatedParam = translatePrimitiveJSTypeToCpp( - param.typeAnnotation, - param.optional, - typeName => - `Unsupported type for param "${param.name}" in ${prop.name}. Found: ${typeName}`, - resolveAlias, - ); - return `${translatedParam} ${param.name}`; - }); - - const returnType = translatePrimitiveJSTypeToCpp( - propTypeAnnotation.returnTypeAnnotation, - false, - typeName => `Unsupported return type for ${prop.name}. Found: ${typeName}`, - resolveAlias, - ); - - // The first param will always be the runtime reference. - paramTypes.unshift('jsi::Runtime &rt'); - - const method = `${returnType} ${prop.name}(${paramTypes.join(', ')})`; - - if (abstract) { - return `virtual ${method} = 0;`; - } - - return `${method} override { - static_assert( - bridging::getParameterCount(&T::${prop.name}) == ${paramTypes.length}, - "Expected ${prop.name}(...) to have ${paramTypes.length} parameters"); - - return bridging::callFromJs<${returnType}>( - rt, &T::${prop.name}, jsInvoker_, ${['instance_', ...params].join(', ')}); -}`; -} - -module.exports = { - generate( - libraryName: string, - schema: SchemaType, - packageName?: string, - assumeNonnull: boolean = false, - ): FilesOutput { - const nativeModules = getModules(schema); - - const modules = Object.keys(nativeModules).flatMap(hasteModuleName => { - const { - aliases, - spec: {properties}, - moduleNames: [moduleName], - } = nativeModules[hasteModuleName]; - const resolveAlias = createAliasResolver(aliases); - const structs = createStructs(moduleName, aliases, resolveAlias); - - return [ - ModuleClassDeclarationTemplate({ - hasteModuleName, - moduleProperties: properties.map(prop => - translatePropertyToCpp(prop, resolveAlias, true), - ), - structs, - }), - ModuleSpecClassDeclarationTemplate({ - hasteModuleName, - moduleName, - moduleProperties: properties.map(prop => - translatePropertyToCpp(prop, resolveAlias), - ), - }), - ]; - }); - - const fileName = `${libraryName}JSI.h`; - const replacedTemplate = FileTemplate({modules}); - - return new Map([[fileName, replacedTemplate]]); - }, -}; diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleJavaSpec.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleJavaSpec.js deleted file mode 100644 index 0b807bbbfa96..000000000000 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleJavaSpec.js +++ /dev/null @@ -1,512 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type { - Nullable, - NamedShape, - SchemaType, - NativeModulePropertyShape, - NativeModuleReturnTypeAnnotation, - NativeModuleFunctionTypeAnnotation, - NativeModuleParamTypeAnnotation, -} from '../../CodegenSchema'; - -import type {AliasResolver} from './Utils'; -const {createAliasResolver, getModules} = require('./Utils'); -const {unwrapNullable} = require('../../parsers/parsers-commons'); - -type FilesOutput = Map; - -function FileTemplate( - config: $ReadOnly<{ - packageName: string, - className: string, - methods: string, - imports: string, - }>, -): string { - const {packageName, className, methods, imports} = config; - return ` -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * ${'@'}generated by codegen project: GenerateModuleJavaSpec.js - * - * ${'@'}nolint - */ - -package ${packageName}; - -${imports} - -public abstract class ${className} extends ReactContextBaseJavaModule implements ReactModuleWithSpec, TurboModule { - public ${className}(ReactApplicationContext reactContext) { - super(reactContext); - } - -${methods} -} -`; -} - -function MethodTemplate( - config: $ReadOnly<{ - abstract: boolean, - methodBody: ?string, - methodJavaAnnotation: string, - methodName: string, - translatedReturnType: string, - traversedArgs: Array, - }>, -): string { - const { - abstract, - methodBody, - methodJavaAnnotation, - methodName, - translatedReturnType, - traversedArgs, - } = config; - const methodQualifier = abstract ? 'abstract ' : ''; - const methodClosing = abstract - ? ';' - : methodBody != null && methodBody.length > 0 - ? ` { ${methodBody} }` - : ' {}'; - return ` ${methodJavaAnnotation} - public ${methodQualifier}${translatedReturnType} ${methodName}(${traversedArgs.join( - ', ', - )})${methodClosing}`; -} - -type Param = NamedShape>; - -function translateFunctionParamToJavaType( - param: Param, - createErrorMessage: (typeName: string) => string, - resolveAlias: AliasResolver, - imports: Set, -): string { - const {optional, typeAnnotation: nullableTypeAnnotation} = param; - const [typeAnnotation, nullable] = - unwrapNullable(nullableTypeAnnotation); - const isRequired = !optional && !nullable; - - function wrapIntoNullableIfNeeded(generatedType: string) { - if (!isRequired) { - imports.add('javax.annotation.Nullable'); - return `@Nullable ${generatedType}`; - } - return generatedType; - } - - let realTypeAnnotation = typeAnnotation; - if (realTypeAnnotation.type === 'TypeAliasTypeAnnotation') { - realTypeAnnotation = resolveAlias(realTypeAnnotation.name); - } - - switch (realTypeAnnotation.type) { - case 'ReservedTypeAnnotation': - switch (realTypeAnnotation.name) { - case 'RootTag': - return !isRequired ? 'Double' : 'double'; - default: - (realTypeAnnotation.name: empty); - throw new Error(createErrorMessage(realTypeAnnotation.name)); - } - case 'StringTypeAnnotation': - return wrapIntoNullableIfNeeded('String'); - case 'NumberTypeAnnotation': - return !isRequired ? 'Double' : 'double'; - case 'FloatTypeAnnotation': - return !isRequired ? 'Double' : 'double'; - case 'DoubleTypeAnnotation': - return !isRequired ? 'Double' : 'double'; - case 'Int32TypeAnnotation': - return !isRequired ? 'Double' : 'double'; - case 'BooleanTypeAnnotation': - return !isRequired ? 'Boolean' : 'boolean'; - case 'EnumDeclaration': - switch (realTypeAnnotation.memberType) { - case 'NumberTypeAnnotation': - return !isRequired ? 'Double' : 'double'; - case 'StringTypeAnnotation': - return wrapIntoNullableIfNeeded('String'); - default: - throw new Error(createErrorMessage(realTypeAnnotation.type)); - } - case 'ObjectTypeAnnotation': - imports.add('com.facebook.react.bridge.ReadableMap'); - if (typeAnnotation.type === 'TypeAliasTypeAnnotation') { - // No class alias for args, so it still falls under ReadableMap. - return 'ReadableMap'; - } - return 'ReadableMap'; - case 'GenericObjectTypeAnnotation': - // Treat this the same as ObjectTypeAnnotation for now. - imports.add('com.facebook.react.bridge.ReadableMap'); - return 'ReadableMap'; - case 'ArrayTypeAnnotation': - imports.add('com.facebook.react.bridge.ReadableArray'); - return 'ReadableArray'; - case 'FunctionTypeAnnotation': - imports.add('com.facebook.react.bridge.Callback'); - return 'Callback'; - default: - (realTypeAnnotation.type: - | 'EnumDeclaration' - | 'MixedTypeAnnotation' - | 'UnionTypeAnnotation'); - throw new Error(createErrorMessage(realTypeAnnotation.type)); - } -} - -function translateFunctionReturnTypeToJavaType( - nullableReturnTypeAnnotation: Nullable, - createErrorMessage: (typeName: string) => string, - resolveAlias: AliasResolver, - imports: Set, -): string { - const [returnTypeAnnotation, nullable] = - unwrapNullable( - nullableReturnTypeAnnotation, - ); - - function wrapIntoNullableIfNeeded(generatedType: string) { - if (nullable) { - imports.add('javax.annotation.Nullable'); - return `@Nullable ${generatedType}`; - } - return generatedType; - } - - let realTypeAnnotation = returnTypeAnnotation; - if (realTypeAnnotation.type === 'TypeAliasTypeAnnotation') { - realTypeAnnotation = resolveAlias(realTypeAnnotation.name); - } - - switch (realTypeAnnotation.type) { - case 'ReservedTypeAnnotation': - switch (realTypeAnnotation.name) { - case 'RootTag': - return nullable ? 'Double' : 'double'; - default: - (realTypeAnnotation.name: empty); - throw new Error(createErrorMessage(realTypeAnnotation.name)); - } - case 'VoidTypeAnnotation': - return 'void'; - case 'PromiseTypeAnnotation': - return 'void'; - case 'StringTypeAnnotation': - return wrapIntoNullableIfNeeded('String'); - case 'NumberTypeAnnotation': - return nullable ? 'Double' : 'double'; - case 'FloatTypeAnnotation': - return nullable ? 'Double' : 'double'; - case 'DoubleTypeAnnotation': - return nullable ? 'Double' : 'double'; - case 'Int32TypeAnnotation': - return nullable ? 'Double' : 'double'; - case 'BooleanTypeAnnotation': - return nullable ? 'Boolean' : 'boolean'; - case 'EnumDeclaration': - switch (realTypeAnnotation.memberType) { - case 'NumberTypeAnnotation': - return nullable ? 'Double' : 'double'; - case 'StringTypeAnnotation': - return wrapIntoNullableIfNeeded('String'); - default: - throw new Error(createErrorMessage(realTypeAnnotation.type)); - } - case 'ObjectTypeAnnotation': - imports.add('com.facebook.react.bridge.WritableMap'); - return wrapIntoNullableIfNeeded('WritableMap'); - case 'GenericObjectTypeAnnotation': - imports.add('com.facebook.react.bridge.WritableMap'); - return wrapIntoNullableIfNeeded('WritableMap'); - case 'ArrayTypeAnnotation': - imports.add('com.facebook.react.bridge.WritableArray'); - return wrapIntoNullableIfNeeded('WritableArray'); - default: - (realTypeAnnotation.type: - | 'EnumDeclaration' - | 'MixedTypeAnnotation' - | 'UnionTypeAnnotation'); - throw new Error(createErrorMessage(realTypeAnnotation.type)); - } -} - -function getFalsyReturnStatementFromReturnType( - nullableReturnTypeAnnotation: Nullable, - createErrorMessage: (typeName: string) => string, - resolveAlias: AliasResolver, -): string { - const [returnTypeAnnotation, nullable] = - unwrapNullable( - nullableReturnTypeAnnotation, - ); - - let realTypeAnnotation = returnTypeAnnotation; - if (realTypeAnnotation.type === 'TypeAliasTypeAnnotation') { - realTypeAnnotation = resolveAlias(realTypeAnnotation.name); - } - - switch (realTypeAnnotation.type) { - case 'ReservedTypeAnnotation': - switch (realTypeAnnotation.name) { - case 'RootTag': - return 'return 0.0;'; - default: - (realTypeAnnotation.name: empty); - throw new Error(createErrorMessage(realTypeAnnotation.name)); - } - case 'VoidTypeAnnotation': - return ''; - case 'PromiseTypeAnnotation': - return ''; - case 'NumberTypeAnnotation': - return nullable ? 'return null;' : 'return 0;'; - case 'FloatTypeAnnotation': - return nullable ? 'return null;' : 'return 0.0;'; - case 'DoubleTypeAnnotation': - return nullable ? 'return null;' : 'return 0.0;'; - case 'Int32TypeAnnotation': - return nullable ? 'return null;' : 'return 0;'; - case 'BooleanTypeAnnotation': - return nullable ? 'return null;' : 'return false;'; - case 'EnumDeclaration': - switch (realTypeAnnotation.memberType) { - case 'NumberTypeAnnotation': - return nullable ? 'return null;' : 'return 0;'; - case 'StringTypeAnnotation': - return nullable ? 'return null;' : 'return "";'; - default: - throw new Error(createErrorMessage(realTypeAnnotation.type)); - } - case 'StringTypeAnnotation': - return nullable ? 'return null;' : 'return "";'; - case 'ObjectTypeAnnotation': - return 'return null;'; - case 'GenericObjectTypeAnnotation': - return 'return null;'; - case 'ArrayTypeAnnotation': - return 'return null;'; - default: - (realTypeAnnotation.type: - | 'EnumDeclaration' - | 'MixedTypeAnnotation' - | 'UnionTypeAnnotation'); - throw new Error(createErrorMessage(realTypeAnnotation.type)); - } -} - -// Build special-cased runtime check for getConstants(). -function buildGetConstantsMethod( - method: NativeModulePropertyShape, - imports: Set, -): string { - const [methodTypeAnnotation] = - unwrapNullable(method.typeAnnotation); - if ( - methodTypeAnnotation.returnTypeAnnotation.type === 'ObjectTypeAnnotation' - ) { - const requiredProps = []; - const optionalProps = []; - const rawProperties = - methodTypeAnnotation.returnTypeAnnotation.properties || []; - rawProperties.forEach(p => { - if (p.optional || p.typeAnnotation.type === 'NullableTypeAnnotation') { - optionalProps.push(p.name); - } else { - requiredProps.push(p.name); - } - }); - if (requiredProps.length === 0 && optionalProps.length === 0) { - // Nothing to validate during runtime. - return ''; - } - - imports.add('com.facebook.react.common.build.ReactBuildConfig'); - imports.add('java.util.Arrays'); - imports.add('java.util.HashSet'); - imports.add('java.util.Map'); - imports.add('java.util.Set'); - imports.add('javax.annotation.Nullable'); - - const requiredPropsFragment = - requiredProps.length > 0 - ? `Arrays.asList( - ${requiredProps - .sort() - .map(p => `"${p}"`) - .join(',\n ')} - )` - : ''; - const optionalPropsFragment = - optionalProps.length > 0 - ? `Arrays.asList( - ${optionalProps - .sort() - .map(p => `"${p}"`) - .join(',\n ')} - )` - : ''; - - return ` protected abstract Map getTypedExportedConstants(); - - @Override - @DoNotStrip - public final @Nullable Map getConstants() { - Map constants = getTypedExportedConstants(); - if (ReactBuildConfig.DEBUG || ReactBuildConfig.IS_INTERNAL_BUILD) { - Set obligatoryFlowConstants = new HashSet<>(${requiredPropsFragment}); - Set optionalFlowConstants = new HashSet<>(${optionalPropsFragment}); - Set undeclaredConstants = new HashSet<>(constants.keySet()); - undeclaredConstants.removeAll(obligatoryFlowConstants); - undeclaredConstants.removeAll(optionalFlowConstants); - if (!undeclaredConstants.isEmpty()) { - throw new IllegalStateException(String.format("Native Module Flow doesn't declare constants: %s", undeclaredConstants)); - } - undeclaredConstants = obligatoryFlowConstants; - undeclaredConstants.removeAll(constants.keySet()); - if (!undeclaredConstants.isEmpty()) { - throw new IllegalStateException(String.format("Native Module doesn't fill in constants: %s", undeclaredConstants)); - } - } - return constants; - }`; - } - - return ''; -} - -module.exports = { - generate( - libraryName: string, - schema: SchemaType, - packageName?: string, - assumeNonnull: boolean = false, - ): FilesOutput { - const files = new Map(); - const nativeModules = getModules(schema); - - const normalizedPackageName = - packageName == null ? 'com.facebook.fbreact.specs' : packageName; - const outputDir = `java/${normalizedPackageName.replace(/\./g, '/')}`; - - Object.keys(nativeModules).forEach(hasteModuleName => { - const { - aliases, - excludedPlatforms, - spec: {properties}, - } = nativeModules[hasteModuleName]; - if (excludedPlatforms != null && excludedPlatforms.includes('android')) { - return; - } - const resolveAlias = createAliasResolver(aliases); - const className = `${hasteModuleName}Spec`; - - const imports: Set = new Set([ - // Always required. - 'com.facebook.react.bridge.ReactApplicationContext', - 'com.facebook.react.bridge.ReactContextBaseJavaModule', - 'com.facebook.react.bridge.ReactMethod', - 'com.facebook.react.bridge.ReactModuleWithSpec', - 'com.facebook.react.turbomodule.core.interfaces.TurboModule', - 'com.facebook.proguard.annotations.DoNotStrip', - ]); - - const methods = properties.map(method => { - if (method.name === 'getConstants') { - return buildGetConstantsMethod(method, imports); - } - - const [methodTypeAnnotation] = - unwrapNullable( - method.typeAnnotation, - ); - - // Handle return type - const translatedReturnType = translateFunctionReturnTypeToJavaType( - methodTypeAnnotation.returnTypeAnnotation, - typeName => - `Unsupported return type for method ${method.name}. Found: ${typeName}`, - resolveAlias, - imports, - ); - const returningPromise = - methodTypeAnnotation.returnTypeAnnotation.type === - 'PromiseTypeAnnotation'; - const isSyncMethod = - methodTypeAnnotation.returnTypeAnnotation.type !== - 'VoidTypeAnnotation' && !returningPromise; - - // Handle method args - const traversedArgs = methodTypeAnnotation.params.map(param => { - const translatedParam = translateFunctionParamToJavaType( - param, - typeName => - `Unsupported type for param "${param.name}" in ${method.name}. Found: ${typeName}`, - resolveAlias, - imports, - ); - return `${translatedParam} ${param.name}`; - }); - - if (returningPromise) { - // Promise return type requires an extra arg at the end. - imports.add('com.facebook.react.bridge.Promise'); - traversedArgs.push('Promise promise'); - } - - const methodJavaAnnotation = `@ReactMethod${ - isSyncMethod ? '(isBlockingSynchronousMethod = true)' : '' - }\n @DoNotStrip`; - const methodBody = method.optional - ? getFalsyReturnStatementFromReturnType( - methodTypeAnnotation.returnTypeAnnotation, - typeName => - `Cannot build falsy return statement for return type for method ${method.name}. Found: ${typeName}`, - resolveAlias, - ) - : null; - return MethodTemplate({ - abstract: !method.optional, - methodBody, - methodJavaAnnotation, - methodName: method.name, - translatedReturnType, - traversedArgs, - }); - }); - - files.set( - `${outputDir}/${className}.java`, - FileTemplate({ - packageName: normalizedPackageName, - className, - methods: methods.filter(Boolean).join('\n\n'), - imports: Array.from(imports) - .sort() - .map(p => `import ${p};`) - .join('\n'), - }), - ); - }); - - return files; - }, -}; diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleJniCpp.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleJniCpp.js deleted file mode 100644 index 891f4fa61037..000000000000 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleJniCpp.js +++ /dev/null @@ -1,500 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type { - Nullable, - NamedShape, - SchemaType, - NativeModulePropertyShape, - NativeModuleReturnTypeAnnotation, - NativeModuleParamTypeAnnotation, - NativeModuleFunctionTypeAnnotation, -} from '../../CodegenSchema'; - -import type {AliasResolver} from './Utils'; -const {createAliasResolver, getModules} = require('./Utils'); -const {unwrapNullable} = require('../../parsers/parsers-commons'); - -type FilesOutput = Map; - -type JSReturnType = - | 'VoidKind' - | 'StringKind' - | 'BooleanKind' - | 'NumberKind' - | 'PromiseKind' - | 'ObjectKind' - | 'ArrayKind'; - -const HostFunctionTemplate = ({ - hasteModuleName, - propertyName, - jniSignature, - jsReturnType, -}: $ReadOnly<{ - hasteModuleName: string, - propertyName: string, - jniSignature: string, - jsReturnType: JSReturnType, -}>) => { - return `static facebook::jsi::Value __hostFunction_${hasteModuleName}SpecJSI_${propertyName}(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, ${jsReturnType}, "${propertyName}", "${jniSignature}", args, count, cachedMethodId); -}`; -}; - -const ModuleClassConstructorTemplate = ({ - hasteModuleName, - methods, -}: $ReadOnly<{ - hasteModuleName: string, - methods: $ReadOnlyArray<{ - propertyName: string, - argCount: number, - }>, -}>) => { - return ` -${hasteModuleName}SpecJSI::${hasteModuleName}SpecJSI(const JavaTurboModule::InitParams ¶ms) - : JavaTurboModule(params) { -${methods - .map(({propertyName, argCount}) => { - return ` methodMap_["${propertyName}"] = MethodMetadata {${argCount}, __hostFunction_${hasteModuleName}SpecJSI_${propertyName}};`; - }) - .join('\n')} -}`.trim(); -}; - -const ModuleLookupTemplate = ({ - moduleName, - hasteModuleName, -}: $ReadOnly<{moduleName: string, hasteModuleName: string}>) => { - return ` if (moduleName == "${moduleName}") { - return std::make_shared<${hasteModuleName}SpecJSI>(params); - }`; -}; - -const FileTemplate = ({ - libraryName, - include, - modules, - moduleLookups, -}: $ReadOnly<{ - libraryName: string, - include: string, - modules: string, - moduleLookups: $ReadOnlyArray< - $ReadOnly<{ - hasteModuleName: string, - moduleName: string, - }>, - >, -}>) => { - return ` -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * ${'@'}generated by codegen project: GenerateModuleJniCpp.js - */ - -#include ${include} - -namespace facebook { -namespace react { - -${modules} - -std::shared_ptr ${libraryName}_ModuleProvider(const std::string &moduleName, const JavaTurboModule::InitParams ¶ms) { -${moduleLookups.map(ModuleLookupTemplate).join('\n')} - return nullptr; -} - -} // namespace react -} // namespace facebook -`; -}; - -function translateReturnTypeToKind( - nullableTypeAnnotation: Nullable, - resolveAlias: AliasResolver, -): JSReturnType { - const [typeAnnotation] = unwrapNullable( - nullableTypeAnnotation, - ); - let realTypeAnnotation = typeAnnotation; - if (realTypeAnnotation.type === 'TypeAliasTypeAnnotation') { - realTypeAnnotation = resolveAlias(realTypeAnnotation.name); - } - - switch (realTypeAnnotation.type) { - case 'ReservedTypeAnnotation': - switch (realTypeAnnotation.name) { - case 'RootTag': - return 'NumberKind'; - default: - (realTypeAnnotation.name: empty); - throw new Error( - `Invalid ReservedFunctionValueTypeName name, got ${realTypeAnnotation.name}`, - ); - } - case 'VoidTypeAnnotation': - return 'VoidKind'; - case 'StringTypeAnnotation': - return 'StringKind'; - case 'BooleanTypeAnnotation': - return 'BooleanKind'; - case 'EnumDeclaration': - switch (typeAnnotation.memberType) { - case 'NumberTypeAnnotation': - return 'NumberKind'; - case 'StringTypeAnnotation': - return 'StringKind'; - default: - throw new Error( - `Unknown enum prop type for returning value, found: ${realTypeAnnotation.type}"`, - ); - } - case 'NumberTypeAnnotation': - return 'NumberKind'; - case 'DoubleTypeAnnotation': - return 'NumberKind'; - case 'FloatTypeAnnotation': - return 'NumberKind'; - case 'Int32TypeAnnotation': - return 'NumberKind'; - case 'PromiseTypeAnnotation': - return 'PromiseKind'; - case 'GenericObjectTypeAnnotation': - return 'ObjectKind'; - case 'ObjectTypeAnnotation': - return 'ObjectKind'; - case 'ArrayTypeAnnotation': - return 'ArrayKind'; - default: - (realTypeAnnotation.type: - | 'EnumDeclaration' - | 'MixedTypeAnnotation' - | 'UnionTypeAnnotation'); - throw new Error( - `Unknown prop type for returning value, found: ${realTypeAnnotation.type}"`, - ); - } -} - -type Param = NamedShape>; - -function translateParamTypeToJniType( - param: Param, - resolveAlias: AliasResolver, -): string { - const {optional, typeAnnotation: nullableTypeAnnotation} = param; - const [typeAnnotation, nullable] = - unwrapNullable(nullableTypeAnnotation); - const isRequired = !optional && !nullable; - - let realTypeAnnotation = typeAnnotation; - if (realTypeAnnotation.type === 'TypeAliasTypeAnnotation') { - realTypeAnnotation = resolveAlias(realTypeAnnotation.name); - } - - switch (realTypeAnnotation.type) { - case 'ReservedTypeAnnotation': - switch (realTypeAnnotation.name) { - case 'RootTag': - return !isRequired ? 'Ljava/lang/Double;' : 'D'; - default: - (realTypeAnnotation.name: empty); - throw new Error( - `Invalid ReservedFunctionValueTypeName name, got ${realTypeAnnotation.name}`, - ); - } - case 'StringTypeAnnotation': - return 'Ljava/lang/String;'; - case 'BooleanTypeAnnotation': - return !isRequired ? 'Ljava/lang/Boolean;' : 'Z'; - case 'EnumDeclaration': - switch (typeAnnotation.memberType) { - case 'NumberTypeAnnotation': - return !isRequired ? 'Ljava/lang/Double;' : 'D'; - case 'StringTypeAnnotation': - return 'Ljava/lang/String;'; - default: - throw new Error( - `Unknown enum prop type for method arg, found: ${realTypeAnnotation.type}"`, - ); - } - case 'NumberTypeAnnotation': - return !isRequired ? 'Ljava/lang/Double;' : 'D'; - case 'DoubleTypeAnnotation': - return !isRequired ? 'Ljava/lang/Double;' : 'D'; - case 'FloatTypeAnnotation': - return !isRequired ? 'Ljava/lang/Double;' : 'D'; - case 'Int32TypeAnnotation': - return !isRequired ? 'Ljava/lang/Double;' : 'D'; - case 'GenericObjectTypeAnnotation': - return 'Lcom/facebook/react/bridge/ReadableMap;'; - case 'ObjectTypeAnnotation': - return 'Lcom/facebook/react/bridge/ReadableMap;'; - case 'ArrayTypeAnnotation': - return 'Lcom/facebook/react/bridge/ReadableArray;'; - case 'FunctionTypeAnnotation': - return 'Lcom/facebook/react/bridge/Callback;'; - default: - (realTypeAnnotation.type: - | 'EnumDeclaration' - | 'MixedTypeAnnotation' - | 'UnionTypeAnnotation'); - throw new Error( - `Unknown prop type for method arg, found: ${realTypeAnnotation.type}"`, - ); - } -} - -function translateReturnTypeToJniType( - nullableTypeAnnotation: Nullable, - resolveAlias: AliasResolver, -): string { - const [typeAnnotation, nullable] = unwrapNullable(nullableTypeAnnotation); - - let realTypeAnnotation = typeAnnotation; - if (realTypeAnnotation.type === 'TypeAliasTypeAnnotation') { - realTypeAnnotation = resolveAlias(realTypeAnnotation.name); - } - - switch (realTypeAnnotation.type) { - case 'ReservedTypeAnnotation': - switch (realTypeAnnotation.name) { - case 'RootTag': - return nullable ? 'Ljava/lang/Double;' : 'D'; - default: - (realTypeAnnotation.name: empty); - throw new Error( - `Invalid ReservedFunctionValueTypeName name, got ${realTypeAnnotation.name}`, - ); - } - case 'VoidTypeAnnotation': - return 'V'; - case 'StringTypeAnnotation': - return 'Ljava/lang/String;'; - case 'BooleanTypeAnnotation': - return nullable ? 'Ljava/lang/Boolean;' : 'Z'; - case 'EnumDeclaration': - switch (typeAnnotation.memberType) { - case 'NumberTypeAnnotation': - return nullable ? 'Ljava/lang/Double;' : 'D'; - case 'StringTypeAnnotation': - return 'Ljava/lang/String;'; - default: - throw new Error( - `Unknown enum prop type for method return type, found: ${realTypeAnnotation.type}"`, - ); - } - case 'NumberTypeAnnotation': - return nullable ? 'Ljava/lang/Double;' : 'D'; - case 'DoubleTypeAnnotation': - return nullable ? 'Ljava/lang/Double;' : 'D'; - case 'FloatTypeAnnotation': - return nullable ? 'Ljava/lang/Double;' : 'D'; - case 'Int32TypeAnnotation': - return nullable ? 'Ljava/lang/Double;' : 'D'; - case 'PromiseTypeAnnotation': - return 'Lcom/facebook/react/bridge/Promise;'; - case 'GenericObjectTypeAnnotation': - return 'Lcom/facebook/react/bridge/WritableMap;'; - case 'ObjectTypeAnnotation': - return 'Lcom/facebook/react/bridge/WritableMap;'; - case 'ArrayTypeAnnotation': - return 'Lcom/facebook/react/bridge/WritableArray;'; - default: - (realTypeAnnotation.type: - | 'EnumDeclaration' - | 'MixedTypeAnnotation' - | 'UnionTypeAnnotation'); - throw new Error( - `Unknown prop type for method return type, found: ${realTypeAnnotation.type}"`, - ); - } -} - -function translateMethodTypeToJniSignature( - property: NativeModulePropertyShape, - resolveAlias: AliasResolver, -): string { - const {name, typeAnnotation} = property; - let [{returnTypeAnnotation, params}] = - unwrapNullable(typeAnnotation); - - params = [...params]; - let processedReturnTypeAnnotation = returnTypeAnnotation; - const isPromiseReturn = returnTypeAnnotation.type === 'PromiseTypeAnnotation'; - if (isPromiseReturn) { - processedReturnTypeAnnotation = { - type: 'VoidTypeAnnotation', - }; - } - - const argsSignatureParts = params.map(t => { - return translateParamTypeToJniType(t, resolveAlias); - }); - if (isPromiseReturn) { - // Additional promise arg for this case. - argsSignatureParts.push( - translateReturnTypeToJniType(returnTypeAnnotation, resolveAlias), - ); - } - const argsSignature = argsSignatureParts.join(''); - const returnSignature = - name === 'getConstants' - ? 'Ljava/util/Map;' - : translateReturnTypeToJniType( - processedReturnTypeAnnotation, - resolveAlias, - ); - - return `(${argsSignature})${returnSignature}`; -} - -function translateMethodForImplementation( - hasteModuleName: string, - property: NativeModulePropertyShape, - resolveAlias: AliasResolver, -): string { - const [propertyTypeAnnotation] = - unwrapNullable(property.typeAnnotation); - const {returnTypeAnnotation} = propertyTypeAnnotation; - - if ( - property.name === 'getConstants' && - returnTypeAnnotation.type === 'ObjectTypeAnnotation' && - returnTypeAnnotation.properties.length === 0 - ) { - return ''; - } - - return HostFunctionTemplate({ - hasteModuleName, - propertyName: property.name, - jniSignature: translateMethodTypeToJniSignature(property, resolveAlias), - jsReturnType: translateReturnTypeToKind(returnTypeAnnotation, resolveAlias), - }); -} - -module.exports = { - generate( - libraryName: string, - schema: SchemaType, - packageName?: string, - assumeNonnull: boolean = false, - ): FilesOutput { - const nativeModules = getModules(schema); - - const modules = Object.keys(nativeModules) - .filter(hasteModuleName => { - const module = nativeModules[hasteModuleName]; - return !( - module.excludedPlatforms != null && - module.excludedPlatforms.includes('android') - ); - }) - .sort() - .map(hasteModuleName => { - const { - aliases, - spec: {properties}, - } = nativeModules[hasteModuleName]; - const resolveAlias = createAliasResolver(aliases); - - const translatedMethods = properties - .map(property => - translateMethodForImplementation( - hasteModuleName, - property, - resolveAlias, - ), - ) - .join('\n\n'); - - return ( - translatedMethods + - '\n\n' + - ModuleClassConstructorTemplate({ - hasteModuleName, - methods: properties - .map(({name: propertyName, typeAnnotation}) => { - const [{returnTypeAnnotation, params}] = - unwrapNullable( - typeAnnotation, - ); - - if ( - propertyName === 'getConstants' && - returnTypeAnnotation.type === 'ObjectTypeAnnotation' && - returnTypeAnnotation.properties && - returnTypeAnnotation.properties.length === 0 - ) { - return null; - } - - return { - propertyName, - argCount: params.length, - }; - }) - .filter(Boolean), - }) - ); - }) - .join('\n'); - - // $FlowFixMe[missing-type-arg] - const moduleLookups = Object.keys(nativeModules) - .filter(hasteModuleName => { - const module = nativeModules[hasteModuleName]; - return !( - module.excludedPlatforms != null && - module.excludedPlatforms.includes('android') - ); - }) - .sort((a, b) => { - const moduleA = nativeModules[a]; - const moduleB = nativeModules[b]; - const nameA = moduleA.moduleNames[0]; - const nameB = moduleB.moduleNames[0]; - if (nameA < nameB) { - return -1; - } else if (nameA > nameB) { - return 1; - } - return 0; - }) - .flatMap<{moduleName: string, hasteModuleName: string}>( - (hasteModuleName: string) => { - const {moduleNames} = nativeModules[hasteModuleName]; - return moduleNames.map(moduleName => ({ - moduleName, - hasteModuleName, - })); - }, - ); - - const fileName = `${libraryName}-generated.cpp`; - const replacedTemplate = FileTemplate({ - modules: modules, - libraryName: libraryName.replace(/-/g, '_'), - moduleLookups, - include: `"${libraryName}.h"`, - }); - return new Map([[`jni/${fileName}`, replacedTemplate]]); - }, -}; diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleJniH.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleJniH.js deleted file mode 100644 index bdedd8615a99..000000000000 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleJniH.js +++ /dev/null @@ -1,200 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type {SchemaType} from '../../CodegenSchema'; - -type FilesOutput = Map; - -const {getModules} = require('./Utils'); - -const ModuleClassDeclarationTemplate = ({ - hasteModuleName, -}: $ReadOnly<{hasteModuleName: string}>) => { - return `/** - * JNI C++ class for module '${hasteModuleName}' - */ -class JSI_EXPORT ${hasteModuleName}SpecJSI : public JavaTurboModule { -public: - ${hasteModuleName}SpecJSI(const JavaTurboModule::InitParams ¶ms); -}; -`; -}; - -const HeaderFileTemplate = ({ - modules, - libraryName, -}: $ReadOnly<{modules: string, libraryName: string}>) => { - return ` -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * ${'@'}generated by codegen project: GenerateModuleJniH.js - */ - -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -${modules} - -JSI_EXPORT -std::shared_ptr ${libraryName}_ModuleProvider(const std::string &moduleName, const JavaTurboModule::InitParams ¶ms); - -} // namespace react -} // namespace facebook -`; -}; - -// Note: this Android.mk template includes dependencies for both NativeModule and components. -const AndroidMkTemplate = ({libraryName}: $ReadOnly<{libraryName: string}>) => { - return `# 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. - -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE := react_codegen_${libraryName} - -LOCAL_C_INCLUDES := $(LOCAL_PATH) - -LOCAL_SRC_FILES := $(wildcard $(LOCAL_PATH)/*.cpp) $(wildcard $(LOCAL_PATH)/react/renderer/components/${libraryName}/*.cpp) -LOCAL_SRC_FILES := $(subst $(LOCAL_PATH)/,,$(LOCAL_SRC_FILES)) - -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) $(LOCAL_PATH)/react/renderer/components/${libraryName} - -LOCAL_SHARED_LIBRARIES := libfbjni \ - libfolly_runtime \ - libglog \ - libjsi \ - libreact_codegen_rncore \ - libreact_debug \ - libreact_nativemodule_core \ - libreact_render_core \ - libreact_render_debug \ - libreact_render_graphics \ - libreact_render_imagemanager \ - libreact_render_mapbuffer \ - librrc_image \ - librrc_view \ - libturbomodulejsijni \ - libyoga - -LOCAL_CFLAGS := \\ - -DLOG_TAG=\\"ReactNative\\" - -LOCAL_CFLAGS += -fexceptions -frtti -std=c++17 -Wall - -include $(BUILD_SHARED_LIBRARY) -`; -}; - -// Note: this CMakeLists.txt template includes dependencies for both NativeModule and components. -const CMakeListsTemplate = ({ - libraryName, -}: $ReadOnly<{libraryName: string}>) => { - return `# 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. - -cmake_minimum_required(VERSION 3.13) -set(CMAKE_VERBOSE_MAKEFILE on) - -file(GLOB react_codegen_SRCS CONFIGURE_DEPENDS *.cpp react/renderer/components/${libraryName}/*.cpp) - -add_library( - react_codegen_${libraryName} - SHARED - \${react_codegen_SRCS} -) - -target_include_directories(react_codegen_${libraryName} PUBLIC . react/renderer/components/${libraryName}) - -target_link_libraries( - react_codegen_${libraryName} - fbjni - folly_runtime - glog - jsi - ${libraryName !== 'rncore' ? 'react_codegen_rncore' : ''} - react_debug - react_nativemodule_core - react_render_core - react_render_debug - react_render_graphics - react_render_imagemanager - rrc_image - rrc_view - turbomodulejsijni - yoga -) - -target_compile_options( - react_codegen_${libraryName} - PRIVATE - -DLOG_TAG=\\"ReactNative\\" - -fexceptions - -frtti - -std=c++17 - -Wall -) -`; -}; - -module.exports = { - generate( - libraryName: string, - schema: SchemaType, - packageName?: string, - assumeNonnull: boolean = false, - ): FilesOutput { - const nativeModules = getModules(schema); - const modules = Object.keys(nativeModules) - .filter(hasteModuleName => { - const module = nativeModules[hasteModuleName]; - return !( - module.excludedPlatforms != null && - module.excludedPlatforms.includes('android') - ); - }) - .sort() - .map(hasteModuleName => ModuleClassDeclarationTemplate({hasteModuleName})) - .join('\n'); - - const fileName = `${libraryName}.h`; - const replacedTemplate = HeaderFileTemplate({ - modules: modules, - libraryName: libraryName.replace(/-/g, '_'), - }); - return new Map([ - [`jni/${fileName}`, replacedTemplate], - [ - 'jni/Android.mk', - AndroidMkTemplate({ - libraryName: libraryName, - }), - ], - ['jni/CMakeLists.txt', CMakeListsTemplate({libraryName: libraryName})], - ]); - }, -}; diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/StructCollector.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/StructCollector.js deleted file mode 100644 index ef7af6ae44a1..000000000000 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/StructCollector.js +++ /dev/null @@ -1,208 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type { - Nullable, - NativeModuleObjectTypeAnnotation, - NativeModuleStringTypeAnnotation, - NativeModuleNumberTypeAnnotation, - NativeModuleInt32TypeAnnotation, - NativeModuleDoubleTypeAnnotation, - NativeModuleFloatTypeAnnotation, - NativeModuleBooleanTypeAnnotation, - NativeModuleEnumDeclaration, - NativeModuleGenericObjectTypeAnnotation, - ReservedTypeAnnotation, - NativeModuleTypeAliasTypeAnnotation, - NativeModuleArrayTypeAnnotation, - NativeModuleBaseTypeAnnotation, -} from '../../../CodegenSchema'; - -import type {AliasResolver} from '../Utils'; - -const {capitalize} = require('../../Utils'); -const { - unwrapNullable, - wrapNullable, -} = require('../../../parsers/parsers-commons'); - -type StructContext = 'CONSTANTS' | 'REGULAR'; - -export type RegularStruct = $ReadOnly<{ - context: 'REGULAR', - name: string, - properties: $ReadOnlyArray, -}>; - -export type ConstantsStruct = $ReadOnly<{ - context: 'CONSTANTS', - name: string, - properties: $ReadOnlyArray, -}>; - -export type Struct = RegularStruct | ConstantsStruct; - -export type StructProperty = $ReadOnly<{ - name: string, - optional: boolean, - typeAnnotation: Nullable, -}>; - -export type StructTypeAnnotation = - | NativeModuleStringTypeAnnotation - | NativeModuleNumberTypeAnnotation - | NativeModuleInt32TypeAnnotation - | NativeModuleDoubleTypeAnnotation - | NativeModuleFloatTypeAnnotation - | NativeModuleBooleanTypeAnnotation - | NativeModuleEnumDeclaration - | NativeModuleGenericObjectTypeAnnotation - | ReservedTypeAnnotation - | NativeModuleTypeAliasTypeAnnotation - | NativeModuleArrayTypeAnnotation>; - -class StructCollector { - _structs: Map = new Map(); - - process( - structName: string, - structContext: StructContext, - resolveAlias: AliasResolver, - nullableTypeAnnotation: Nullable, - ): Nullable { - const [typeAnnotation, nullable] = unwrapNullable(nullableTypeAnnotation); - switch (typeAnnotation.type) { - case 'ObjectTypeAnnotation': { - this._insertStruct( - structName, - structContext, - resolveAlias, - typeAnnotation, - ); - return wrapNullable(nullable, { - type: 'TypeAliasTypeAnnotation', - name: structName, - }); - } - case 'ArrayTypeAnnotation': { - if (typeAnnotation.elementType == null) { - return wrapNullable(nullable, { - type: 'ArrayTypeAnnotation', - }); - } - - return wrapNullable(nullable, { - type: 'ArrayTypeAnnotation', - elementType: this.process( - structName + 'Element', - structContext, - resolveAlias, - typeAnnotation.elementType, - ), - }); - } - case 'TypeAliasTypeAnnotation': { - this._insertAlias(typeAnnotation.name, structContext, resolveAlias); - return wrapNullable(nullable, typeAnnotation); - } - case 'EnumDeclaration': - return wrapNullable(nullable, typeAnnotation); - case 'MixedTypeAnnotation': - throw new Error('Mixed types are unsupported in structs'); - case 'UnionTypeAnnotation': - throw new Error('Union types are unsupported in structs'); - default: { - return wrapNullable(nullable, typeAnnotation); - } - } - } - - _insertAlias( - aliasName: string, - structContext: StructContext, - resolveAlias: AliasResolver, - ): void { - const usedStruct = this._structs.get(aliasName); - if (usedStruct == null) { - this._insertStruct( - aliasName, - structContext, - resolveAlias, - resolveAlias(aliasName), - ); - } else if (usedStruct.context !== structContext) { - throw new Error( - `Tried to use alias '${aliasName}' in a getConstants() return type and inside a regular struct.`, - ); - } - } - - _insertStruct( - structName: string, - structContext: StructContext, - resolveAlias: AliasResolver, - objectTypeAnnotation: NativeModuleObjectTypeAnnotation, - ): void { - // $FlowFixMe[missing-type-arg] - const properties = objectTypeAnnotation.properties.map< - $ReadOnly<{ - name: string, - optional: boolean, - typeAnnotation: Nullable, - }>, - >(property => { - const propertyStructName = structName + capitalize(property.name); - - return { - ...property, - typeAnnotation: this.process( - propertyStructName, - structContext, - resolveAlias, - property.typeAnnotation, - ), - }; - }); - - switch (structContext) { - case 'REGULAR': - this._structs.set(structName, { - name: structName, - context: 'REGULAR', - properties: properties, - }); - break; - case 'CONSTANTS': - this._structs.set(structName, { - name: structName, - context: 'CONSTANTS', - properties: properties, - }); - break; - default: - (structContext: empty); - throw new Error(`Detected an invalid struct context: ${structContext}`); - } - } - - getAllStructs(): $ReadOnlyArray { - return [...this._structs.values()]; - } - - getStruct(name: string): ?Struct { - return this._structs.get(name); - } -} - -module.exports = { - StructCollector, -}; diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/Utils.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/Utils.js deleted file mode 100644 index 59121a4b52fa..000000000000 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/Utils.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type {StructProperty} from './StructCollector'; - -function getSafePropertyName(property: StructProperty): string { - if (property.name === 'id') { - return `${property.name}_`; - } - return property.name; -} - -function getNamespacedStructName( - hasteModuleName: string, - structName: string, -): string { - return `JS::${hasteModuleName}::${structName}`; -} - -module.exports = { - getSafePropertyName, - getNamespacedStructName, -}; diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/header/serializeConstantsStruct.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/header/serializeConstantsStruct.js deleted file mode 100644 index 0fa67683e662..000000000000 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/header/serializeConstantsStruct.js +++ /dev/null @@ -1,288 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -const {getSafePropertyName, getNamespacedStructName} = require('../Utils'); -const {capitalize} = require('../../../Utils'); - -import type {Nullable} from '../../../../CodegenSchema'; -import type {StructTypeAnnotation, ConstantsStruct} from '../StructCollector'; -import type {StructSerilizationOutput} from './serializeStruct'; - -const {unwrapNullable} = require('../../../../parsers/parsers-commons'); - -const StructTemplate = ({ - hasteModuleName, - structName, - builderInputProps, -}: $ReadOnly<{ - hasteModuleName: string, - structName: string, - builderInputProps: string, -}>) => `namespace JS { - namespace ${hasteModuleName} { - struct ${structName} { - - struct Builder { - struct Input { - ${builderInputProps} - }; - - /** Initialize with a set of values */ - Builder(const Input i); - /** Initialize with an existing ${structName} */ - Builder(${structName} i); - /** Builds the object. Generally used only by the infrastructure. */ - NSDictionary *buildUnsafeRawValue() const { return _factory(); }; - private: - NSDictionary *(^_factory)(void); - }; - - static ${structName} fromUnsafeRawValue(NSDictionary *const v) { return {v}; } - NSDictionary *unsafeRawValue() const { return _v; } - private: - ${structName}(NSDictionary *const v) : _v(v) {} - NSDictionary *_v; - }; - } -}`; - -const MethodTemplate = ({ - hasteModuleName, - structName, - properties, -}: $ReadOnly<{ - hasteModuleName: string, - structName: string, - properties: string, -}>) => `inline JS::${hasteModuleName}::${structName}::Builder::Builder(const Input i) : _factory(^{ - NSMutableDictionary *d = [NSMutableDictionary new]; -${properties} - return d; -}) {} -inline JS::${hasteModuleName}::${structName}::Builder::Builder(${structName} i) : _factory(^{ - return i.unsafeRawValue(); -}) {}`; - -function toObjCType( - hasteModuleName: string, - nullableTypeAnnotation: Nullable, - isOptional: boolean = false, -): string { - const [typeAnnotation, nullable] = unwrapNullable(nullableTypeAnnotation); - const isRequired = !nullable && !isOptional; - const wrapOptional = (type: string) => { - return isRequired ? type : `std::optional<${type}>`; - }; - - switch (typeAnnotation.type) { - case 'ReservedTypeAnnotation': - switch (typeAnnotation.name) { - case 'RootTag': - return wrapOptional('double'); - default: - (typeAnnotation.name: empty); - throw new Error(`Unknown prop type, found: ${typeAnnotation.name}"`); - } - case 'StringTypeAnnotation': - return 'NSString *'; - case 'NumberTypeAnnotation': - return wrapOptional('double'); - case 'FloatTypeAnnotation': - return wrapOptional('double'); - case 'Int32TypeAnnotation': - return wrapOptional('double'); - case 'DoubleTypeAnnotation': - return wrapOptional('double'); - case 'BooleanTypeAnnotation': - return wrapOptional('bool'); - case 'EnumDeclaration': - switch (typeAnnotation.memberType) { - case 'NumberTypeAnnotation': - return wrapOptional('double'); - case 'StringTypeAnnotation': - return 'NSString *'; - default: - throw new Error( - `Couldn't convert enum into ObjC type: ${typeAnnotation.type}"`, - ); - } - case 'GenericObjectTypeAnnotation': - return isRequired ? 'id ' : 'id _Nullable '; - case 'ArrayTypeAnnotation': - if (typeAnnotation.elementType == null) { - return isRequired ? 'id ' : 'id _Nullable '; - } - - return wrapOptional( - `std::vector<${toObjCType( - hasteModuleName, - typeAnnotation.elementType, - )}>`, - ); - case 'TypeAliasTypeAnnotation': - const structName = capitalize(typeAnnotation.name); - const namespacedStructName = getNamespacedStructName( - hasteModuleName, - structName, - ); - return wrapOptional(`${namespacedStructName}::Builder`); - default: - (typeAnnotation.type: empty); - throw new Error( - `Couldn't convert into ObjC type: ${typeAnnotation.type}"`, - ); - } -} - -function toObjCValue( - hasteModuleName: string, - nullableTypeAnnotation: Nullable, - value: string, - depth: number, - isOptional: boolean = false, -): string { - const [typeAnnotation, nullable] = unwrapNullable(nullableTypeAnnotation); - const isRequired = !nullable && !isOptional; - - function wrapPrimitive(type: string) { - return !isRequired - ? `${value}.has_value() ? @((${type})${value}.value()) : nil` - : `@(${value})`; - } - - switch (typeAnnotation.type) { - case 'ReservedTypeAnnotation': - switch (typeAnnotation.name) { - case 'RootTag': - return wrapPrimitive('double'); - default: - (typeAnnotation.name: empty); - throw new Error( - `Couldn't convert into ObjC type: ${typeAnnotation.type}"`, - ); - } - case 'StringTypeAnnotation': - return value; - case 'NumberTypeAnnotation': - return wrapPrimitive('double'); - case 'FloatTypeAnnotation': - return wrapPrimitive('double'); - case 'Int32TypeAnnotation': - return wrapPrimitive('double'); - case 'DoubleTypeAnnotation': - return wrapPrimitive('double'); - case 'BooleanTypeAnnotation': - return wrapPrimitive('BOOL'); - case 'EnumDeclaration': - switch (typeAnnotation.memberType) { - case 'NumberTypeAnnotation': - return wrapPrimitive('double'); - case 'StringTypeAnnotation': - return value; - default: - throw new Error( - `Couldn't convert enum into ObjC value: ${typeAnnotation.type}"`, - ); - } - case 'GenericObjectTypeAnnotation': - return value; - case 'ArrayTypeAnnotation': - const {elementType} = typeAnnotation; - if (elementType == null) { - return value; - } - - const localVarName = `el${'_'.repeat(depth + 1)}`; - const elementObjCType = toObjCType(hasteModuleName, elementType); - const elementObjCValue = toObjCValue( - hasteModuleName, - elementType, - localVarName, - depth + 1, - ); - - const RCTConvertVecToArray = (transformer: string) => { - return `RCTConvert${ - !isRequired ? 'Optional' : '' - }VecToArray(${value}, ${transformer})`; - }; - - return RCTConvertVecToArray( - `^id(${elementObjCType} ${localVarName}) { return ${elementObjCValue}; }`, - ); - case 'TypeAliasTypeAnnotation': - return !isRequired - ? `${value}.has_value() ? ${value}.value().buildUnsafeRawValue() : nil` - : `${value}.buildUnsafeRawValue()`; - default: - (typeAnnotation.type: empty); - throw new Error( - `Couldn't convert into ObjC value: ${typeAnnotation.type}"`, - ); - } -} - -function serializeConstantsStruct( - hasteModuleName: string, - struct: ConstantsStruct, -): StructSerilizationOutput { - const declaration = StructTemplate({ - hasteModuleName, - structName: struct.name, - builderInputProps: struct.properties - .map(property => { - const {typeAnnotation, optional} = property; - const safePropName = getSafePropertyName(property); - const objCType = toObjCType(hasteModuleName, typeAnnotation, optional); - - if (!optional) { - return `RCTRequired<${objCType}> ${safePropName};`; - } - - const space = ' '.repeat(objCType.endsWith('*') ? 0 : 1); - return `${objCType}${space}${safePropName};`; - }) - .join('\n '), - }); - - const methods = MethodTemplate({ - hasteModuleName, - structName: struct.name, - properties: struct.properties - .map(property => { - const {typeAnnotation, optional, name: propName} = property; - const safePropName = getSafePropertyName(property); - const objCValue = toObjCValue( - hasteModuleName, - typeAnnotation, - safePropName, - 0, - optional, - ); - - let varDecl = `auto ${safePropName} = i.${safePropName}`; - if (!optional) { - varDecl += '.get()'; - } - - const assignment = `d[@"${propName}"] = ` + objCValue; - return ` ${varDecl};\n ${assignment};`; - }) - .join('\n'), - }); - - return {declaration, methods}; -} - -module.exports = { - serializeConstantsStruct, -}; diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/header/serializeRegularStruct.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/header/serializeRegularStruct.js deleted file mode 100644 index e6c73c733888..000000000000 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/header/serializeRegularStruct.js +++ /dev/null @@ -1,279 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -const {getSafePropertyName, getNamespacedStructName} = require('../Utils'); -const {capitalize} = require('../../../Utils'); - -import type {Nullable} from '../../../../CodegenSchema'; -import type {StructTypeAnnotation, RegularStruct} from '../StructCollector'; -import type {StructSerilizationOutput} from './serializeStruct'; - -const {unwrapNullable} = require('../../../../parsers/parsers-commons'); - -const StructTemplate = ({ - hasteModuleName, - structName, - structProperties, -}: $ReadOnly<{ - hasteModuleName: string, - structName: string, - structProperties: string, -}>) => `namespace JS { - namespace ${hasteModuleName} { - struct ${structName} { - ${structProperties} - - ${structName}(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (${hasteModuleName}_${structName}) -+ (RCTManagedPointer *)JS_${hasteModuleName}_${structName}:(id)json; -@end`; - -const MethodTemplate = ({ - returnType, - returnValue, - hasteModuleName, - structName, - propertyName, - safePropertyName, -}: $ReadOnly<{ - returnType: string, - returnValue: string, - hasteModuleName: string, - structName: string, - propertyName: string, - safePropertyName: string, -}>) => `inline ${returnType}JS::${hasteModuleName}::${structName}::${safePropertyName}() const -{ - id const p = _v[@"${propertyName}"]; - return ${returnValue}; -}`; - -function toObjCType( - hasteModuleName: string, - nullableTypeAnnotation: Nullable, - isOptional: boolean = false, -): string { - const [typeAnnotation, nullable] = unwrapNullable(nullableTypeAnnotation); - const isRequired = !nullable && !isOptional; - const wrapOptional = (type: string) => { - return isRequired ? type : `std::optional<${type}>`; - }; - - switch (typeAnnotation.type) { - case 'ReservedTypeAnnotation': - switch (typeAnnotation.name) { - case 'RootTag': - return wrapOptional('double'); - default: - (typeAnnotation.name: empty); - throw new Error(`Unknown prop type, found: ${typeAnnotation.name}"`); - } - case 'StringTypeAnnotation': - return 'NSString *'; - case 'NumberTypeAnnotation': - return wrapOptional('double'); - case 'FloatTypeAnnotation': - return wrapOptional('double'); - case 'Int32TypeAnnotation': - return wrapOptional('double'); - case 'DoubleTypeAnnotation': - return wrapOptional('double'); - case 'BooleanTypeAnnotation': - return wrapOptional('bool'); - case 'EnumDeclaration': - switch (typeAnnotation.memberType) { - case 'NumberTypeAnnotation': - return wrapOptional('double'); - case 'StringTypeAnnotation': - return 'NSString *'; - default: - throw new Error( - `Couldn't convert enum into ObjC type: ${typeAnnotation.type}"`, - ); - } - case 'GenericObjectTypeAnnotation': - return isRequired ? 'id ' : 'id _Nullable'; - case 'ArrayTypeAnnotation': - if (typeAnnotation.elementType == null) { - return isRequired ? 'id ' : 'id _Nullable'; - } - return wrapOptional( - `facebook::react::LazyVector<${toObjCType( - hasteModuleName, - typeAnnotation.elementType, - )}>`, - ); - case 'TypeAliasTypeAnnotation': - const structName = capitalize(typeAnnotation.name); - const namespacedStructName = getNamespacedStructName( - hasteModuleName, - structName, - ); - return wrapOptional(namespacedStructName); - default: - (typeAnnotation.type: empty); - throw new Error( - `Couldn't convert into ObjC type: ${typeAnnotation.type}"`, - ); - } -} - -function toObjCValue( - hasteModuleName: string, - nullableTypeAnnotation: Nullable, - value: string, - depth: number, - isOptional: boolean = false, -): string { - const [typeAnnotation, nullable] = unwrapNullable(nullableTypeAnnotation); - const isRequired = !nullable && !isOptional; - const RCTBridgingTo = (type: string, arg?: string) => { - const args = [value, arg].filter(Boolean).join(', '); - return isRequired - ? `RCTBridgingTo${type}(${args})` - : `RCTBridgingToOptional${type}(${args})`; - }; - - switch (typeAnnotation.type) { - case 'ReservedTypeAnnotation': - switch (typeAnnotation.name) { - case 'RootTag': - return RCTBridgingTo('Double'); - default: - (typeAnnotation.name: empty); - throw new Error( - `Couldn't convert into ObjC type: ${typeAnnotation.type}"`, - ); - } - case 'StringTypeAnnotation': - return RCTBridgingTo('String'); - case 'NumberTypeAnnotation': - return RCTBridgingTo('Double'); - case 'FloatTypeAnnotation': - return RCTBridgingTo('Double'); - case 'Int32TypeAnnotation': - return RCTBridgingTo('Double'); - case 'DoubleTypeAnnotation': - return RCTBridgingTo('Double'); - case 'BooleanTypeAnnotation': - return RCTBridgingTo('Bool'); - case 'EnumDeclaration': - switch (typeAnnotation.memberType) { - case 'NumberTypeAnnotation': - return RCTBridgingTo('Double'); - case 'StringTypeAnnotation': - return RCTBridgingTo('String'); - default: - throw new Error( - `Couldn't convert enum into ObjC value: ${typeAnnotation.type}"`, - ); - } - case 'GenericObjectTypeAnnotation': - return value; - case 'ArrayTypeAnnotation': - const {elementType} = typeAnnotation; - if (elementType == null) { - return value; - } - - const localVarName = `itemValue_${depth}`; - const elementObjCType = toObjCType(hasteModuleName, elementType); - const elementObjCValue = toObjCValue( - hasteModuleName, - elementType, - localVarName, - depth + 1, - ); - - return RCTBridgingTo( - 'Vec', - `^${elementObjCType}(id ${localVarName}) { return ${elementObjCValue}; }`, - ); - case 'TypeAliasTypeAnnotation': - const structName = capitalize(typeAnnotation.name); - const namespacedStructName = getNamespacedStructName( - hasteModuleName, - structName, - ); - - return !isRequired - ? `(${value} == nil ? std::nullopt : std::make_optional(${namespacedStructName}(${value})))` - : `${namespacedStructName}(${value})`; - default: - (typeAnnotation.type: empty); - throw new Error( - `Couldn't convert into ObjC value: ${typeAnnotation.type}"`, - ); - } -} - -function serializeRegularStruct( - hasteModuleName: string, - struct: RegularStruct, -): StructSerilizationOutput { - const declaration = StructTemplate({ - hasteModuleName: hasteModuleName, - structName: struct.name, - structProperties: struct.properties - .map(property => { - const {typeAnnotation, optional} = property; - const safePropName = getSafePropertyName(property); - const returnType = toObjCType( - hasteModuleName, - typeAnnotation, - optional, - ); - - const padding = ' '.repeat(returnType.endsWith('*') ? 0 : 1); - return `${returnType}${padding}${safePropName}() const;`; - }) - .join('\n '), - }); - - // $FlowFixMe[missing-type-arg] - const methods = struct.properties - .map(property => { - const {typeAnnotation, optional, name: propName} = property; - const safePropertyName = getSafePropertyName(property); - const returnType = toObjCType(hasteModuleName, typeAnnotation, optional); - const returnValue = toObjCValue( - hasteModuleName, - typeAnnotation, - 'p', - 0, - optional, - ); - - const padding = ' '.repeat(returnType.endsWith('*') ? 0 : 1); - return MethodTemplate({ - hasteModuleName, - structName: struct.name, - returnType: returnType + padding, - returnValue: returnValue, - propertyName: propName, - safePropertyName, - }); - }) - .join('\n'); - - return {methods, declaration}; -} - -module.exports = { - serializeRegularStruct, -}; diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/header/serializeStruct.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/header/serializeStruct.js deleted file mode 100644 index d5b38f45357a..000000000000 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/header/serializeStruct.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type {Struct} from '../StructCollector'; - -const {serializeConstantsStruct} = require('./serializeConstantsStruct'); -const {serializeRegularStruct} = require('./serializeRegularStruct'); - -export type StructSerilizationOutput = $ReadOnly<{ - methods: string, - declaration: string, -}>; - -function serializeStruct( - hasteModuleName: string, - struct: Struct, -): StructSerilizationOutput { - if (struct.context === 'REGULAR') { - return serializeRegularStruct(hasteModuleName, struct); - } - return serializeConstantsStruct(hasteModuleName, struct); -} - -module.exports = { - serializeStruct, -}; diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/index.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/index.js deleted file mode 100644 index 8f8da790b904..000000000000 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/index.js +++ /dev/null @@ -1,219 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; -import type {NativeModulePropertyShape} from '../../../CodegenSchema'; - -import type {SchemaType} from '../../../CodegenSchema'; -import type {MethodSerializationOutput} from './serializeMethod'; - -const {createAliasResolver, getModules} = require('../Utils'); - -const {StructCollector} = require('./StructCollector'); -const {serializeStruct} = require('./header/serializeStruct'); -const {serializeMethod} = require('./serializeMethod'); -const {serializeModuleSource} = require('./source/serializeModule'); - -type FilesOutput = Map; - -const ModuleDeclarationTemplate = ({ - hasteModuleName, - structDeclarations, - protocolMethods, -}: $ReadOnly<{ - hasteModuleName: string, - structDeclarations: string, - protocolMethods: string, -}>) => `${structDeclarations} -@protocol ${hasteModuleName}Spec - -${protocolMethods} - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module '${hasteModuleName}' - */ - class JSI_EXPORT ${hasteModuleName}SpecJSI : public ObjCTurboModule { - public: - ${hasteModuleName}SpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook`; - -const HeaderFileTemplate = ({ - moduleDeclarations, - structInlineMethods, - assumeNonnull, -}: $ReadOnly<{ - moduleDeclarations: string, - structInlineMethods: string, - assumeNonnull: boolean, -}>) => - `/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * ${'@'}generated by codegen project: GenerateModuleObjCpp - * - * We create an umbrella header (and corresponding implementation) here since - * Cxx compilation in BUCK has a limitation: source-code producing genrule()s - * must have a single output. More files => more genrule()s => slower builds. - */ - -#ifndef __cplusplus -#error This file must be compiled as Obj-C++. If you are importing it, you must change your file extension to .mm. -#endif -#import -#import -#import -#import -#import -#import -#import -#import -#import -#import - -` + - (assumeNonnull ? '\nNS_ASSUME_NONNULL_BEGIN\n' : '') + - moduleDeclarations + - '\n' + - structInlineMethods + - (assumeNonnull ? '\nNS_ASSUME_NONNULL_END\n' : '\n'); - -const SourceFileTemplate = ({ - headerFileName, - moduleImplementations, -}: $ReadOnly<{ - headerFileName: string, - moduleImplementations: string, -}>) => `/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * ${'@'}generated by codegen project: GenerateModuleObjCpp - * - * We create an umbrella header (and corresponding implementation) here since - * Cxx compilation in BUCK has a limitation: source-code producing genrule()s - * must have a single output. More files => more genrule()s => slower builds. - */ - -#import "${headerFileName}" - -${moduleImplementations} -`; - -module.exports = { - generate( - libraryName: string, - schema: SchemaType, - packageName?: string, - assumeNonnull: boolean, - ): FilesOutput { - const nativeModules = getModules(schema); - - const moduleDeclarations: Array = []; - const structInlineMethods: Array = []; - const moduleImplementations: Array = []; - - const hasteModuleNames: Array = Object.keys(nativeModules).sort(); - for (const hasteModuleName of hasteModuleNames) { - const { - aliases, - excludedPlatforms, - spec: {properties}, - } = nativeModules[hasteModuleName]; - if (excludedPlatforms != null && excludedPlatforms.includes('iOS')) { - continue; - } - const resolveAlias = createAliasResolver(aliases); - const structCollector = new StructCollector(); - - const methodSerializations: Array = []; - const serializeProperty = (property: NativeModulePropertyShape) => { - methodSerializations.push( - ...serializeMethod( - hasteModuleName, - property, - structCollector, - resolveAlias, - ), - ); - }; - - /** - * Note: As we serialize NativeModule methods, we insert structs into - * StructCollector, as we encounter them. - */ - properties - .filter(property => property.name !== 'getConstants') - .forEach(serializeProperty); - properties - .filter(property => property.name === 'getConstants') - .forEach(serializeProperty); - - const generatedStructs = structCollector.getAllStructs(); - const structStrs = []; - const methodStrs = []; - - for (const struct of generatedStructs) { - const {methods, declaration} = serializeStruct(hasteModuleName, struct); - structStrs.push(declaration); - methodStrs.push(methods); - } - - moduleDeclarations.push( - ModuleDeclarationTemplate({ - hasteModuleName: hasteModuleName, - structDeclarations: structStrs.join('\n'), - protocolMethods: methodSerializations - .map(({protocolMethod}) => protocolMethod) - .join('\n'), - }), - ); - - structInlineMethods.push(methodStrs.join('\n')); - - moduleImplementations.push( - serializeModuleSource( - hasteModuleName, - generatedStructs, - methodSerializations.filter( - ({selector}) => selector !== '@selector(constantsToExport)', - ), - ), - ); - } - - const headerFileName = `${libraryName}.h`; - const headerFile = HeaderFileTemplate({ - moduleDeclarations: moduleDeclarations.join('\n'), - structInlineMethods: structInlineMethods.join('\n'), - assumeNonnull, - }); - - const sourceFileName = `${libraryName}-generated.mm`; - const sourceFile = SourceFileTemplate({ - headerFileName, - moduleImplementations: moduleImplementations.join('\n'), - }); - - return new Map([ - [headerFileName, headerFile], - [sourceFileName, sourceFile], - ]); - }, -}; diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/serializeMethod.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/serializeMethod.js deleted file mode 100644 index d0864ca5ea8e..000000000000 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/serializeMethod.js +++ /dev/null @@ -1,488 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type { - Nullable, - NamedShape, - NativeModuleParamTypeAnnotation, - NativeModuleReturnTypeAnnotation, - NativeModulePropertyShape, -} from '../../../CodegenSchema'; - -import type {AliasResolver} from '../Utils'; -import type {StructCollector} from './StructCollector'; - -const invariant = require('invariant'); -const {getNamespacedStructName} = require('./Utils'); -const {capitalize} = require('../../Utils'); -const { - wrapNullable, - unwrapNullable, -} = require('../../../parsers/parsers-commons'); - -const ProtocolMethodTemplate = ({ - returnObjCType, - methodName, - params, -}: $ReadOnly<{ - returnObjCType: string, - methodName: string, - params: string, -}>) => `- (${returnObjCType})${methodName}${params};`; - -export type StructParameterRecord = $ReadOnly<{ - paramIndex: number, - structName: string, -}>; - -type ReturnJSType = - | 'VoidKind' - | 'BooleanKind' - | 'PromiseKind' - | 'ObjectKind' - | 'ArrayKind' - | 'NumberKind' - | 'StringKind'; - -export type MethodSerializationOutput = $ReadOnly<{ - methodName: string, - protocolMethod: string, - selector: string, - structParamRecords: $ReadOnlyArray, - returnJSType: ReturnJSType, - argCount: number, -}>; - -function serializeMethod( - hasteModuleName: string, - property: NativeModulePropertyShape, - structCollector: StructCollector, - resolveAlias: AliasResolver, -): $ReadOnlyArray { - const {name: methodName, typeAnnotation: nullableTypeAnnotation} = property; - const [propertyTypeAnnotation] = unwrapNullable(nullableTypeAnnotation); - const {params} = propertyTypeAnnotation; - - if (methodName === 'getConstants') { - return serializeConstantsProtocolMethods( - hasteModuleName, - property, - structCollector, - resolveAlias, - ); - } - - const methodParams: Array<{paramName: string, objCType: string}> = []; - const structParamRecords: Array = []; - - params.forEach((param, index) => { - const structName = getParamStructName(methodName, param); - const {objCType, isStruct} = getParamObjCType( - hasteModuleName, - methodName, - param, - structName, - structCollector, - resolveAlias, - ); - - methodParams.push({paramName: param.name, objCType}); - - if (isStruct) { - structParamRecords.push({paramIndex: index, structName}); - } - }); - - // Unwrap returnTypeAnnotation, so we check if the return type is Promise - // TODO(T76719514): Disallow nullable PromiseTypeAnnotations - const [returnTypeAnnotation] = unwrapNullable( - propertyTypeAnnotation.returnTypeAnnotation, - ); - - if (returnTypeAnnotation.type === 'PromiseTypeAnnotation') { - methodParams.push( - {paramName: 'resolve', objCType: 'RCTPromiseResolveBlock'}, - {paramName: 'reject', objCType: 'RCTPromiseRejectBlock'}, - ); - } - - /** - * Build Protocol Method - **/ - const returnObjCType = getReturnObjCType( - methodName, - propertyTypeAnnotation.returnTypeAnnotation, - ); - const paddingMax = `- (${returnObjCType})${methodName}`.length; - - const objCParams = methodParams.reduce( - ($objCParams, {objCType, paramName}, i) => { - const rhs = `(${objCType})${paramName}`; - const padding = ' '.repeat(Math.max(0, paddingMax - paramName.length)); - return i === 0 - ? `:${rhs}` - : `${$objCParams}\n${padding}${paramName}:${rhs}`; - }, - '', - ); - - const protocolMethod = ProtocolMethodTemplate({ - methodName, - returnObjCType, - params: objCParams, - }); - - /** - * Build ObjC Selector - */ - // $FlowFixMe[missing-type-arg] - const selector = methodParams - .map(({paramName}) => paramName) - .reduce(($selector, paramName, i) => { - return i === 0 ? `${$selector}:` : `${$selector}${paramName}:`; - }, methodName); - - /** - * Build JS Return type - */ - const returnJSType = getReturnJSType(methodName, returnTypeAnnotation); - - return [ - { - methodName, - protocolMethod, - selector: `@selector(${selector})`, - structParamRecords, - returnJSType, - argCount: params.length, - }, - ]; -} - -type Param = NamedShape>; - -function getParamStructName(methodName: string, param: Param): string { - const [typeAnnotation] = unwrapNullable(param.typeAnnotation); - if (typeAnnotation.type === 'TypeAliasTypeAnnotation') { - return typeAnnotation.name; - } - - return `Spec${capitalize(methodName)}${capitalize(param.name)}`; -} - -function getParamObjCType( - hasteModuleName: string, - methodName: string, - param: Param, - structName: string, - structCollector: StructCollector, - resolveAlias: AliasResolver, -): $ReadOnly<{objCType: string, isStruct: boolean}> { - const {name: paramName, typeAnnotation: nullableTypeAnnotation} = param; - const [typeAnnotation, nullable] = unwrapNullable(nullableTypeAnnotation); - const notRequired = param.optional || nullable; - - function wrapIntoNullableIfNeeded(generatedType: string) { - return nullable ? `${generatedType} _Nullable` : generatedType; - } - - const isStruct = (objCType: string) => ({ - isStruct: true, - objCType, - }); - - const notStruct = (objCType: string) => ({ - isStruct: false, - objCType, - }); - - // Handle types that can only be in parameters - switch (typeAnnotation.type) { - case 'FunctionTypeAnnotation': { - return notStruct('RCTResponseSenderBlock'); - } - case 'ArrayTypeAnnotation': { - /** - * Array in params always codegen NSArray * - * - * TODO(T73933406): Support codegen for Arrays of structs and primitives - * - * For example: - * Array => NSArray - * type Animal = {}; - * Array => NSArray, etc. - */ - return notStruct(wrapIntoNullableIfNeeded('NSArray *')); - } - } - - const [structTypeAnnotation] = unwrapNullable( - structCollector.process( - structName, - 'REGULAR', - resolveAlias, - wrapNullable(nullable, typeAnnotation), - ), - ); - - invariant( - structTypeAnnotation.type !== 'ArrayTypeAnnotation', - 'ArrayTypeAnnotations should have been processed earlier', - ); - - switch (structTypeAnnotation.type) { - case 'TypeAliasTypeAnnotation': { - /** - * TODO(T73943261): Support nullable object literals and aliases? - */ - return isStruct( - getNamespacedStructName(hasteModuleName, structTypeAnnotation.name) + - ' &', - ); - } - case 'ReservedTypeAnnotation': - switch (structTypeAnnotation.name) { - case 'RootTag': - return notStruct(notRequired ? 'NSNumber *' : 'double'); - default: - (structTypeAnnotation.name: empty); - throw new Error( - `Unsupported type for param "${paramName}" in ${methodName}. Found: ${structTypeAnnotation.type}`, - ); - } - case 'StringTypeAnnotation': - return notStruct(wrapIntoNullableIfNeeded('NSString *')); - case 'NumberTypeAnnotation': - return notStruct(notRequired ? 'NSNumber *' : 'double'); - case 'FloatTypeAnnotation': - return notStruct(notRequired ? 'NSNumber *' : 'double'); - case 'DoubleTypeAnnotation': - return notStruct(notRequired ? 'NSNumber *' : 'double'); - case 'Int32TypeAnnotation': - return notStruct(notRequired ? 'NSNumber *' : 'double'); - case 'BooleanTypeAnnotation': - return notStruct(notRequired ? 'NSNumber *' : 'BOOL'); - case 'EnumDeclaration': - switch (typeAnnotation.memberType) { - case 'NumberTypeAnnotation': - return notStruct(notRequired ? 'NSNumber *' : 'double'); - case 'StringTypeAnnotation': - return notStruct(wrapIntoNullableIfNeeded('NSString *')); - default: - throw new Error( - `Unsupported enum type for param "${paramName}" in ${methodName}. Found: ${typeAnnotation.type}`, - ); - } - case 'GenericObjectTypeAnnotation': - return notStruct(wrapIntoNullableIfNeeded('NSDictionary *')); - default: - (structTypeAnnotation.type: empty); - throw new Error( - `Unsupported type for param "${paramName}" in ${methodName}. Found: ${typeAnnotation.type}`, - ); - } -} - -function getReturnObjCType( - methodName: string, - nullableTypeAnnotation: Nullable, -): string { - const [typeAnnotation, nullable] = unwrapNullable(nullableTypeAnnotation); - - function wrapIntoNullableIfNeeded(generatedType: string) { - return nullable ? `${generatedType} _Nullable` : generatedType; - } - - switch (typeAnnotation.type) { - case 'VoidTypeAnnotation': - return 'void'; - case 'PromiseTypeAnnotation': - return 'void'; - case 'ObjectTypeAnnotation': - return wrapIntoNullableIfNeeded('NSDictionary *'); - case 'TypeAliasTypeAnnotation': - return wrapIntoNullableIfNeeded('NSDictionary *'); - case 'ArrayTypeAnnotation': - if (typeAnnotation.elementType == null) { - return wrapIntoNullableIfNeeded('NSArray> *'); - } - - return wrapIntoNullableIfNeeded( - `NSArray<${getReturnObjCType( - methodName, - typeAnnotation.elementType, - )}> *`, - ); - case 'ReservedTypeAnnotation': - switch (typeAnnotation.name) { - case 'RootTag': - return wrapIntoNullableIfNeeded('NSNumber *'); - default: - (typeAnnotation.name: empty); - throw new Error( - `Unsupported return type for ${methodName}. Found: ${typeAnnotation.name}`, - ); - } - case 'StringTypeAnnotation': - // TODO: Can NSString * returns not be _Nullable? - // In the legacy codegen, we don't surround NSSTring * with _Nullable - return wrapIntoNullableIfNeeded('NSString *'); - case 'NumberTypeAnnotation': - return wrapIntoNullableIfNeeded('NSNumber *'); - case 'FloatTypeAnnotation': - return wrapIntoNullableIfNeeded('NSNumber *'); - case 'DoubleTypeAnnotation': - return wrapIntoNullableIfNeeded('NSNumber *'); - case 'Int32TypeAnnotation': - return wrapIntoNullableIfNeeded('NSNumber *'); - case 'BooleanTypeAnnotation': - return wrapIntoNullableIfNeeded('NSNumber *'); - case 'EnumDeclaration': - switch (typeAnnotation.memberType) { - case 'NumberTypeAnnotation': - return wrapIntoNullableIfNeeded('NSNumber *'); - case 'StringTypeAnnotation': - return wrapIntoNullableIfNeeded('NSString *'); - default: - throw new Error( - `Unsupported enum return type for ${methodName}. Found: ${typeAnnotation.type}`, - ); - } - case 'GenericObjectTypeAnnotation': - return wrapIntoNullableIfNeeded('NSDictionary *'); - default: - (typeAnnotation.type: - | 'EnumDeclaration' - | 'MixedTypeAnnotation' - | 'UnionTypeAnnotation'); - throw new Error( - `Unsupported return type for ${methodName}. Found: ${typeAnnotation.type}`, - ); - } -} - -function getReturnJSType( - methodName: string, - nullableTypeAnnotation: Nullable, -): ReturnJSType { - const [typeAnnotation] = unwrapNullable(nullableTypeAnnotation); - switch (typeAnnotation.type) { - case 'VoidTypeAnnotation': - return 'VoidKind'; - case 'PromiseTypeAnnotation': - return 'PromiseKind'; - case 'ObjectTypeAnnotation': - return 'ObjectKind'; - case 'TypeAliasTypeAnnotation': - return 'ObjectKind'; - case 'ArrayTypeAnnotation': - return 'ArrayKind'; - case 'ReservedTypeAnnotation': - return 'NumberKind'; - case 'StringTypeAnnotation': - return 'StringKind'; - case 'NumberTypeAnnotation': - return 'NumberKind'; - case 'FloatTypeAnnotation': - return 'NumberKind'; - case 'DoubleTypeAnnotation': - return 'NumberKind'; - case 'Int32TypeAnnotation': - return 'NumberKind'; - case 'BooleanTypeAnnotation': - return 'BooleanKind'; - case 'GenericObjectTypeAnnotation': - return 'ObjectKind'; - case 'EnumDeclaration': - switch (typeAnnotation.memberType) { - case 'NumberTypeAnnotation': - return 'NumberKind'; - case 'StringTypeAnnotation': - return 'StringKind'; - default: - throw new Error( - `Unsupported return type for ${methodName}. Found: ${typeAnnotation.type}`, - ); - } - default: - (typeAnnotation.type: - | 'EnumDeclaration' - | 'MixedTypeAnnotation' - | 'UnionTypeAnnotation'); - throw new Error( - `Unsupported return type for ${methodName}. Found: ${typeAnnotation.type}`, - ); - } -} - -function serializeConstantsProtocolMethods( - hasteModuleName: string, - property: NativeModulePropertyShape, - structCollector: StructCollector, - resolveAlias: AliasResolver, -): $ReadOnlyArray { - const [propertyTypeAnnotation] = unwrapNullable(property.typeAnnotation); - if (propertyTypeAnnotation.params.length !== 0) { - throw new Error( - `${hasteModuleName}.getConstants() may only accept 0 arguments.`, - ); - } - - const {returnTypeAnnotation} = propertyTypeAnnotation; - if (returnTypeAnnotation.type !== 'ObjectTypeAnnotation') { - throw new Error( - `${hasteModuleName}.getConstants() may only return an object literal: {...}.`, - ); - } - - if (returnTypeAnnotation.properties.length === 0) { - return []; - } - - const realTypeAnnotation = structCollector.process( - 'Constants', - 'CONSTANTS', - resolveAlias, - returnTypeAnnotation, - ); - - invariant( - realTypeAnnotation.type === 'TypeAliasTypeAnnotation', - "Unable to generate C++ struct from module's getConstants() method return type.", - ); - - const returnObjCType = `facebook::react::ModuleConstants`; - - // $FlowFixMe[missing-type-arg] - return ['constantsToExport', 'getConstants'].map( - methodName => { - const protocolMethod = ProtocolMethodTemplate({ - methodName, - returnObjCType, - params: '', - }); - - return { - methodName, - protocolMethod, - returnJSType: 'ObjectKind', - selector: `@selector(${methodName})`, - structParamRecords: [], - argCount: 0, - }; - }, - ); -} - -module.exports = { - serializeMethod, -}; diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/source/serializeModule.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/source/serializeModule.js deleted file mode 100644 index 2d9eb34d2564..000000000000 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/source/serializeModule.js +++ /dev/null @@ -1,121 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type {Struct} from '../StructCollector'; -import type { - MethodSerializationOutput, - StructParameterRecord, -} from '../serializeMethod'; - -const ModuleTemplate = ({ - hasteModuleName, - structs, - methodSerializationOutputs, -}: $ReadOnly<{ - hasteModuleName: string, - structs: $ReadOnlyArray, - methodSerializationOutputs: $ReadOnlyArray, -}>) => `${structs - .map(struct => - RCTCxxConvertCategoryTemplate({hasteModuleName, structName: struct.name}), - ) - .join('\n')} -namespace facebook { - namespace react { - ${methodSerializationOutputs - .map(serializedMethodParts => - InlineHostFunctionTemplate({ - hasteModuleName, - methodName: serializedMethodParts.methodName, - returnJSType: serializedMethodParts.returnJSType, - selector: serializedMethodParts.selector, - }), - ) - .join('\n')} - - ${hasteModuleName}SpecJSI::${hasteModuleName}SpecJSI(const ObjCTurboModule::InitParams ¶ms) - : ObjCTurboModule(params) { - ${methodSerializationOutputs - .map(({methodName, structParamRecords, argCount}) => - MethodMapEntryTemplate({ - hasteModuleName, - methodName, - structParamRecords, - argCount, - }), - ) - .join('\n' + ' '.repeat(8))} - } - } // namespace react -} // namespace facebook`; - -const RCTCxxConvertCategoryTemplate = ({ - hasteModuleName, - structName, -}: $ReadOnly<{ - hasteModuleName: string, - structName: string, -}>) => `@implementation RCTCxxConvert (${hasteModuleName}_${structName}) -+ (RCTManagedPointer *)JS_${hasteModuleName}_${structName}:(id)json -{ - return facebook::react::managedPointer(json); -} -@end`; - -const InlineHostFunctionTemplate = ({ - hasteModuleName, - methodName, - returnJSType, - selector, -}: $ReadOnly<{ - hasteModuleName: string, - methodName: string, - returnJSType: string, - selector: string, -}>) => ` - static facebook::jsi::Value __hostFunction_${hasteModuleName}SpecJSI_${methodName}(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ${returnJSType}, "${methodName}", ${selector}, args, count); - }`; - -const MethodMapEntryTemplate = ({ - hasteModuleName, - methodName, - structParamRecords, - argCount, -}: $ReadOnly<{ - hasteModuleName: string, - methodName: string, - structParamRecords: $ReadOnlyArray, - argCount: number, -}>) => ` - methodMap_["${methodName}"] = MethodMetadata {${argCount}, __hostFunction_${hasteModuleName}SpecJSI_${methodName}}; - ${structParamRecords - .map(({paramIndex, structName}) => { - return `setMethodArgConversionSelector(@"${methodName}", ${paramIndex}, @"JS_${hasteModuleName}_${structName}:");`; - }) - .join('\n' + ' '.repeat(8))}`; - -function serializeModuleSource( - hasteModuleName: string, - structs: $ReadOnlyArray, - methodSerializationOutputs: $ReadOnlyArray, -): string { - return ModuleTemplate({ - hasteModuleName, - structs: structs.filter(({context}) => context !== 'CONSTANTS'), - methodSerializationOutputs, - }); -} - -module.exports = { - serializeModuleSource, -}; diff --git a/packages/react-native-codegen/src/generators/modules/Utils.js b/packages/react-native-codegen/src/generators/modules/Utils.js deleted file mode 100644 index b89df46a01f8..000000000000 --- a/packages/react-native-codegen/src/generators/modules/Utils.js +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type { - SchemaType, - NativeModuleAliasMap, - NativeModuleObjectTypeAnnotation, - NativeModuleSchema, -} from '../../CodegenSchema'; - -const invariant = require('invariant'); - -export type AliasResolver = ( - aliasName: string, -) => NativeModuleObjectTypeAnnotation; - -function createAliasResolver(aliasMap: NativeModuleAliasMap): AliasResolver { - return (aliasName: string) => { - const alias = aliasMap[aliasName]; - invariant(alias != null, `Unable to resolve type alias '${aliasName}'.`); - return alias; - }; -} - -function getModules( - schema: SchemaType, -): $ReadOnly<{[hasteModuleName: string]: NativeModuleSchema}> { - return Object.keys(schema.modules).reduce<{[string]: NativeModuleSchema}>( - (modules, hasteModuleName: string) => { - const module = schema.modules[hasteModuleName]; - if (module == null || module.type === 'Component') { - return modules; - } - modules[hasteModuleName] = module; - return modules; - }, - {}, - ); -} - -module.exports = { - createAliasResolver, - getModules, -}; diff --git a/packages/react-native-codegen/src/generators/modules/__test_fixtures__/fixtures.js b/packages/react-native-codegen/src/generators/modules/__test_fixtures__/fixtures.js deleted file mode 100644 index b2b7e0cdfa9a..000000000000 --- a/packages/react-native-codegen/src/generators/modules/__test_fixtures__/fixtures.js +++ /dev/null @@ -1,1669 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {SchemaType} from '../../../CodegenSchema.js'; - -const EMPTY_NATIVE_MODULES: SchemaType = { - modules: { - NativeSampleTurboModule: { - type: 'NativeModule', - aliases: {}, - spec: { - properties: [], - }, - moduleNames: ['SampleTurboModule'], - }, - }, -}; - -const SIMPLE_NATIVE_MODULES: SchemaType = { - modules: { - NativeSampleTurboModule: { - type: 'NativeModule', - aliases: {}, - spec: { - properties: [ - { - name: 'getConstants', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'ObjectTypeAnnotation', - properties: [ - { - optional: false, - name: 'const1', - typeAnnotation: { - type: 'BooleanTypeAnnotation', - }, - }, - { - optional: false, - name: 'const2', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - { - optional: false, - name: 'const3', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - ], - }, - params: [], - }, - }, - { - name: 'voidFunc', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'VoidTypeAnnotation', - }, - params: [], - }, - }, - { - name: 'getBool', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'BooleanTypeAnnotation', - }, - params: [ - { - optional: false, - name: 'arg', - typeAnnotation: { - type: 'BooleanTypeAnnotation', - }, - }, - ], - }, - }, - { - name: 'getNumber', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'NumberTypeAnnotation', - }, - params: [ - { - optional: false, - name: 'arg', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - ], - }, - }, - { - name: 'getString', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'StringTypeAnnotation', - }, - params: [ - { - optional: false, - name: 'arg', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - ], - }, - }, - { - name: 'getArray', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'GenericObjectTypeAnnotation', - }, - }, - params: [ - { - name: 'arg', - optional: false, - typeAnnotation: { - type: 'ArrayTypeAnnotation', - - elementType: { - type: 'GenericObjectTypeAnnotation', - }, - }, - }, - ], - }, - }, - { - name: 'getObject', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'GenericObjectTypeAnnotation', - }, - params: [ - { - optional: false, - name: 'arg', - typeAnnotation: { - type: 'GenericObjectTypeAnnotation', - }, - }, - ], - }, - }, - { - name: 'getRootTag', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'ReservedTypeAnnotation', - name: 'RootTag', - }, - params: [ - { - optional: false, - name: 'arg', - typeAnnotation: { - type: 'ReservedTypeAnnotation', - name: 'RootTag', - }, - }, - ], - }, - }, - { - name: 'getValue', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'GenericObjectTypeAnnotation', - }, - params: [ - { - optional: false, - name: 'x', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - { - optional: false, - name: 'y', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - { - optional: false, - name: 'z', - typeAnnotation: { - type: 'GenericObjectTypeAnnotation', - }, - }, - ], - }, - }, - { - name: 'getValueWithCallback', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'VoidTypeAnnotation', - }, - params: [ - { - name: 'callback', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - params: [], - returnTypeAnnotation: { - type: 'VoidTypeAnnotation', - }, - }, - }, - ], - }, - }, - { - name: 'getValueWithPromise', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'PromiseTypeAnnotation', - }, - params: [ - { - optional: false, - name: 'error', - typeAnnotation: { - type: 'BooleanTypeAnnotation', - }, - }, - ], - }, - }, - { - name: 'getValueWithOptionalArg', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'PromiseTypeAnnotation', - }, - params: [ - { - optional: true, - name: 'parameter', - typeAnnotation: { - type: 'GenericObjectTypeAnnotation', - }, - }, - ], - }, - }, - { - name: 'getEnums', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'StringTypeAnnotation', - }, - params: [ - { - name: 'enumInt', - optional: false, - typeAnnotation: { - type: 'EnumDeclaration', - memberType: 'NumberTypeAnnotation', - }, - }, - { - name: 'enumFloat', - optional: false, - typeAnnotation: { - type: 'EnumDeclaration', - memberType: 'NumberTypeAnnotation', - }, - }, - { - name: 'enumString', - optional: false, - typeAnnotation: { - type: 'EnumDeclaration', - memberType: 'StringTypeAnnotation', - }, - }, - ], - }, - }, - ], - }, - moduleNames: ['SampleTurboModule'], - }, - }, -}; - -const TWO_MODULES_DIFFERENT_FILES: SchemaType = { - modules: { - NativeSampleTurboModule: { - type: 'NativeModule', - aliases: {}, - spec: { - properties: [ - { - name: 'voidFunc', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'VoidTypeAnnotation', - }, - params: [], - }, - }, - ], - }, - moduleNames: ['SampleTurboModule'], - }, - NativeSampleTurboModule2: { - type: 'NativeModule', - aliases: {}, - spec: { - properties: [ - { - name: 'getConstants', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'ObjectTypeAnnotation', - properties: [], - }, - params: [], - }, - }, - { - name: 'voidFunc', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'VoidTypeAnnotation', - }, - params: [], - }, - }, - ], - }, - moduleNames: ['SampleTurboModule2'], - }, - }, -}; - -const COMPLEX_OBJECTS: SchemaType = { - modules: { - NativeSampleTurboModule: { - type: 'NativeModule', - aliases: {}, - spec: { - properties: [ - { - name: 'difficult', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'ObjectTypeAnnotation', - properties: [ - { - optional: false, - name: 'D', - typeAnnotation: { - type: 'BooleanTypeAnnotation', - }, - }, - { - optional: false, - name: 'E', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - { - optional: false, - name: 'F', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - ], - }, - params: [ - { - optional: false, - name: 'A', - typeAnnotation: { - type: 'ObjectTypeAnnotation', - properties: [ - { - optional: false, - name: 'D', - typeAnnotation: { - type: 'BooleanTypeAnnotation', - }, - }, - { - optional: false, - name: 'E', - typeAnnotation: { - type: 'ObjectTypeAnnotation', - properties: [ - { - optional: false, - name: 'D', - typeAnnotation: { - type: 'BooleanTypeAnnotation', - }, - }, - { - optional: false, - name: 'E', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - { - optional: false, - name: 'F', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - { - optional: false, - name: 'id', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - ], - }, - }, - { - optional: false, - name: 'F', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - ], - }, - }, - ], - }, - }, - { - name: 'optionals', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'VoidTypeAnnotation', - }, - params: [ - { - optional: false, - name: 'A', - typeAnnotation: { - type: 'ObjectTypeAnnotation', - properties: [ - { - optional: true, - name: 'optionalNumberProperty', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - { - optional: true, - name: 'optionalArrayProperty', - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'NumberTypeAnnotation', - }, - }, - }, - { - optional: true, - name: 'optionalObjectProperty', - typeAnnotation: { - type: 'ObjectTypeAnnotation', - properties: [ - { - optional: false, - name: 'x', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - { - optional: false, - name: 'y', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - ], - }, - }, - { - optional: true, - name: 'optionalGenericObjectProperty', - typeAnnotation: { - type: 'GenericObjectTypeAnnotation', - }, - }, - { - optional: true, - name: 'optionalBooleanTypeProperty', - typeAnnotation: { - type: 'BooleanTypeAnnotation', - }, - }, - ], - }, - }, - ], - }, - }, - { - name: 'optionalMethod', - optional: true, - typeAnnotation: { - type: 'NullableTypeAnnotation', - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'VoidTypeAnnotation', - }, - params: [ - { - optional: false, - name: 'options', - typeAnnotation: { - type: 'GenericObjectTypeAnnotation', - }, - }, - { - name: 'callback', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - params: [], - returnTypeAnnotation: { - type: 'VoidTypeAnnotation', - }, - }, - }, - { - name: 'extras', - optional: true, - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'ObjectTypeAnnotation', - properties: [ - { - optional: false, - name: 'key', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - { - optional: false, - name: 'value', - typeAnnotation: { - type: 'GenericObjectTypeAnnotation', - }, - }, - ], - }, - }, - }, - ], - }, - }, - }, - { - name: 'getArrays', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'VoidTypeAnnotation', - }, - params: [ - { - optional: false, - name: 'options', - typeAnnotation: { - type: 'ObjectTypeAnnotation', - properties: [ - { - optional: false, - name: 'arrayOfNumbers', - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'NumberTypeAnnotation', - }, - }, - }, - { - optional: true, - name: 'optionalArrayOfNumbers', - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'NumberTypeAnnotation', - }, - }, - }, - { - optional: false, - name: 'arrayOfStrings', - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'StringTypeAnnotation', - }, - }, - }, - { - optional: true, - name: 'optionalArrayOfStrings', - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'StringTypeAnnotation', - }, - }, - }, - { - optional: false, - name: 'arrayOfObjects', - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'ObjectTypeAnnotation', - properties: [ - { - optional: false, - name: 'numberProperty', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - ], - }, - }, - }, - ], - }, - }, - ], - }, - }, - { - name: 'getNullableObject', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'NullableTypeAnnotation', - typeAnnotation: { - type: 'ObjectTypeAnnotation', - properties: [], - }, - }, - params: [], - }, - }, - { - name: 'getNullableGenericObject', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'NullableTypeAnnotation', - typeAnnotation: { - type: 'GenericObjectTypeAnnotation', - }, - }, - params: [], - }, - }, - { - name: 'getNullableArray', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'NullableTypeAnnotation', - typeAnnotation: { - type: 'ArrayTypeAnnotation', - }, - }, - params: [], - }, - }, - ], - }, - moduleNames: ['SampleTurboModule'], - }, - }, -}; - -const NATIVE_MODULES_WITH_TYPE_ALIASES: SchemaType = { - modules: { - AliasTurboModule: { - type: 'NativeModule', - aliases: { - Options: { - type: 'ObjectTypeAnnotation', - properties: [ - { - optional: false, - name: 'offset', - typeAnnotation: { - type: 'ObjectTypeAnnotation', - properties: [ - { - optional: false, - name: 'x', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - { - optional: false, - name: 'y', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - ], - }, - }, - { - optional: false, - name: 'size', - typeAnnotation: { - type: 'ObjectTypeAnnotation', - properties: [ - { - optional: false, - name: 'width', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - { - optional: false, - name: 'height', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - ], - }, - }, - { - optional: true, - name: 'displaySize', - typeAnnotation: { - type: 'ObjectTypeAnnotation', - properties: [ - { - optional: false, - name: 'width', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - { - optional: false, - name: 'height', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - ], - }, - }, - { - optional: true, - name: 'resizeMode', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - { - optional: true, - name: 'allowExternalStorage', - typeAnnotation: { - type: 'BooleanTypeAnnotation', - }, - }, - ], - }, - }, - spec: { - properties: [ - { - name: 'getConstants', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'ObjectTypeAnnotation', - properties: [], - }, - params: [], - }, - }, - { - name: 'cropImage', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'VoidTypeAnnotation', - }, - params: [ - { - optional: false, - name: 'cropData', - typeAnnotation: { - type: 'TypeAliasTypeAnnotation', - name: 'Options', - }, - }, - ], - }, - }, - ], - }, - moduleNames: ['AliasTurboModule'], - }, - }, -}; - -const REAL_MODULE_EXAMPLE: SchemaType = { - modules: { - NativeCameraRollManager: { - type: 'NativeModule', - aliases: { - PhotoIdentifierImage: { - type: 'ObjectTypeAnnotation', - properties: [ - { - optional: false, - name: 'uri', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - { - optional: false, - name: 'playableDuration', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - { - optional: false, - name: 'width', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - { - optional: false, - name: 'height', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - { - optional: true, - name: 'isStored', - typeAnnotation: { - type: 'BooleanTypeAnnotation', - }, - }, - { - optional: false, - name: 'filename', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - ], - }, - PhotoIdentifier: { - type: 'ObjectTypeAnnotation', - properties: [ - { - optional: false, - name: 'node', - typeAnnotation: { - type: 'ObjectTypeAnnotation', - properties: [ - { - optional: false, - name: 'image', - typeAnnotation: { - type: 'TypeAliasTypeAnnotation', - name: 'PhotoIdentifierImage', - }, - }, - { - optional: false, - name: 'type', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - { - optional: false, - name: 'group_name', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - { - optional: false, - name: 'timestamp', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - { - optional: false, - name: 'location', - typeAnnotation: { - type: 'ObjectTypeAnnotation', - properties: [ - { - optional: false, - name: 'longitude', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - { - optional: false, - name: 'latitude', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - { - optional: true, - name: 'altitude', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - { - optional: true, - name: 'heading', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - { - optional: true, - name: 'speed', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - ], - }, - }, - ], - }, - }, - ], - }, - PhotoIdentifiersPage: { - type: 'ObjectTypeAnnotation', - properties: [ - { - optional: false, - name: 'edges', - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'TypeAliasTypeAnnotation', - name: 'PhotoIdentifier', - }, - }, - }, - { - optional: false, - name: 'page_info', - typeAnnotation: { - type: 'ObjectTypeAnnotation', - properties: [ - { - optional: false, - name: 'has_next_page', - typeAnnotation: { - type: 'BooleanTypeAnnotation', - }, - }, - { - optional: true, - name: 'start_cursor', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - { - optional: true, - name: 'end_cursor', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - ], - }, - }, - ], - }, - GetPhotosParams: { - type: 'ObjectTypeAnnotation', - properties: [ - { - optional: false, - name: 'first', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - { - optional: true, - name: 'after', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - { - optional: true, - name: 'groupName', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - { - optional: true, - name: 'groupTypes', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - { - optional: true, - name: 'assetType', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - { - optional: true, - name: 'maxSize', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - { - optional: true, - name: 'mimeTypes', - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'StringTypeAnnotation', - }, - }, - }, - ], - }, - }, - spec: { - properties: [ - { - name: 'getConstants', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'ObjectTypeAnnotation', - properties: [], - }, - params: [], - }, - }, - { - name: 'getPhotos', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'PromiseTypeAnnotation', - }, - params: [ - { - optional: false, - name: 'params', - typeAnnotation: { - type: 'TypeAliasTypeAnnotation', - name: 'GetPhotosParams', - }, - }, - ], - }, - }, - { - name: 'saveToCameraRoll', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'PromiseTypeAnnotation', - }, - params: [ - { - optional: false, - name: 'uri', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - { - optional: false, - name: 'type', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - ], - }, - }, - { - name: 'deletePhotos', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'PromiseTypeAnnotation', - }, - params: [ - { - name: 'assets', - optional: false, - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'StringTypeAnnotation', - }, - }, - }, - ], - }, - }, - ], - }, - moduleNames: ['CameraRollManager'], - }, - NativeExceptionsManager: { - type: 'NativeModule', - aliases: { - StackFrame: { - properties: [ - { - optional: true, - name: 'column', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - { - optional: false, - name: 'file', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - { - optional: true, - name: 'lineNumber', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - { - optional: false, - name: 'methodName', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - { - optional: true, - name: 'collapse', - typeAnnotation: { - type: 'BooleanTypeAnnotation', - }, - }, - ], - type: 'ObjectTypeAnnotation', - }, - ExceptionData: { - properties: [ - { - optional: false, - name: 'message', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - { - optional: false, - name: 'originalMessage', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - { - optional: false, - name: 'name', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - { - optional: false, - name: 'componentStack', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - { - optional: false, - name: 'stack', - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'TypeAliasTypeAnnotation', - name: 'StackFrame', - }, - }, - }, - { - optional: false, - name: 'id', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - { - optional: false, - name: 'isFatal', - typeAnnotation: { - type: 'BooleanTypeAnnotation', - }, - }, - { - optional: true, - name: 'extraData', - typeAnnotation: { - type: 'GenericObjectTypeAnnotation', - }, - }, - ], - type: 'ObjectTypeAnnotation', - }, - }, - spec: { - properties: [ - { - name: 'reportFatalException', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'VoidTypeAnnotation', - }, - params: [ - { - optional: false, - name: 'message', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - { - name: 'stack', - optional: false, - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'TypeAliasTypeAnnotation', - name: 'StackFrame', - }, - }, - }, - { - optional: false, - name: 'exceptionId', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - ], - }, - }, - { - name: 'reportSoftException', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'VoidTypeAnnotation', - }, - params: [ - { - optional: false, - name: 'message', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - { - name: 'stack', - optional: false, - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'TypeAliasTypeAnnotation', - name: 'StackFrame', - }, - }, - }, - { - optional: false, - name: 'exceptionId', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - ], - }, - }, - { - name: 'reportException', - optional: true, - typeAnnotation: { - type: 'NullableTypeAnnotation', - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'VoidTypeAnnotation', - }, - params: [ - { - optional: false, - name: 'data', - typeAnnotation: { - type: 'TypeAliasTypeAnnotation', - name: 'ExceptionData', - }, - }, - ], - }, - }, - }, - { - name: 'updateExceptionMessage', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'VoidTypeAnnotation', - }, - params: [ - { - optional: false, - name: 'message', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - { - name: 'stack', - optional: false, - typeAnnotation: { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'TypeAliasTypeAnnotation', - name: 'StackFrame', - }, - }, - }, - { - optional: false, - name: 'exceptionId', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - ], - }, - }, - { - name: 'dismissRedbox', - optional: true, - typeAnnotation: { - type: 'NullableTypeAnnotation', - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'VoidTypeAnnotation', - }, - params: [], - }, - }, - }, - ], - }, - moduleNames: ['ExceptionsManager'], - }, - }, -}; - -const CXX_ONLY_NATIVE_MODULES: SchemaType = { - modules: { - NativeSampleTurboModule: { - type: 'NativeModule', - aliases: { - ObjectAlias: { - type: 'ObjectTypeAnnotation', - properties: [ - { - name: 'x', - optional: false, - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - ], - }, - }, - spec: { - properties: [ - { - name: 'getMixed', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'MixedTypeAnnotation', - }, - params: [ - { - name: 'arg', - optional: false, - typeAnnotation: { - type: 'MixedTypeAnnotation', - }, - }, - ], - }, - }, - { - name: 'getNullableNumberFromNullableAlias', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'NullableTypeAnnotation', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }, - params: [ - { - name: 'a', - optional: false, - typeAnnotation: { - type: 'NullableTypeAnnotation', - typeAnnotation: { - type: 'TypeAliasTypeAnnotation', - name: 'ObjectAlias', - }, - }, - }, - ], - }, - }, - { - name: 'getEnums', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'StringTypeAnnotation', - }, - params: [ - { - name: 'enumInt', - optional: false, - typeAnnotation: { - type: 'EnumDeclaration', - memberType: 'NumberTypeAnnotation', - }, - }, - { - name: 'enumFloat', - optional: false, - typeAnnotation: { - type: 'EnumDeclaration', - memberType: 'NumberTypeAnnotation', - }, - }, - { - name: 'enumString', - optional: false, - typeAnnotation: { - type: 'EnumDeclaration', - memberType: 'StringTypeAnnotation', - }, - }, - ], - }, - }, - { - name: 'getUnion', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'UnionTypeAnnotation', - memberType: 'ObjectTypeAnnotation', - }, - params: [ - { - name: 'chooseInt', - optional: false, - typeAnnotation: { - type: 'UnionTypeAnnotation', - memberType: 'NumberTypeAnnotation', - }, - }, - { - name: 'chooseFloat', - optional: false, - typeAnnotation: { - type: 'UnionTypeAnnotation', - memberType: 'NumberTypeAnnotation', - }, - }, - { - name: 'chooseObject', - optional: false, - typeAnnotation: { - type: 'UnionTypeAnnotation', - memberType: 'ObjectTypeAnnotation', - }, - }, - { - name: 'chooseString', - optional: false, - typeAnnotation: { - type: 'UnionTypeAnnotation', - memberType: 'StringTypeAnnotation', - }, - }, - ], - }, - }, - ], - }, - moduleNames: ['SampleTurboModuleCxx'], - excludedPlatforms: ['iOS', 'android'], - }, - }, -}; - -const SAMPLE_WITH_UPPERCASE_NAME: SchemaType = { - modules: { - NativeSampleTurboModule: { - type: 'NativeModule', - aliases: {}, - spec: { - properties: [], - }, - moduleNames: ['SampleTurboModule'], - }, - }, -}; - -module.exports = { - complex_objects: COMPLEX_OBJECTS, - two_modules_different_files: TWO_MODULES_DIFFERENT_FILES, - empty_native_modules: EMPTY_NATIVE_MODULES, - simple_native_modules: SIMPLE_NATIVE_MODULES, - native_modules_with_type_aliases: NATIVE_MODULES_WITH_TYPE_ALIASES, - real_module_example: REAL_MODULE_EXAMPLE, - cxx_only_native_modules: CXX_ONLY_NATIVE_MODULES, - SampleWithUppercaseName: SAMPLE_WITH_UPPERCASE_NAME, -}; diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/GenerateModuleCpp-test.js b/packages/react-native-codegen/src/generators/modules/__tests__/GenerateModuleCpp-test.js deleted file mode 100644 index 993cf01ef1b4..000000000000 --- a/packages/react-native-codegen/src/generators/modules/__tests__/GenerateModuleCpp-test.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const fixtures = require('../__test_fixtures__/fixtures.js'); -const generator = require('../GenerateModuleCpp.js'); - -describe('GenerateModuleCpp', () => { - Object.keys(fixtures) - .sort() - .forEach(fixtureName => { - const fixture = fixtures[fixtureName]; - - it(`can generate fixture ${fixtureName}`, () => { - expect( - generator.generate( - fixtureName, - fixture, - 'com.facebook.fbreact.specs', - ), - ).toMatchSnapshot(); - }); - }); -}); diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/GenerateModuleH-test.js b/packages/react-native-codegen/src/generators/modules/__tests__/GenerateModuleH-test.js deleted file mode 100644 index 2d7e3e49f8c3..000000000000 --- a/packages/react-native-codegen/src/generators/modules/__tests__/GenerateModuleH-test.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const fixtures = require('../__test_fixtures__/fixtures.js'); -const generator = require('../GenerateModuleH.js'); - -describe('GenerateModuleH', () => { - Object.keys(fixtures) - .sort() - .forEach(fixtureName => { - const fixture = fixtures[fixtureName]; - - it(`can generate fixture ${fixtureName}`, () => { - expect( - generator.generate( - fixtureName, - fixture, - 'com.facebook.fbreact.specs', - ), - ).toMatchSnapshot(); - }); - }); -}); diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/GenerateModuleHObjCpp-test.js b/packages/react-native-codegen/src/generators/modules/__tests__/GenerateModuleHObjCpp-test.js deleted file mode 100644 index 6476daa01c41..000000000000 --- a/packages/react-native-codegen/src/generators/modules/__tests__/GenerateModuleHObjCpp-test.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const fixtures = require('../__test_fixtures__/fixtures.js'); -const generator = require('../GenerateModuleObjCpp'); - -describe('GenerateModuleHObjCpp', () => { - Object.keys(fixtures) - .sort() - .forEach(fixtureName => { - const fixture = fixtures[fixtureName]; - - it(`can generate fixture ${fixtureName}`, () => { - const output = generator.generate( - fixtureName, - fixture, - 'com.facebook.fbreact.specs', - false, - ); - expect( - new Map([[`${fixtureName}.h`, output.get(`${fixtureName}.h`)]]), - ).toMatchSnapshot(); - }); - }); -}); diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/GenerateModuleJavaSpec-test.js b/packages/react-native-codegen/src/generators/modules/__tests__/GenerateModuleJavaSpec-test.js deleted file mode 100644 index b3ea40c76e02..000000000000 --- a/packages/react-native-codegen/src/generators/modules/__tests__/GenerateModuleJavaSpec-test.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const fixtures = require('../__test_fixtures__/fixtures.js'); -const generator = require('../GenerateModuleJavaSpec.js'); - -describe('GenerateModuleJavaSpec', () => { - Object.keys(fixtures) - .sort() - .forEach(fixtureName => { - const fixture = fixtures[fixtureName]; - - it(`can generate fixture ${fixtureName}`, () => { - expect( - generator.generate( - fixtureName, - fixture, - 'com.facebook.fbreact.specs', - ), - ).toMatchSnapshot(); - }); - }); -}); diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/GenerateModuleJniCpp-test.js b/packages/react-native-codegen/src/generators/modules/__tests__/GenerateModuleJniCpp-test.js deleted file mode 100644 index dc9565119937..000000000000 --- a/packages/react-native-codegen/src/generators/modules/__tests__/GenerateModuleJniCpp-test.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const fixtures = require('../__test_fixtures__/fixtures.js'); -const generator = require('../GenerateModuleJniCpp.js'); - -describe('GenerateModuleJniCpp', () => { - Object.keys(fixtures) - .sort() - .forEach(fixtureName => { - const fixture = fixtures[fixtureName]; - - it(`can generate fixture ${fixtureName}`, () => { - expect( - generator.generate( - fixtureName, - fixture, - 'com.facebook.fbreact.specs', - ), - ).toMatchSnapshot(); - }); - }); -}); diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/GenerateModuleJniH-test.js b/packages/react-native-codegen/src/generators/modules/__tests__/GenerateModuleJniH-test.js deleted file mode 100644 index 0ce2e0ef1460..000000000000 --- a/packages/react-native-codegen/src/generators/modules/__tests__/GenerateModuleJniH-test.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const fixtures = require('../__test_fixtures__/fixtures.js'); -const generator = require('../GenerateModuleJniH.js'); - -describe('GenerateModuleJniH', () => { - Object.keys(fixtures) - .sort() - .forEach(fixtureName => { - const fixture = fixtures[fixtureName]; - - it(`can generate fixture ${fixtureName}`, () => { - expect( - generator.generate( - fixtureName, - fixture, - 'com.facebook.fbreact.specs', - ), - ).toMatchSnapshot(); - }); - }); -}); diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/GenerateModuleMm-test.js b/packages/react-native-codegen/src/generators/modules/__tests__/GenerateModuleMm-test.js deleted file mode 100644 index 11fd335a9b44..000000000000 --- a/packages/react-native-codegen/src/generators/modules/__tests__/GenerateModuleMm-test.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const fixtures = require('../__test_fixtures__/fixtures.js'); -const generator = require('../GenerateModuleObjCpp'); - -describe('GenerateModuleMm', () => { - Object.keys(fixtures) - .sort() - .forEach(fixtureName => { - const fixture = fixtures[fixtureName]; - - it(`can generate fixture ${fixtureName}`, () => { - const output = generator.generate( - fixtureName, - fixture, - 'com.facebook.fbreact.specs', - false, - ); - expect( - new Map([ - [ - `${fixtureName}-generated.mm`, - output.get(`${fixtureName}-generated.mm`), - ], - ]), - ).toMatchSnapshot(); - }); - }); -}); diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleCpp-test.js.snap b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleCpp-test.js.snap deleted file mode 100644 index 4a22ab252d74..000000000000 --- a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleCpp-test.js.snap +++ /dev/null @@ -1,406 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GenerateModuleCpp can generate fixture SampleWithUppercaseName 1`] = ` -Map { - "SampleWithUppercaseNameJSI-generated.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleH.js - */ - -#include \\"SampleWithUppercaseNameJSI.h\\" - -namespace facebook { -namespace react { - - - -NativeSampleTurboModuleCxxSpecJSI::NativeSampleTurboModuleCxxSpecJSI(std::shared_ptr jsInvoker) - : TurboModule(\\"SampleTurboModule\\", jsInvoker) { - -} - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateModuleCpp can generate fixture complex_objects 1`] = ` -Map { - "complex_objectsJSI-generated.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleH.js - */ - -#include \\"complex_objectsJSI.h\\" - -namespace facebook { -namespace react { - -static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_difficult(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - return static_cast(&turboModule)->difficult(rt, args[0].asObject(rt)); -} -static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_optionals(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - static_cast(&turboModule)->optionals(rt, args[0].asObject(rt)); - return jsi::Value::undefined(); -} -static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_optionalMethod(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - static_cast(&turboModule)->optionalMethod(rt, args[0].asObject(rt), args[1].asObject(rt).asFunction(rt), count < 2 || args[2].isNull() || args[2].isUndefined() ? std::nullopt : std::make_optional(args[2].asObject(rt).asArray(rt))); - return jsi::Value::undefined(); -} -static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getArrays(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - static_cast(&turboModule)->getArrays(rt, args[0].asObject(rt)); - return jsi::Value::undefined(); -} -static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getNullableObject(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - auto result = static_cast(&turboModule)->getNullableObject(rt); - return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); -} -static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getNullableGenericObject(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - auto result = static_cast(&turboModule)->getNullableGenericObject(rt); - return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); -} -static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getNullableArray(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - auto result = static_cast(&turboModule)->getNullableArray(rt); - return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); -} - -NativeSampleTurboModuleCxxSpecJSI::NativeSampleTurboModuleCxxSpecJSI(std::shared_ptr jsInvoker) - : TurboModule(\\"SampleTurboModule\\", jsInvoker) { - methodMap_[\\"difficult\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_difficult}; - methodMap_[\\"optionals\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_optionals}; - methodMap_[\\"optionalMethod\\"] = MethodMetadata {3, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_optionalMethod}; - methodMap_[\\"getArrays\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getArrays}; - methodMap_[\\"getNullableObject\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getNullableObject}; - methodMap_[\\"getNullableGenericObject\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getNullableGenericObject}; - methodMap_[\\"getNullableArray\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getNullableArray}; -} - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateModuleCpp can generate fixture cxx_only_native_modules 1`] = ` -Map { - "cxx_only_native_modulesJSI-generated.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleH.js - */ - -#include \\"cxx_only_native_modulesJSI.h\\" - -namespace facebook { -namespace react { - -static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getMixed(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - return static_cast(&turboModule)->getMixed(rt, jsi::Value(rt, args[0])); -} -static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getNullableNumberFromNullableAlias(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - auto result = static_cast(&turboModule)->getNullableNumberFromNullableAlias(rt, args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt))); - return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); -} -static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getEnums(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - return static_cast(&turboModule)->getEnums(rt, args[0].asNumber(), args[1].asNumber(), args[2].asString(rt)); -} -static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getUnion(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - return static_cast(&turboModule)->getUnion(rt, args[0].asNumber(), args[1].asNumber(), args[2].asObject(rt), args[3].asString(rt)); -} - -NativeSampleTurboModuleCxxSpecJSI::NativeSampleTurboModuleCxxSpecJSI(std::shared_ptr jsInvoker) - : TurboModule(\\"SampleTurboModuleCxx\\", jsInvoker) { - methodMap_[\\"getMixed\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getMixed}; - methodMap_[\\"getNullableNumberFromNullableAlias\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getNullableNumberFromNullableAlias}; - methodMap_[\\"getEnums\\"] = MethodMetadata {3, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getEnums}; - methodMap_[\\"getUnion\\"] = MethodMetadata {4, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getUnion}; -} - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateModuleCpp can generate fixture empty_native_modules 1`] = ` -Map { - "empty_native_modulesJSI-generated.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleH.js - */ - -#include \\"empty_native_modulesJSI.h\\" - -namespace facebook { -namespace react { - - - -NativeSampleTurboModuleCxxSpecJSI::NativeSampleTurboModuleCxxSpecJSI(std::shared_ptr jsInvoker) - : TurboModule(\\"SampleTurboModule\\", jsInvoker) { - -} - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateModuleCpp can generate fixture native_modules_with_type_aliases 1`] = ` -Map { - "native_modules_with_type_aliasesJSI-generated.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleH.js - */ - -#include \\"native_modules_with_type_aliasesJSI.h\\" - -namespace facebook { -namespace react { - -static jsi::Value __hostFunction_AliasTurboModuleCxxSpecJSI_getConstants(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - return static_cast(&turboModule)->getConstants(rt); -} -static jsi::Value __hostFunction_AliasTurboModuleCxxSpecJSI_cropImage(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - static_cast(&turboModule)->cropImage(rt, args[0].asObject(rt)); - return jsi::Value::undefined(); -} - -AliasTurboModuleCxxSpecJSI::AliasTurboModuleCxxSpecJSI(std::shared_ptr jsInvoker) - : TurboModule(\\"AliasTurboModule\\", jsInvoker) { - methodMap_[\\"getConstants\\"] = MethodMetadata {0, __hostFunction_AliasTurboModuleCxxSpecJSI_getConstants}; - methodMap_[\\"cropImage\\"] = MethodMetadata {1, __hostFunction_AliasTurboModuleCxxSpecJSI_cropImage}; -} - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateModuleCpp can generate fixture real_module_example 1`] = ` -Map { - "real_module_exampleJSI-generated.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleH.js - */ - -#include \\"real_module_exampleJSI.h\\" - -namespace facebook { -namespace react { - -static jsi::Value __hostFunction_NativeCameraRollManagerCxxSpecJSI_getConstants(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - return static_cast(&turboModule)->getConstants(rt); -} -static jsi::Value __hostFunction_NativeCameraRollManagerCxxSpecJSI_getPhotos(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - return static_cast(&turboModule)->getPhotos(rt, args[0].asObject(rt)); -} -static jsi::Value __hostFunction_NativeCameraRollManagerCxxSpecJSI_saveToCameraRoll(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - return static_cast(&turboModule)->saveToCameraRoll(rt, args[0].asString(rt), args[1].asString(rt)); -} -static jsi::Value __hostFunction_NativeCameraRollManagerCxxSpecJSI_deletePhotos(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - return static_cast(&turboModule)->deletePhotos(rt, args[0].asObject(rt).asArray(rt)); -} - -NativeCameraRollManagerCxxSpecJSI::NativeCameraRollManagerCxxSpecJSI(std::shared_ptr jsInvoker) - : TurboModule(\\"CameraRollManager\\", jsInvoker) { - methodMap_[\\"getConstants\\"] = MethodMetadata {0, __hostFunction_NativeCameraRollManagerCxxSpecJSI_getConstants}; - methodMap_[\\"getPhotos\\"] = MethodMetadata {1, __hostFunction_NativeCameraRollManagerCxxSpecJSI_getPhotos}; - methodMap_[\\"saveToCameraRoll\\"] = MethodMetadata {2, __hostFunction_NativeCameraRollManagerCxxSpecJSI_saveToCameraRoll}; - methodMap_[\\"deletePhotos\\"] = MethodMetadata {1, __hostFunction_NativeCameraRollManagerCxxSpecJSI_deletePhotos}; -} -static jsi::Value __hostFunction_NativeExceptionsManagerCxxSpecJSI_reportFatalException(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - static_cast(&turboModule)->reportFatalException(rt, args[0].asString(rt), args[1].asObject(rt).asArray(rt), args[2].asNumber()); - return jsi::Value::undefined(); -} -static jsi::Value __hostFunction_NativeExceptionsManagerCxxSpecJSI_reportSoftException(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - static_cast(&turboModule)->reportSoftException(rt, args[0].asString(rt), args[1].asObject(rt).asArray(rt), args[2].asNumber()); - return jsi::Value::undefined(); -} -static jsi::Value __hostFunction_NativeExceptionsManagerCxxSpecJSI_reportException(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - static_cast(&turboModule)->reportException(rt, args[0].asObject(rt)); - return jsi::Value::undefined(); -} -static jsi::Value __hostFunction_NativeExceptionsManagerCxxSpecJSI_updateExceptionMessage(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - static_cast(&turboModule)->updateExceptionMessage(rt, args[0].asString(rt), args[1].asObject(rt).asArray(rt), args[2].asNumber()); - return jsi::Value::undefined(); -} -static jsi::Value __hostFunction_NativeExceptionsManagerCxxSpecJSI_dismissRedbox(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - static_cast(&turboModule)->dismissRedbox(rt); - return jsi::Value::undefined(); -} - -NativeExceptionsManagerCxxSpecJSI::NativeExceptionsManagerCxxSpecJSI(std::shared_ptr jsInvoker) - : TurboModule(\\"ExceptionsManager\\", jsInvoker) { - methodMap_[\\"reportFatalException\\"] = MethodMetadata {3, __hostFunction_NativeExceptionsManagerCxxSpecJSI_reportFatalException}; - methodMap_[\\"reportSoftException\\"] = MethodMetadata {3, __hostFunction_NativeExceptionsManagerCxxSpecJSI_reportSoftException}; - methodMap_[\\"reportException\\"] = MethodMetadata {1, __hostFunction_NativeExceptionsManagerCxxSpecJSI_reportException}; - methodMap_[\\"updateExceptionMessage\\"] = MethodMetadata {3, __hostFunction_NativeExceptionsManagerCxxSpecJSI_updateExceptionMessage}; - methodMap_[\\"dismissRedbox\\"] = MethodMetadata {0, __hostFunction_NativeExceptionsManagerCxxSpecJSI_dismissRedbox}; -} - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateModuleCpp can generate fixture simple_native_modules 1`] = ` -Map { - "simple_native_modulesJSI-generated.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleH.js - */ - -#include \\"simple_native_modulesJSI.h\\" - -namespace facebook { -namespace react { - -static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getConstants(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - return static_cast(&turboModule)->getConstants(rt); -} -static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_voidFunc(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - static_cast(&turboModule)->voidFunc(rt); - return jsi::Value::undefined(); -} -static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getBool(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - return static_cast(&turboModule)->getBool(rt, args[0].asBool()); -} -static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getNumber(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - return static_cast(&turboModule)->getNumber(rt, args[0].asNumber()); -} -static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getString(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - return static_cast(&turboModule)->getString(rt, args[0].asString(rt)); -} -static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getArray(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - return static_cast(&turboModule)->getArray(rt, args[0].asObject(rt).asArray(rt)); -} -static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getObject(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - return static_cast(&turboModule)->getObject(rt, args[0].asObject(rt)); -} -static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getRootTag(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - return static_cast(&turboModule)->getRootTag(rt, args[0].getNumber()); -} -static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValue(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - return static_cast(&turboModule)->getValue(rt, args[0].asNumber(), args[1].asString(rt), args[2].asObject(rt)); -} -static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValueWithCallback(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - static_cast(&turboModule)->getValueWithCallback(rt, args[0].asObject(rt).asFunction(rt)); - return jsi::Value::undefined(); -} -static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValueWithPromise(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - return static_cast(&turboModule)->getValueWithPromise(rt, args[0].asBool()); -} -static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValueWithOptionalArg(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - return static_cast(&turboModule)->getValueWithOptionalArg(rt, count < 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt))); -} -static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getEnums(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - return static_cast(&turboModule)->getEnums(rt, args[0].asNumber(), args[1].asNumber(), args[2].asString(rt)); -} - -NativeSampleTurboModuleCxxSpecJSI::NativeSampleTurboModuleCxxSpecJSI(std::shared_ptr jsInvoker) - : TurboModule(\\"SampleTurboModule\\", jsInvoker) { - methodMap_[\\"getConstants\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getConstants}; - methodMap_[\\"voidFunc\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_voidFunc}; - methodMap_[\\"getBool\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getBool}; - methodMap_[\\"getNumber\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getNumber}; - methodMap_[\\"getString\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getString}; - methodMap_[\\"getArray\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getArray}; - methodMap_[\\"getObject\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getObject}; - methodMap_[\\"getRootTag\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getRootTag}; - methodMap_[\\"getValue\\"] = MethodMetadata {3, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValue}; - methodMap_[\\"getValueWithCallback\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValueWithCallback}; - methodMap_[\\"getValueWithPromise\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValueWithPromise}; - methodMap_[\\"getValueWithOptionalArg\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValueWithOptionalArg}; - methodMap_[\\"getEnums\\"] = MethodMetadata {3, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getEnums}; -} - - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateModuleCpp can generate fixture two_modules_different_files 1`] = ` -Map { - "two_modules_different_filesJSI-generated.cpp" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleH.js - */ - -#include \\"two_modules_different_filesJSI.h\\" - -namespace facebook { -namespace react { - -static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_voidFunc(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - static_cast(&turboModule)->voidFunc(rt); - return jsi::Value::undefined(); -} - -NativeSampleTurboModuleCxxSpecJSI::NativeSampleTurboModuleCxxSpecJSI(std::shared_ptr jsInvoker) - : TurboModule(\\"SampleTurboModule\\", jsInvoker) { - methodMap_[\\"voidFunc\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_voidFunc}; -} -static jsi::Value __hostFunction_NativeSampleTurboModule2CxxSpecJSI_getConstants(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - return static_cast(&turboModule)->getConstants(rt); -} -static jsi::Value __hostFunction_NativeSampleTurboModule2CxxSpecJSI_voidFunc(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - static_cast(&turboModule)->voidFunc(rt); - return jsi::Value::undefined(); -} - -NativeSampleTurboModule2CxxSpecJSI::NativeSampleTurboModule2CxxSpecJSI(std::shared_ptr jsInvoker) - : TurboModule(\\"SampleTurboModule2\\", jsInvoker) { - methodMap_[\\"getConstants\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModule2CxxSpecJSI_getConstants}; - methodMap_[\\"voidFunc\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModule2CxxSpecJSI_voidFunc}; -} - - -} // namespace react -} // namespace facebook -", -} -`; diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleH-test.js.snap b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleH-test.js.snap deleted file mode 100644 index 679072d878eb..000000000000 --- a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleH-test.js.snap +++ /dev/null @@ -1,1240 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GenerateModuleH can generate fixture SampleWithUppercaseName 1`] = ` -Map { - "SampleWithUppercaseNameJSI.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT NativeSampleTurboModuleCxxSpecJSI : public TurboModule { -protected: - NativeSampleTurboModuleCxxSpecJSI(std::shared_ptr jsInvoker); - -public: - - -}; - -template -class JSI_EXPORT NativeSampleTurboModuleCxxSpec : public TurboModule { -public: - jsi::Value get(jsi::Runtime &rt, const jsi::PropNameID &propName) override { - return delegate_.get(rt, propName); - } - -protected: - NativeSampleTurboModuleCxxSpec(std::shared_ptr jsInvoker) - : TurboModule(\\"SampleTurboModule\\", jsInvoker), - delegate_(static_cast(this), jsInvoker) {} - -private: - class Delegate : public NativeSampleTurboModuleCxxSpecJSI { - public: - Delegate(T *instance, std::shared_ptr jsInvoker) : - NativeSampleTurboModuleCxxSpecJSI(std::move(jsInvoker)), instance_(instance) {} - - - - private: - T *instance_; - }; - - Delegate delegate_; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateModuleH can generate fixture complex_objects 1`] = ` -Map { - "complex_objectsJSI.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT NativeSampleTurboModuleCxxSpecJSI : public TurboModule { -protected: - NativeSampleTurboModuleCxxSpecJSI(std::shared_ptr jsInvoker); - -public: - virtual jsi::Object difficult(jsi::Runtime &rt, jsi::Object A) = 0; - virtual void optionals(jsi::Runtime &rt, jsi::Object A) = 0; - virtual void optionalMethod(jsi::Runtime &rt, jsi::Object options, jsi::Function callback, std::optional extras) = 0; - virtual void getArrays(jsi::Runtime &rt, jsi::Object options) = 0; - virtual std::optional getNullableObject(jsi::Runtime &rt) = 0; - virtual std::optional getNullableGenericObject(jsi::Runtime &rt) = 0; - virtual std::optional getNullableArray(jsi::Runtime &rt) = 0; - -}; - -template -class JSI_EXPORT NativeSampleTurboModuleCxxSpec : public TurboModule { -public: - jsi::Value get(jsi::Runtime &rt, const jsi::PropNameID &propName) override { - return delegate_.get(rt, propName); - } - -protected: - NativeSampleTurboModuleCxxSpec(std::shared_ptr jsInvoker) - : TurboModule(\\"SampleTurboModule\\", jsInvoker), - delegate_(static_cast(this), jsInvoker) {} - -private: - class Delegate : public NativeSampleTurboModuleCxxSpecJSI { - public: - Delegate(T *instance, std::shared_ptr jsInvoker) : - NativeSampleTurboModuleCxxSpecJSI(std::move(jsInvoker)), instance_(instance) {} - - jsi::Object difficult(jsi::Runtime &rt, jsi::Object A) override { - static_assert( - bridging::getParameterCount(&T::difficult) == 2, - \\"Expected difficult(...) to have 2 parameters\\"); - - return bridging::callFromJs( - rt, &T::difficult, jsInvoker_, instance_, std::move(A)); - } - void optionals(jsi::Runtime &rt, jsi::Object A) override { - static_assert( - bridging::getParameterCount(&T::optionals) == 2, - \\"Expected optionals(...) to have 2 parameters\\"); - - return bridging::callFromJs( - rt, &T::optionals, jsInvoker_, instance_, std::move(A)); - } - void optionalMethod(jsi::Runtime &rt, jsi::Object options, jsi::Function callback, std::optional extras) override { - static_assert( - bridging::getParameterCount(&T::optionalMethod) == 4, - \\"Expected optionalMethod(...) to have 4 parameters\\"); - - return bridging::callFromJs( - rt, &T::optionalMethod, jsInvoker_, instance_, std::move(options), std::move(callback), std::move(extras)); - } - void getArrays(jsi::Runtime &rt, jsi::Object options) override { - static_assert( - bridging::getParameterCount(&T::getArrays) == 2, - \\"Expected getArrays(...) to have 2 parameters\\"); - - return bridging::callFromJs( - rt, &T::getArrays, jsInvoker_, instance_, std::move(options)); - } - std::optional getNullableObject(jsi::Runtime &rt) override { - static_assert( - bridging::getParameterCount(&T::getNullableObject) == 1, - \\"Expected getNullableObject(...) to have 1 parameters\\"); - - return bridging::callFromJs>( - rt, &T::getNullableObject, jsInvoker_, instance_); - } - std::optional getNullableGenericObject(jsi::Runtime &rt) override { - static_assert( - bridging::getParameterCount(&T::getNullableGenericObject) == 1, - \\"Expected getNullableGenericObject(...) to have 1 parameters\\"); - - return bridging::callFromJs>( - rt, &T::getNullableGenericObject, jsInvoker_, instance_); - } - std::optional getNullableArray(jsi::Runtime &rt) override { - static_assert( - bridging::getParameterCount(&T::getNullableArray) == 1, - \\"Expected getNullableArray(...) to have 1 parameters\\"); - - return bridging::callFromJs>( - rt, &T::getNullableArray, jsInvoker_, instance_); - } - - private: - T *instance_; - }; - - Delegate delegate_; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateModuleH can generate fixture cxx_only_native_modules 1`] = ` -Map { - "cxx_only_native_modulesJSI.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -#pragma mark - SampleTurboModuleCxxBaseObjectAlias - -template -struct SampleTurboModuleCxxBaseObjectAlias { - P0 x; - bool operator==(const SampleTurboModuleCxxBaseObjectAlias &other) const { - return x == other.x; - } -}; - -template -struct SampleTurboModuleCxxBaseObjectAliasBridging { - static SampleTurboModuleCxxBaseObjectAlias fromJs( - jsi::Runtime &rt, - const jsi::Object &value, - const std::shared_ptr &jsInvoker) { - SampleTurboModuleCxxBaseObjectAlias result{ - bridging::fromJs(rt, value.getProperty(rt, \\"x\\"), jsInvoker)}; - return result; - } - - static jsi::Object toJs( - jsi::Runtime &rt, - const SampleTurboModuleCxxBaseObjectAlias &value) { - auto result = facebook::jsi::Object(rt); - result.setProperty(rt, \\"x\\", bridging::toJs(rt, value.x)); - return result; - } -}; - -class JSI_EXPORT NativeSampleTurboModuleCxxSpecJSI : public TurboModule { -protected: - NativeSampleTurboModuleCxxSpecJSI(std::shared_ptr jsInvoker); - -public: - virtual jsi::Value getMixed(jsi::Runtime &rt, jsi::Value arg) = 0; - virtual std::optional getNullableNumberFromNullableAlias(jsi::Runtime &rt, std::optional a) = 0; - virtual jsi::String getEnums(jsi::Runtime &rt, double enumInt, double enumFloat, jsi::String enumString) = 0; - virtual jsi::Object getUnion(jsi::Runtime &rt, double chooseInt, double chooseFloat, jsi::Object chooseObject, jsi::String chooseString) = 0; - -}; - -template -class JSI_EXPORT NativeSampleTurboModuleCxxSpec : public TurboModule { -public: - jsi::Value get(jsi::Runtime &rt, const jsi::PropNameID &propName) override { - return delegate_.get(rt, propName); - } - -protected: - NativeSampleTurboModuleCxxSpec(std::shared_ptr jsInvoker) - : TurboModule(\\"SampleTurboModuleCxx\\", jsInvoker), - delegate_(static_cast(this), jsInvoker) {} - -private: - class Delegate : public NativeSampleTurboModuleCxxSpecJSI { - public: - Delegate(T *instance, std::shared_ptr jsInvoker) : - NativeSampleTurboModuleCxxSpecJSI(std::move(jsInvoker)), instance_(instance) {} - - jsi::Value getMixed(jsi::Runtime &rt, jsi::Value arg) override { - static_assert( - bridging::getParameterCount(&T::getMixed) == 2, - \\"Expected getMixed(...) to have 2 parameters\\"); - - return bridging::callFromJs( - rt, &T::getMixed, jsInvoker_, instance_, std::move(arg)); - } - std::optional getNullableNumberFromNullableAlias(jsi::Runtime &rt, std::optional a) override { - static_assert( - bridging::getParameterCount(&T::getNullableNumberFromNullableAlias) == 2, - \\"Expected getNullableNumberFromNullableAlias(...) to have 2 parameters\\"); - - return bridging::callFromJs>( - rt, &T::getNullableNumberFromNullableAlias, jsInvoker_, instance_, std::move(a)); - } - jsi::String getEnums(jsi::Runtime &rt, double enumInt, double enumFloat, jsi::String enumString) override { - static_assert( - bridging::getParameterCount(&T::getEnums) == 4, - \\"Expected getEnums(...) to have 4 parameters\\"); - - return bridging::callFromJs( - rt, &T::getEnums, jsInvoker_, instance_, std::move(enumInt), std::move(enumFloat), std::move(enumString)); - } - jsi::Object getUnion(jsi::Runtime &rt, double chooseInt, double chooseFloat, jsi::Object chooseObject, jsi::String chooseString) override { - static_assert( - bridging::getParameterCount(&T::getUnion) == 5, - \\"Expected getUnion(...) to have 5 parameters\\"); - - return bridging::callFromJs( - rt, &T::getUnion, jsInvoker_, instance_, std::move(chooseInt), std::move(chooseFloat), std::move(chooseObject), std::move(chooseString)); - } - - private: - T *instance_; - }; - - Delegate delegate_; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateModuleH can generate fixture empty_native_modules 1`] = ` -Map { - "empty_native_modulesJSI.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT NativeSampleTurboModuleCxxSpecJSI : public TurboModule { -protected: - NativeSampleTurboModuleCxxSpecJSI(std::shared_ptr jsInvoker); - -public: - - -}; - -template -class JSI_EXPORT NativeSampleTurboModuleCxxSpec : public TurboModule { -public: - jsi::Value get(jsi::Runtime &rt, const jsi::PropNameID &propName) override { - return delegate_.get(rt, propName); - } - -protected: - NativeSampleTurboModuleCxxSpec(std::shared_ptr jsInvoker) - : TurboModule(\\"SampleTurboModule\\", jsInvoker), - delegate_(static_cast(this), jsInvoker) {} - -private: - class Delegate : public NativeSampleTurboModuleCxxSpecJSI { - public: - Delegate(T *instance, std::shared_ptr jsInvoker) : - NativeSampleTurboModuleCxxSpecJSI(std::move(jsInvoker)), instance_(instance) {} - - - - private: - T *instance_; - }; - - Delegate delegate_; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateModuleH can generate fixture native_modules_with_type_aliases 1`] = ` -Map { - "native_modules_with_type_aliasesJSI.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -#pragma mark - AliasTurboModuleBaseOptions - -template -struct AliasTurboModuleBaseOptions { - P0 offset; - P1 size; - P2 displaySize; - P3 resizeMode; - P4 allowExternalStorage; - bool operator==(const AliasTurboModuleBaseOptions &other) const { - return offset == other.offset && size == other.size && displaySize == other.displaySize && resizeMode == other.resizeMode && allowExternalStorage == other.allowExternalStorage; - } -}; - -template -struct AliasTurboModuleBaseOptionsBridging { - static AliasTurboModuleBaseOptions fromJs( - jsi::Runtime &rt, - const jsi::Object &value, - const std::shared_ptr &jsInvoker) { - AliasTurboModuleBaseOptions result{ - bridging::fromJs(rt, value.getProperty(rt, \\"offset\\"), jsInvoker), - bridging::fromJs(rt, value.getProperty(rt, \\"size\\"), jsInvoker), - bridging::fromJs(rt, value.getProperty(rt, \\"displaySize\\"), jsInvoker), - bridging::fromJs(rt, value.getProperty(rt, \\"resizeMode\\"), jsInvoker), - bridging::fromJs(rt, value.getProperty(rt, \\"allowExternalStorage\\"), jsInvoker)}; - return result; - } - - static jsi::Object toJs( - jsi::Runtime &rt, - const AliasTurboModuleBaseOptions &value) { - auto result = facebook::jsi::Object(rt); - result.setProperty(rt, \\"offset\\", bridging::toJs(rt, value.offset)); - result.setProperty(rt, \\"size\\", bridging::toJs(rt, value.size)); - if (value.displaySize) { - result.setProperty(rt, \\"displaySize\\", bridging::toJs(rt, value.displaySize.value())); - } - if (value.resizeMode) { - result.setProperty(rt, \\"resizeMode\\", bridging::toJs(rt, value.resizeMode.value())); - } - if (value.allowExternalStorage) { - result.setProperty(rt, \\"allowExternalStorage\\", bridging::toJs(rt, value.allowExternalStorage.value())); - } - return result; - } -}; - -class JSI_EXPORT AliasTurboModuleCxxSpecJSI : public TurboModule { -protected: - AliasTurboModuleCxxSpecJSI(std::shared_ptr jsInvoker); - -public: - virtual jsi::Object getConstants(jsi::Runtime &rt) = 0; - virtual void cropImage(jsi::Runtime &rt, jsi::Object cropData) = 0; - -}; - -template -class JSI_EXPORT AliasTurboModuleCxxSpec : public TurboModule { -public: - jsi::Value get(jsi::Runtime &rt, const jsi::PropNameID &propName) override { - return delegate_.get(rt, propName); - } - -protected: - AliasTurboModuleCxxSpec(std::shared_ptr jsInvoker) - : TurboModule(\\"AliasTurboModule\\", jsInvoker), - delegate_(static_cast(this), jsInvoker) {} - -private: - class Delegate : public AliasTurboModuleCxxSpecJSI { - public: - Delegate(T *instance, std::shared_ptr jsInvoker) : - AliasTurboModuleCxxSpecJSI(std::move(jsInvoker)), instance_(instance) {} - - jsi::Object getConstants(jsi::Runtime &rt) override { - static_assert( - bridging::getParameterCount(&T::getConstants) == 1, - \\"Expected getConstants(...) to have 1 parameters\\"); - - return bridging::callFromJs( - rt, &T::getConstants, jsInvoker_, instance_); - } - void cropImage(jsi::Runtime &rt, jsi::Object cropData) override { - static_assert( - bridging::getParameterCount(&T::cropImage) == 2, - \\"Expected cropImage(...) to have 2 parameters\\"); - - return bridging::callFromJs( - rt, &T::cropImage, jsInvoker_, instance_, std::move(cropData)); - } - - private: - T *instance_; - }; - - Delegate delegate_; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateModuleH can generate fixture real_module_example 1`] = ` -Map { - "real_module_exampleJSI.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -#pragma mark - CameraRollManagerBasePhotoIdentifierImage - -template -struct CameraRollManagerBasePhotoIdentifierImage { - P0 uri; - P1 playableDuration; - P2 width; - P3 height; - P4 isStored; - P5 filename; - bool operator==(const CameraRollManagerBasePhotoIdentifierImage &other) const { - return uri == other.uri && playableDuration == other.playableDuration && width == other.width && height == other.height && isStored == other.isStored && filename == other.filename; - } -}; - -template -struct CameraRollManagerBasePhotoIdentifierImageBridging { - static CameraRollManagerBasePhotoIdentifierImage fromJs( - jsi::Runtime &rt, - const jsi::Object &value, - const std::shared_ptr &jsInvoker) { - CameraRollManagerBasePhotoIdentifierImage result{ - bridging::fromJs(rt, value.getProperty(rt, \\"uri\\"), jsInvoker), - bridging::fromJs(rt, value.getProperty(rt, \\"playableDuration\\"), jsInvoker), - bridging::fromJs(rt, value.getProperty(rt, \\"width\\"), jsInvoker), - bridging::fromJs(rt, value.getProperty(rt, \\"height\\"), jsInvoker), - bridging::fromJs(rt, value.getProperty(rt, \\"isStored\\"), jsInvoker), - bridging::fromJs(rt, value.getProperty(rt, \\"filename\\"), jsInvoker)}; - return result; - } - - static jsi::Object toJs( - jsi::Runtime &rt, - const CameraRollManagerBasePhotoIdentifierImage &value) { - auto result = facebook::jsi::Object(rt); - result.setProperty(rt, \\"uri\\", bridging::toJs(rt, value.uri)); - result.setProperty(rt, \\"playableDuration\\", bridging::toJs(rt, value.playableDuration)); - result.setProperty(rt, \\"width\\", bridging::toJs(rt, value.width)); - result.setProperty(rt, \\"height\\", bridging::toJs(rt, value.height)); - if (value.isStored) { - result.setProperty(rt, \\"isStored\\", bridging::toJs(rt, value.isStored.value())); - } - result.setProperty(rt, \\"filename\\", bridging::toJs(rt, value.filename)); - return result; - } -}; - - -#pragma mark - CameraRollManagerBasePhotoIdentifier - -template -struct CameraRollManagerBasePhotoIdentifier { - P0 node; - bool operator==(const CameraRollManagerBasePhotoIdentifier &other) const { - return node == other.node; - } -}; - -template -struct CameraRollManagerBasePhotoIdentifierBridging { - static CameraRollManagerBasePhotoIdentifier fromJs( - jsi::Runtime &rt, - const jsi::Object &value, - const std::shared_ptr &jsInvoker) { - CameraRollManagerBasePhotoIdentifier result{ - bridging::fromJs(rt, value.getProperty(rt, \\"node\\"), jsInvoker)}; - return result; - } - - static jsi::Object toJs( - jsi::Runtime &rt, - const CameraRollManagerBasePhotoIdentifier &value) { - auto result = facebook::jsi::Object(rt); - result.setProperty(rt, \\"node\\", bridging::toJs(rt, value.node)); - return result; - } -}; - - -#pragma mark - CameraRollManagerBasePhotoIdentifiersPage - -template -struct CameraRollManagerBasePhotoIdentifiersPage { - P0 edges; - P1 page_info; - bool operator==(const CameraRollManagerBasePhotoIdentifiersPage &other) const { - return edges == other.edges && page_info == other.page_info; - } -}; - -template -struct CameraRollManagerBasePhotoIdentifiersPageBridging { - static CameraRollManagerBasePhotoIdentifiersPage fromJs( - jsi::Runtime &rt, - const jsi::Object &value, - const std::shared_ptr &jsInvoker) { - CameraRollManagerBasePhotoIdentifiersPage result{ - bridging::fromJs(rt, value.getProperty(rt, \\"edges\\"), jsInvoker), - bridging::fromJs(rt, value.getProperty(rt, \\"page_info\\"), jsInvoker)}; - return result; - } - - static jsi::Object toJs( - jsi::Runtime &rt, - const CameraRollManagerBasePhotoIdentifiersPage &value) { - auto result = facebook::jsi::Object(rt); - result.setProperty(rt, \\"edges\\", bridging::toJs(rt, value.edges)); - result.setProperty(rt, \\"page_info\\", bridging::toJs(rt, value.page_info)); - return result; - } -}; - - -#pragma mark - CameraRollManagerBaseGetPhotosParams - -template -struct CameraRollManagerBaseGetPhotosParams { - P0 first; - P1 after; - P2 groupName; - P3 groupTypes; - P4 assetType; - P5 maxSize; - P6 mimeTypes; - bool operator==(const CameraRollManagerBaseGetPhotosParams &other) const { - return first == other.first && after == other.after && groupName == other.groupName && groupTypes == other.groupTypes && assetType == other.assetType && maxSize == other.maxSize && mimeTypes == other.mimeTypes; - } -}; - -template -struct CameraRollManagerBaseGetPhotosParamsBridging { - static CameraRollManagerBaseGetPhotosParams fromJs( - jsi::Runtime &rt, - const jsi::Object &value, - const std::shared_ptr &jsInvoker) { - CameraRollManagerBaseGetPhotosParams result{ - bridging::fromJs(rt, value.getProperty(rt, \\"first\\"), jsInvoker), - bridging::fromJs(rt, value.getProperty(rt, \\"after\\"), jsInvoker), - bridging::fromJs(rt, value.getProperty(rt, \\"groupName\\"), jsInvoker), - bridging::fromJs(rt, value.getProperty(rt, \\"groupTypes\\"), jsInvoker), - bridging::fromJs(rt, value.getProperty(rt, \\"assetType\\"), jsInvoker), - bridging::fromJs(rt, value.getProperty(rt, \\"maxSize\\"), jsInvoker), - bridging::fromJs(rt, value.getProperty(rt, \\"mimeTypes\\"), jsInvoker)}; - return result; - } - - static jsi::Object toJs( - jsi::Runtime &rt, - const CameraRollManagerBaseGetPhotosParams &value) { - auto result = facebook::jsi::Object(rt); - result.setProperty(rt, \\"first\\", bridging::toJs(rt, value.first)); - if (value.after) { - result.setProperty(rt, \\"after\\", bridging::toJs(rt, value.after.value())); - } - if (value.groupName) { - result.setProperty(rt, \\"groupName\\", bridging::toJs(rt, value.groupName.value())); - } - if (value.groupTypes) { - result.setProperty(rt, \\"groupTypes\\", bridging::toJs(rt, value.groupTypes.value())); - } - if (value.assetType) { - result.setProperty(rt, \\"assetType\\", bridging::toJs(rt, value.assetType.value())); - } - if (value.maxSize) { - result.setProperty(rt, \\"maxSize\\", bridging::toJs(rt, value.maxSize.value())); - } - if (value.mimeTypes) { - result.setProperty(rt, \\"mimeTypes\\", bridging::toJs(rt, value.mimeTypes.value())); - } - return result; - } -}; - -class JSI_EXPORT NativeCameraRollManagerCxxSpecJSI : public TurboModule { -protected: - NativeCameraRollManagerCxxSpecJSI(std::shared_ptr jsInvoker); - -public: - virtual jsi::Object getConstants(jsi::Runtime &rt) = 0; - virtual jsi::Value getPhotos(jsi::Runtime &rt, jsi::Object params) = 0; - virtual jsi::Value saveToCameraRoll(jsi::Runtime &rt, jsi::String uri, jsi::String type) = 0; - virtual jsi::Value deletePhotos(jsi::Runtime &rt, jsi::Array assets) = 0; - -}; - -template -class JSI_EXPORT NativeCameraRollManagerCxxSpec : public TurboModule { -public: - jsi::Value get(jsi::Runtime &rt, const jsi::PropNameID &propName) override { - return delegate_.get(rt, propName); - } - -protected: - NativeCameraRollManagerCxxSpec(std::shared_ptr jsInvoker) - : TurboModule(\\"CameraRollManager\\", jsInvoker), - delegate_(static_cast(this), jsInvoker) {} - -private: - class Delegate : public NativeCameraRollManagerCxxSpecJSI { - public: - Delegate(T *instance, std::shared_ptr jsInvoker) : - NativeCameraRollManagerCxxSpecJSI(std::move(jsInvoker)), instance_(instance) {} - - jsi::Object getConstants(jsi::Runtime &rt) override { - static_assert( - bridging::getParameterCount(&T::getConstants) == 1, - \\"Expected getConstants(...) to have 1 parameters\\"); - - return bridging::callFromJs( - rt, &T::getConstants, jsInvoker_, instance_); - } - jsi::Value getPhotos(jsi::Runtime &rt, jsi::Object params) override { - static_assert( - bridging::getParameterCount(&T::getPhotos) == 2, - \\"Expected getPhotos(...) to have 2 parameters\\"); - - return bridging::callFromJs( - rt, &T::getPhotos, jsInvoker_, instance_, std::move(params)); - } - jsi::Value saveToCameraRoll(jsi::Runtime &rt, jsi::String uri, jsi::String type) override { - static_assert( - bridging::getParameterCount(&T::saveToCameraRoll) == 3, - \\"Expected saveToCameraRoll(...) to have 3 parameters\\"); - - return bridging::callFromJs( - rt, &T::saveToCameraRoll, jsInvoker_, instance_, std::move(uri), std::move(type)); - } - jsi::Value deletePhotos(jsi::Runtime &rt, jsi::Array assets) override { - static_assert( - bridging::getParameterCount(&T::deletePhotos) == 2, - \\"Expected deletePhotos(...) to have 2 parameters\\"); - - return bridging::callFromJs( - rt, &T::deletePhotos, jsInvoker_, instance_, std::move(assets)); - } - - private: - T *instance_; - }; - - Delegate delegate_; -}; - -#pragma mark - ExceptionsManagerBaseStackFrame - -template -struct ExceptionsManagerBaseStackFrame { - P0 column; - P1 file; - P2 lineNumber; - P3 methodName; - P4 collapse; - bool operator==(const ExceptionsManagerBaseStackFrame &other) const { - return column == other.column && file == other.file && lineNumber == other.lineNumber && methodName == other.methodName && collapse == other.collapse; - } -}; - -template -struct ExceptionsManagerBaseStackFrameBridging { - static ExceptionsManagerBaseStackFrame fromJs( - jsi::Runtime &rt, - const jsi::Object &value, - const std::shared_ptr &jsInvoker) { - ExceptionsManagerBaseStackFrame result{ - bridging::fromJs(rt, value.getProperty(rt, \\"column\\"), jsInvoker), - bridging::fromJs(rt, value.getProperty(rt, \\"file\\"), jsInvoker), - bridging::fromJs(rt, value.getProperty(rt, \\"lineNumber\\"), jsInvoker), - bridging::fromJs(rt, value.getProperty(rt, \\"methodName\\"), jsInvoker), - bridging::fromJs(rt, value.getProperty(rt, \\"collapse\\"), jsInvoker)}; - return result; - } - - static jsi::Object toJs( - jsi::Runtime &rt, - const ExceptionsManagerBaseStackFrame &value) { - auto result = facebook::jsi::Object(rt); - if (value.column) { - result.setProperty(rt, \\"column\\", bridging::toJs(rt, value.column.value())); - } - result.setProperty(rt, \\"file\\", bridging::toJs(rt, value.file)); - if (value.lineNumber) { - result.setProperty(rt, \\"lineNumber\\", bridging::toJs(rt, value.lineNumber.value())); - } - result.setProperty(rt, \\"methodName\\", bridging::toJs(rt, value.methodName)); - if (value.collapse) { - result.setProperty(rt, \\"collapse\\", bridging::toJs(rt, value.collapse.value())); - } - return result; - } -}; - - -#pragma mark - ExceptionsManagerBaseExceptionData - -template -struct ExceptionsManagerBaseExceptionData { - P0 message; - P1 originalMessage; - P2 name; - P3 componentStack; - P4 stack; - P5 id; - P6 isFatal; - P7 extraData; - bool operator==(const ExceptionsManagerBaseExceptionData &other) const { - return message == other.message && originalMessage == other.originalMessage && name == other.name && componentStack == other.componentStack && stack == other.stack && id == other.id && isFatal == other.isFatal && extraData == other.extraData; - } -}; - -template -struct ExceptionsManagerBaseExceptionDataBridging { - static ExceptionsManagerBaseExceptionData fromJs( - jsi::Runtime &rt, - const jsi::Object &value, - const std::shared_ptr &jsInvoker) { - ExceptionsManagerBaseExceptionData result{ - bridging::fromJs(rt, value.getProperty(rt, \\"message\\"), jsInvoker), - bridging::fromJs(rt, value.getProperty(rt, \\"originalMessage\\"), jsInvoker), - bridging::fromJs(rt, value.getProperty(rt, \\"name\\"), jsInvoker), - bridging::fromJs(rt, value.getProperty(rt, \\"componentStack\\"), jsInvoker), - bridging::fromJs(rt, value.getProperty(rt, \\"stack\\"), jsInvoker), - bridging::fromJs(rt, value.getProperty(rt, \\"id\\"), jsInvoker), - bridging::fromJs(rt, value.getProperty(rt, \\"isFatal\\"), jsInvoker), - bridging::fromJs(rt, value.getProperty(rt, \\"extraData\\"), jsInvoker)}; - return result; - } - - static jsi::Object toJs( - jsi::Runtime &rt, - const ExceptionsManagerBaseExceptionData &value) { - auto result = facebook::jsi::Object(rt); - result.setProperty(rt, \\"message\\", bridging::toJs(rt, value.message)); - result.setProperty(rt, \\"originalMessage\\", bridging::toJs(rt, value.originalMessage)); - result.setProperty(rt, \\"name\\", bridging::toJs(rt, value.name)); - result.setProperty(rt, \\"componentStack\\", bridging::toJs(rt, value.componentStack)); - result.setProperty(rt, \\"stack\\", bridging::toJs(rt, value.stack)); - result.setProperty(rt, \\"id\\", bridging::toJs(rt, value.id)); - result.setProperty(rt, \\"isFatal\\", bridging::toJs(rt, value.isFatal)); - if (value.extraData) { - result.setProperty(rt, \\"extraData\\", bridging::toJs(rt, value.extraData.value())); - } - return result; - } -}; - -class JSI_EXPORT NativeExceptionsManagerCxxSpecJSI : public TurboModule { -protected: - NativeExceptionsManagerCxxSpecJSI(std::shared_ptr jsInvoker); - -public: - virtual void reportFatalException(jsi::Runtime &rt, jsi::String message, jsi::Array stack, double exceptionId) = 0; - virtual void reportSoftException(jsi::Runtime &rt, jsi::String message, jsi::Array stack, double exceptionId) = 0; - virtual void reportException(jsi::Runtime &rt, jsi::Object data) = 0; - virtual void updateExceptionMessage(jsi::Runtime &rt, jsi::String message, jsi::Array stack, double exceptionId) = 0; - virtual void dismissRedbox(jsi::Runtime &rt) = 0; - -}; - -template -class JSI_EXPORT NativeExceptionsManagerCxxSpec : public TurboModule { -public: - jsi::Value get(jsi::Runtime &rt, const jsi::PropNameID &propName) override { - return delegate_.get(rt, propName); - } - -protected: - NativeExceptionsManagerCxxSpec(std::shared_ptr jsInvoker) - : TurboModule(\\"ExceptionsManager\\", jsInvoker), - delegate_(static_cast(this), jsInvoker) {} - -private: - class Delegate : public NativeExceptionsManagerCxxSpecJSI { - public: - Delegate(T *instance, std::shared_ptr jsInvoker) : - NativeExceptionsManagerCxxSpecJSI(std::move(jsInvoker)), instance_(instance) {} - - void reportFatalException(jsi::Runtime &rt, jsi::String message, jsi::Array stack, double exceptionId) override { - static_assert( - bridging::getParameterCount(&T::reportFatalException) == 4, - \\"Expected reportFatalException(...) to have 4 parameters\\"); - - return bridging::callFromJs( - rt, &T::reportFatalException, jsInvoker_, instance_, std::move(message), std::move(stack), std::move(exceptionId)); - } - void reportSoftException(jsi::Runtime &rt, jsi::String message, jsi::Array stack, double exceptionId) override { - static_assert( - bridging::getParameterCount(&T::reportSoftException) == 4, - \\"Expected reportSoftException(...) to have 4 parameters\\"); - - return bridging::callFromJs( - rt, &T::reportSoftException, jsInvoker_, instance_, std::move(message), std::move(stack), std::move(exceptionId)); - } - void reportException(jsi::Runtime &rt, jsi::Object data) override { - static_assert( - bridging::getParameterCount(&T::reportException) == 2, - \\"Expected reportException(...) to have 2 parameters\\"); - - return bridging::callFromJs( - rt, &T::reportException, jsInvoker_, instance_, std::move(data)); - } - void updateExceptionMessage(jsi::Runtime &rt, jsi::String message, jsi::Array stack, double exceptionId) override { - static_assert( - bridging::getParameterCount(&T::updateExceptionMessage) == 4, - \\"Expected updateExceptionMessage(...) to have 4 parameters\\"); - - return bridging::callFromJs( - rt, &T::updateExceptionMessage, jsInvoker_, instance_, std::move(message), std::move(stack), std::move(exceptionId)); - } - void dismissRedbox(jsi::Runtime &rt) override { - static_assert( - bridging::getParameterCount(&T::dismissRedbox) == 1, - \\"Expected dismissRedbox(...) to have 1 parameters\\"); - - return bridging::callFromJs( - rt, &T::dismissRedbox, jsInvoker_, instance_); - } - - private: - T *instance_; - }; - - Delegate delegate_; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateModuleH can generate fixture simple_native_modules 1`] = ` -Map { - "simple_native_modulesJSI.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT NativeSampleTurboModuleCxxSpecJSI : public TurboModule { -protected: - NativeSampleTurboModuleCxxSpecJSI(std::shared_ptr jsInvoker); - -public: - virtual jsi::Object getConstants(jsi::Runtime &rt) = 0; - virtual void voidFunc(jsi::Runtime &rt) = 0; - virtual bool getBool(jsi::Runtime &rt, bool arg) = 0; - virtual double getNumber(jsi::Runtime &rt, double arg) = 0; - virtual jsi::String getString(jsi::Runtime &rt, jsi::String arg) = 0; - virtual jsi::Array getArray(jsi::Runtime &rt, jsi::Array arg) = 0; - virtual jsi::Object getObject(jsi::Runtime &rt, jsi::Object arg) = 0; - virtual double getRootTag(jsi::Runtime &rt, double arg) = 0; - virtual jsi::Object getValue(jsi::Runtime &rt, double x, jsi::String y, jsi::Object z) = 0; - virtual void getValueWithCallback(jsi::Runtime &rt, jsi::Function callback) = 0; - virtual jsi::Value getValueWithPromise(jsi::Runtime &rt, bool error) = 0; - virtual jsi::Value getValueWithOptionalArg(jsi::Runtime &rt, std::optional parameter) = 0; - virtual jsi::String getEnums(jsi::Runtime &rt, double enumInt, double enumFloat, jsi::String enumString) = 0; - -}; - -template -class JSI_EXPORT NativeSampleTurboModuleCxxSpec : public TurboModule { -public: - jsi::Value get(jsi::Runtime &rt, const jsi::PropNameID &propName) override { - return delegate_.get(rt, propName); - } - -protected: - NativeSampleTurboModuleCxxSpec(std::shared_ptr jsInvoker) - : TurboModule(\\"SampleTurboModule\\", jsInvoker), - delegate_(static_cast(this), jsInvoker) {} - -private: - class Delegate : public NativeSampleTurboModuleCxxSpecJSI { - public: - Delegate(T *instance, std::shared_ptr jsInvoker) : - NativeSampleTurboModuleCxxSpecJSI(std::move(jsInvoker)), instance_(instance) {} - - jsi::Object getConstants(jsi::Runtime &rt) override { - static_assert( - bridging::getParameterCount(&T::getConstants) == 1, - \\"Expected getConstants(...) to have 1 parameters\\"); - - return bridging::callFromJs( - rt, &T::getConstants, jsInvoker_, instance_); - } - void voidFunc(jsi::Runtime &rt) override { - static_assert( - bridging::getParameterCount(&T::voidFunc) == 1, - \\"Expected voidFunc(...) to have 1 parameters\\"); - - return bridging::callFromJs( - rt, &T::voidFunc, jsInvoker_, instance_); - } - bool getBool(jsi::Runtime &rt, bool arg) override { - static_assert( - bridging::getParameterCount(&T::getBool) == 2, - \\"Expected getBool(...) to have 2 parameters\\"); - - return bridging::callFromJs( - rt, &T::getBool, jsInvoker_, instance_, std::move(arg)); - } - double getNumber(jsi::Runtime &rt, double arg) override { - static_assert( - bridging::getParameterCount(&T::getNumber) == 2, - \\"Expected getNumber(...) to have 2 parameters\\"); - - return bridging::callFromJs( - rt, &T::getNumber, jsInvoker_, instance_, std::move(arg)); - } - jsi::String getString(jsi::Runtime &rt, jsi::String arg) override { - static_assert( - bridging::getParameterCount(&T::getString) == 2, - \\"Expected getString(...) to have 2 parameters\\"); - - return bridging::callFromJs( - rt, &T::getString, jsInvoker_, instance_, std::move(arg)); - } - jsi::Array getArray(jsi::Runtime &rt, jsi::Array arg) override { - static_assert( - bridging::getParameterCount(&T::getArray) == 2, - \\"Expected getArray(...) to have 2 parameters\\"); - - return bridging::callFromJs( - rt, &T::getArray, jsInvoker_, instance_, std::move(arg)); - } - jsi::Object getObject(jsi::Runtime &rt, jsi::Object arg) override { - static_assert( - bridging::getParameterCount(&T::getObject) == 2, - \\"Expected getObject(...) to have 2 parameters\\"); - - return bridging::callFromJs( - rt, &T::getObject, jsInvoker_, instance_, std::move(arg)); - } - double getRootTag(jsi::Runtime &rt, double arg) override { - static_assert( - bridging::getParameterCount(&T::getRootTag) == 2, - \\"Expected getRootTag(...) to have 2 parameters\\"); - - return bridging::callFromJs( - rt, &T::getRootTag, jsInvoker_, instance_, std::move(arg)); - } - jsi::Object getValue(jsi::Runtime &rt, double x, jsi::String y, jsi::Object z) override { - static_assert( - bridging::getParameterCount(&T::getValue) == 4, - \\"Expected getValue(...) to have 4 parameters\\"); - - return bridging::callFromJs( - rt, &T::getValue, jsInvoker_, instance_, std::move(x), std::move(y), std::move(z)); - } - void getValueWithCallback(jsi::Runtime &rt, jsi::Function callback) override { - static_assert( - bridging::getParameterCount(&T::getValueWithCallback) == 2, - \\"Expected getValueWithCallback(...) to have 2 parameters\\"); - - return bridging::callFromJs( - rt, &T::getValueWithCallback, jsInvoker_, instance_, std::move(callback)); - } - jsi::Value getValueWithPromise(jsi::Runtime &rt, bool error) override { - static_assert( - bridging::getParameterCount(&T::getValueWithPromise) == 2, - \\"Expected getValueWithPromise(...) to have 2 parameters\\"); - - return bridging::callFromJs( - rt, &T::getValueWithPromise, jsInvoker_, instance_, std::move(error)); - } - jsi::Value getValueWithOptionalArg(jsi::Runtime &rt, std::optional parameter) override { - static_assert( - bridging::getParameterCount(&T::getValueWithOptionalArg) == 2, - \\"Expected getValueWithOptionalArg(...) to have 2 parameters\\"); - - return bridging::callFromJs( - rt, &T::getValueWithOptionalArg, jsInvoker_, instance_, std::move(parameter)); - } - jsi::String getEnums(jsi::Runtime &rt, double enumInt, double enumFloat, jsi::String enumString) override { - static_assert( - bridging::getParameterCount(&T::getEnums) == 4, - \\"Expected getEnums(...) to have 4 parameters\\"); - - return bridging::callFromJs( - rt, &T::getEnums, jsInvoker_, instance_, std::move(enumInt), std::move(enumFloat), std::move(enumString)); - } - - private: - T *instance_; - }; - - Delegate delegate_; -}; - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateModuleH can generate fixture two_modules_different_files 1`] = ` -Map { - "two_modules_different_filesJSI.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleH.js - */ - -#pragma once - -#include -#include - -namespace facebook { -namespace react { - -class JSI_EXPORT NativeSampleTurboModuleCxxSpecJSI : public TurboModule { -protected: - NativeSampleTurboModuleCxxSpecJSI(std::shared_ptr jsInvoker); - -public: - virtual void voidFunc(jsi::Runtime &rt) = 0; - -}; - -template -class JSI_EXPORT NativeSampleTurboModuleCxxSpec : public TurboModule { -public: - jsi::Value get(jsi::Runtime &rt, const jsi::PropNameID &propName) override { - return delegate_.get(rt, propName); - } - -protected: - NativeSampleTurboModuleCxxSpec(std::shared_ptr jsInvoker) - : TurboModule(\\"SampleTurboModule\\", jsInvoker), - delegate_(static_cast(this), jsInvoker) {} - -private: - class Delegate : public NativeSampleTurboModuleCxxSpecJSI { - public: - Delegate(T *instance, std::shared_ptr jsInvoker) : - NativeSampleTurboModuleCxxSpecJSI(std::move(jsInvoker)), instance_(instance) {} - - void voidFunc(jsi::Runtime &rt) override { - static_assert( - bridging::getParameterCount(&T::voidFunc) == 1, - \\"Expected voidFunc(...) to have 1 parameters\\"); - - return bridging::callFromJs( - rt, &T::voidFunc, jsInvoker_, instance_); - } - - private: - T *instance_; - }; - - Delegate delegate_; -}; - -class JSI_EXPORT NativeSampleTurboModule2CxxSpecJSI : public TurboModule { -protected: - NativeSampleTurboModule2CxxSpecJSI(std::shared_ptr jsInvoker); - -public: - virtual jsi::Object getConstants(jsi::Runtime &rt) = 0; - virtual void voidFunc(jsi::Runtime &rt) = 0; - -}; - -template -class JSI_EXPORT NativeSampleTurboModule2CxxSpec : public TurboModule { -public: - jsi::Value get(jsi::Runtime &rt, const jsi::PropNameID &propName) override { - return delegate_.get(rt, propName); - } - -protected: - NativeSampleTurboModule2CxxSpec(std::shared_ptr jsInvoker) - : TurboModule(\\"SampleTurboModule2\\", jsInvoker), - delegate_(static_cast(this), jsInvoker) {} - -private: - class Delegate : public NativeSampleTurboModule2CxxSpecJSI { - public: - Delegate(T *instance, std::shared_ptr jsInvoker) : - NativeSampleTurboModule2CxxSpecJSI(std::move(jsInvoker)), instance_(instance) {} - - jsi::Object getConstants(jsi::Runtime &rt) override { - static_assert( - bridging::getParameterCount(&T::getConstants) == 1, - \\"Expected getConstants(...) to have 1 parameters\\"); - - return bridging::callFromJs( - rt, &T::getConstants, jsInvoker_, instance_); - } - void voidFunc(jsi::Runtime &rt) override { - static_assert( - bridging::getParameterCount(&T::voidFunc) == 1, - \\"Expected voidFunc(...) to have 1 parameters\\"); - - return bridging::callFromJs( - rt, &T::voidFunc, jsInvoker_, instance_); - } - - private: - T *instance_; - }; - - Delegate delegate_; -}; - -} // namespace react -} // namespace facebook -", -} -`; diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleHObjCpp-test.js.snap b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleHObjCpp-test.js.snap deleted file mode 100644 index 4e923454c776..000000000000 --- a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleHObjCpp-test.js.snap +++ /dev/null @@ -1,997 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GenerateModuleHObjCpp can generate fixture SampleWithUppercaseName 1`] = ` -Map { - "SampleWithUppercaseName.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleObjCpp - * - * We create an umbrella header (and corresponding implementation) here since - * Cxx compilation in BUCK has a limitation: source-code producing genrule()s - * must have a single output. More files => more genrule()s => slower builds. - */ - -#ifndef __cplusplus -#error This file must be compiled as Obj-C++. If you are importing it, you must change your file extension to .mm. -#endif -#import -#import -#import -#import -#import -#import -#import -#import -#import -#import - - -@protocol NativeSampleTurboModuleSpec - - - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeSampleTurboModule' - */ - class JSI_EXPORT NativeSampleTurboModuleSpecJSI : public ObjCTurboModule { - public: - NativeSampleTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook - -", -} -`; - -exports[`GenerateModuleHObjCpp can generate fixture complex_objects 1`] = ` -Map { - "complex_objects.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleObjCpp - * - * We create an umbrella header (and corresponding implementation) here since - * Cxx compilation in BUCK has a limitation: source-code producing genrule()s - * must have a single output. More files => more genrule()s => slower builds. - */ - -#ifndef __cplusplus -#error This file must be compiled as Obj-C++. If you are importing it, you must change your file extension to .mm. -#endif -#import -#import -#import -#import -#import -#import -#import -#import -#import -#import - -namespace JS { - namespace NativeSampleTurboModule { - struct SpecDifficultAE { - bool D() const; - double E() const; - NSString *F() const; - double id_() const; - - SpecDifficultAE(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (NativeSampleTurboModule_SpecDifficultAE) -+ (RCTManagedPointer *)JS_NativeSampleTurboModule_SpecDifficultAE:(id)json; -@end -namespace JS { - namespace NativeSampleTurboModule { - struct SpecDifficultA { - bool D() const; - JS::NativeSampleTurboModule::SpecDifficultAE E() const; - NSString *F() const; - - SpecDifficultA(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (NativeSampleTurboModule_SpecDifficultA) -+ (RCTManagedPointer *)JS_NativeSampleTurboModule_SpecDifficultA:(id)json; -@end -namespace JS { - namespace NativeSampleTurboModule { - struct SpecOptionalsAOptionalObjectProperty { - double x() const; - double y() const; - - SpecOptionalsAOptionalObjectProperty(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (NativeSampleTurboModule_SpecOptionalsAOptionalObjectProperty) -+ (RCTManagedPointer *)JS_NativeSampleTurboModule_SpecOptionalsAOptionalObjectProperty:(id)json; -@end -namespace JS { - namespace NativeSampleTurboModule { - struct SpecOptionalsA { - std::optional optionalNumberProperty() const; - std::optional> optionalArrayProperty() const; - std::optional optionalObjectProperty() const; - id _Nullable optionalGenericObjectProperty() const; - std::optional optionalBooleanTypeProperty() const; - - SpecOptionalsA(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (NativeSampleTurboModule_SpecOptionalsA) -+ (RCTManagedPointer *)JS_NativeSampleTurboModule_SpecOptionalsA:(id)json; -@end -namespace JS { - namespace NativeSampleTurboModule { - struct SpecGetArraysOptionsArrayOfObjectsElement { - double numberProperty() const; - - SpecGetArraysOptionsArrayOfObjectsElement(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (NativeSampleTurboModule_SpecGetArraysOptionsArrayOfObjectsElement) -+ (RCTManagedPointer *)JS_NativeSampleTurboModule_SpecGetArraysOptionsArrayOfObjectsElement:(id)json; -@end -namespace JS { - namespace NativeSampleTurboModule { - struct SpecGetArraysOptions { - facebook::react::LazyVector arrayOfNumbers() const; - std::optional> optionalArrayOfNumbers() const; - facebook::react::LazyVector arrayOfStrings() const; - std::optional> optionalArrayOfStrings() const; - facebook::react::LazyVector arrayOfObjects() const; - - SpecGetArraysOptions(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (NativeSampleTurboModule_SpecGetArraysOptions) -+ (RCTManagedPointer *)JS_NativeSampleTurboModule_SpecGetArraysOptions:(id)json; -@end -@protocol NativeSampleTurboModuleSpec - -- (NSDictionary *)difficult:(JS::NativeSampleTurboModule::SpecDifficultA &)A; -- (void)optionals:(JS::NativeSampleTurboModule::SpecOptionalsA &)A; -- (void)optionalMethod:(NSDictionary *)options - callback:(RCTResponseSenderBlock)callback - extras:(NSArray *)extras; -- (void)getArrays:(JS::NativeSampleTurboModule::SpecGetArraysOptions &)options; -- (NSDictionary * _Nullable)getNullableObject; -- (NSDictionary * _Nullable)getNullableGenericObject; -- (NSArray> * _Nullable)getNullableArray; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeSampleTurboModule' - */ - class JSI_EXPORT NativeSampleTurboModuleSpecJSI : public ObjCTurboModule { - public: - NativeSampleTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook -inline bool JS::NativeSampleTurboModule::SpecDifficultAE::D() const -{ - id const p = _v[@\\"D\\"]; - return RCTBridgingToBool(p); -} -inline double JS::NativeSampleTurboModule::SpecDifficultAE::E() const -{ - id const p = _v[@\\"E\\"]; - return RCTBridgingToDouble(p); -} -inline NSString *JS::NativeSampleTurboModule::SpecDifficultAE::F() const -{ - id const p = _v[@\\"F\\"]; - return RCTBridgingToString(p); -} -inline double JS::NativeSampleTurboModule::SpecDifficultAE::id_() const -{ - id const p = _v[@\\"id\\"]; - return RCTBridgingToDouble(p); -} -inline bool JS::NativeSampleTurboModule::SpecDifficultA::D() const -{ - id const p = _v[@\\"D\\"]; - return RCTBridgingToBool(p); -} -inline JS::NativeSampleTurboModule::SpecDifficultAE JS::NativeSampleTurboModule::SpecDifficultA::E() const -{ - id const p = _v[@\\"E\\"]; - return JS::NativeSampleTurboModule::SpecDifficultAE(p); -} -inline NSString *JS::NativeSampleTurboModule::SpecDifficultA::F() const -{ - id const p = _v[@\\"F\\"]; - return RCTBridgingToString(p); -} -inline double JS::NativeSampleTurboModule::SpecOptionalsAOptionalObjectProperty::x() const -{ - id const p = _v[@\\"x\\"]; - return RCTBridgingToDouble(p); -} -inline double JS::NativeSampleTurboModule::SpecOptionalsAOptionalObjectProperty::y() const -{ - id const p = _v[@\\"y\\"]; - return RCTBridgingToDouble(p); -} -inline std::optional JS::NativeSampleTurboModule::SpecOptionalsA::optionalNumberProperty() const -{ - id const p = _v[@\\"optionalNumberProperty\\"]; - return RCTBridgingToOptionalDouble(p); -} -inline std::optional> JS::NativeSampleTurboModule::SpecOptionalsA::optionalArrayProperty() const -{ - id const p = _v[@\\"optionalArrayProperty\\"]; - return RCTBridgingToOptionalVec(p, ^double(id itemValue_0) { return RCTBridgingToDouble(itemValue_0); }); -} -inline std::optional JS::NativeSampleTurboModule::SpecOptionalsA::optionalObjectProperty() const -{ - id const p = _v[@\\"optionalObjectProperty\\"]; - return (p == nil ? std::nullopt : std::make_optional(JS::NativeSampleTurboModule::SpecOptionalsAOptionalObjectProperty(p))); -} -inline id _Nullable JS::NativeSampleTurboModule::SpecOptionalsA::optionalGenericObjectProperty() const -{ - id const p = _v[@\\"optionalGenericObjectProperty\\"]; - return p; -} -inline std::optional JS::NativeSampleTurboModule::SpecOptionalsA::optionalBooleanTypeProperty() const -{ - id const p = _v[@\\"optionalBooleanTypeProperty\\"]; - return RCTBridgingToOptionalBool(p); -} -inline double JS::NativeSampleTurboModule::SpecGetArraysOptionsArrayOfObjectsElement::numberProperty() const -{ - id const p = _v[@\\"numberProperty\\"]; - return RCTBridgingToDouble(p); -} -inline facebook::react::LazyVector JS::NativeSampleTurboModule::SpecGetArraysOptions::arrayOfNumbers() const -{ - id const p = _v[@\\"arrayOfNumbers\\"]; - return RCTBridgingToVec(p, ^double(id itemValue_0) { return RCTBridgingToDouble(itemValue_0); }); -} -inline std::optional> JS::NativeSampleTurboModule::SpecGetArraysOptions::optionalArrayOfNumbers() const -{ - id const p = _v[@\\"optionalArrayOfNumbers\\"]; - return RCTBridgingToOptionalVec(p, ^double(id itemValue_0) { return RCTBridgingToDouble(itemValue_0); }); -} -inline facebook::react::LazyVector JS::NativeSampleTurboModule::SpecGetArraysOptions::arrayOfStrings() const -{ - id const p = _v[@\\"arrayOfStrings\\"]; - return RCTBridgingToVec(p, ^NSString *(id itemValue_0) { return RCTBridgingToString(itemValue_0); }); -} -inline std::optional> JS::NativeSampleTurboModule::SpecGetArraysOptions::optionalArrayOfStrings() const -{ - id const p = _v[@\\"optionalArrayOfStrings\\"]; - return RCTBridgingToOptionalVec(p, ^NSString *(id itemValue_0) { return RCTBridgingToString(itemValue_0); }); -} -inline facebook::react::LazyVector JS::NativeSampleTurboModule::SpecGetArraysOptions::arrayOfObjects() const -{ - id const p = _v[@\\"arrayOfObjects\\"]; - return RCTBridgingToVec(p, ^JS::NativeSampleTurboModule::SpecGetArraysOptionsArrayOfObjectsElement(id itemValue_0) { return JS::NativeSampleTurboModule::SpecGetArraysOptionsArrayOfObjectsElement(itemValue_0); }); -} -", -} -`; - -exports[`GenerateModuleHObjCpp can generate fixture cxx_only_native_modules 1`] = ` -Map { - "cxx_only_native_modules.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleObjCpp - * - * We create an umbrella header (and corresponding implementation) here since - * Cxx compilation in BUCK has a limitation: source-code producing genrule()s - * must have a single output. More files => more genrule()s => slower builds. - */ - -#ifndef __cplusplus -#error This file must be compiled as Obj-C++. If you are importing it, you must change your file extension to .mm. -#endif -#import -#import -#import -#import -#import -#import -#import -#import -#import -#import - - - -", -} -`; - -exports[`GenerateModuleHObjCpp can generate fixture empty_native_modules 1`] = ` -Map { - "empty_native_modules.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleObjCpp - * - * We create an umbrella header (and corresponding implementation) here since - * Cxx compilation in BUCK has a limitation: source-code producing genrule()s - * must have a single output. More files => more genrule()s => slower builds. - */ - -#ifndef __cplusplus -#error This file must be compiled as Obj-C++. If you are importing it, you must change your file extension to .mm. -#endif -#import -#import -#import -#import -#import -#import -#import -#import -#import -#import - - -@protocol NativeSampleTurboModuleSpec - - - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeSampleTurboModule' - */ - class JSI_EXPORT NativeSampleTurboModuleSpecJSI : public ObjCTurboModule { - public: - NativeSampleTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook - -", -} -`; - -exports[`GenerateModuleHObjCpp can generate fixture native_modules_with_type_aliases 1`] = ` -Map { - "native_modules_with_type_aliases.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleObjCpp - * - * We create an umbrella header (and corresponding implementation) here since - * Cxx compilation in BUCK has a limitation: source-code producing genrule()s - * must have a single output. More files => more genrule()s => slower builds. - */ - -#ifndef __cplusplus -#error This file must be compiled as Obj-C++. If you are importing it, you must change your file extension to .mm. -#endif -#import -#import -#import -#import -#import -#import -#import -#import -#import -#import - -namespace JS { - namespace AliasTurboModule { - struct OptionsOffset { - double x() const; - double y() const; - - OptionsOffset(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (AliasTurboModule_OptionsOffset) -+ (RCTManagedPointer *)JS_AliasTurboModule_OptionsOffset:(id)json; -@end -namespace JS { - namespace AliasTurboModule { - struct OptionsSize { - double width() const; - double height() const; - - OptionsSize(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (AliasTurboModule_OptionsSize) -+ (RCTManagedPointer *)JS_AliasTurboModule_OptionsSize:(id)json; -@end -namespace JS { - namespace AliasTurboModule { - struct OptionsDisplaySize { - double width() const; - double height() const; - - OptionsDisplaySize(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (AliasTurboModule_OptionsDisplaySize) -+ (RCTManagedPointer *)JS_AliasTurboModule_OptionsDisplaySize:(id)json; -@end -namespace JS { - namespace AliasTurboModule { - struct Options { - JS::AliasTurboModule::OptionsOffset offset() const; - JS::AliasTurboModule::OptionsSize size() const; - std::optional displaySize() const; - NSString *resizeMode() const; - std::optional allowExternalStorage() const; - - Options(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (AliasTurboModule_Options) -+ (RCTManagedPointer *)JS_AliasTurboModule_Options:(id)json; -@end -@protocol AliasTurboModuleSpec - -- (void)cropImage:(JS::AliasTurboModule::Options &)cropData; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'AliasTurboModule' - */ - class JSI_EXPORT AliasTurboModuleSpecJSI : public ObjCTurboModule { - public: - AliasTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook -inline double JS::AliasTurboModule::OptionsOffset::x() const -{ - id const p = _v[@\\"x\\"]; - return RCTBridgingToDouble(p); -} -inline double JS::AliasTurboModule::OptionsOffset::y() const -{ - id const p = _v[@\\"y\\"]; - return RCTBridgingToDouble(p); -} -inline double JS::AliasTurboModule::OptionsSize::width() const -{ - id const p = _v[@\\"width\\"]; - return RCTBridgingToDouble(p); -} -inline double JS::AliasTurboModule::OptionsSize::height() const -{ - id const p = _v[@\\"height\\"]; - return RCTBridgingToDouble(p); -} -inline double JS::AliasTurboModule::OptionsDisplaySize::width() const -{ - id const p = _v[@\\"width\\"]; - return RCTBridgingToDouble(p); -} -inline double JS::AliasTurboModule::OptionsDisplaySize::height() const -{ - id const p = _v[@\\"height\\"]; - return RCTBridgingToDouble(p); -} -inline JS::AliasTurboModule::OptionsOffset JS::AliasTurboModule::Options::offset() const -{ - id const p = _v[@\\"offset\\"]; - return JS::AliasTurboModule::OptionsOffset(p); -} -inline JS::AliasTurboModule::OptionsSize JS::AliasTurboModule::Options::size() const -{ - id const p = _v[@\\"size\\"]; - return JS::AliasTurboModule::OptionsSize(p); -} -inline std::optional JS::AliasTurboModule::Options::displaySize() const -{ - id const p = _v[@\\"displaySize\\"]; - return (p == nil ? std::nullopt : std::make_optional(JS::AliasTurboModule::OptionsDisplaySize(p))); -} -inline NSString *JS::AliasTurboModule::Options::resizeMode() const -{ - id const p = _v[@\\"resizeMode\\"]; - return RCTBridgingToOptionalString(p); -} -inline std::optional JS::AliasTurboModule::Options::allowExternalStorage() const -{ - id const p = _v[@\\"allowExternalStorage\\"]; - return RCTBridgingToOptionalBool(p); -} -", -} -`; - -exports[`GenerateModuleHObjCpp can generate fixture real_module_example 1`] = ` -Map { - "real_module_example.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleObjCpp - * - * We create an umbrella header (and corresponding implementation) here since - * Cxx compilation in BUCK has a limitation: source-code producing genrule()s - * must have a single output. More files => more genrule()s => slower builds. - */ - -#ifndef __cplusplus -#error This file must be compiled as Obj-C++. If you are importing it, you must change your file extension to .mm. -#endif -#import -#import -#import -#import -#import -#import -#import -#import -#import -#import - -namespace JS { - namespace NativeCameraRollManager { - struct GetPhotosParams { - double first() const; - NSString *after() const; - NSString *groupName() const; - NSString *groupTypes() const; - NSString *assetType() const; - std::optional maxSize() const; - std::optional> mimeTypes() const; - - GetPhotosParams(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (NativeCameraRollManager_GetPhotosParams) -+ (RCTManagedPointer *)JS_NativeCameraRollManager_GetPhotosParams:(id)json; -@end -@protocol NativeCameraRollManagerSpec - -- (void)getPhotos:(JS::NativeCameraRollManager::GetPhotosParams &)params - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject; -- (void)saveToCameraRoll:(NSString *)uri - type:(NSString *)type - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject; -- (void)deletePhotos:(NSArray *)assets - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeCameraRollManager' - */ - class JSI_EXPORT NativeCameraRollManagerSpecJSI : public ObjCTurboModule { - public: - NativeCameraRollManagerSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook -namespace JS { - namespace NativeExceptionsManager { - struct StackFrame { - std::optional column() const; - NSString *file() const; - std::optional lineNumber() const; - NSString *methodName() const; - std::optional collapse() const; - - StackFrame(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (NativeExceptionsManager_StackFrame) -+ (RCTManagedPointer *)JS_NativeExceptionsManager_StackFrame:(id)json; -@end -namespace JS { - namespace NativeExceptionsManager { - struct ExceptionData { - NSString *message() const; - NSString *originalMessage() const; - NSString *name() const; - NSString *componentStack() const; - facebook::react::LazyVector stack() const; - double id_() const; - bool isFatal() const; - id _Nullable extraData() const; - - ExceptionData(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (NativeExceptionsManager_ExceptionData) -+ (RCTManagedPointer *)JS_NativeExceptionsManager_ExceptionData:(id)json; -@end -@protocol NativeExceptionsManagerSpec - -- (void)reportFatalException:(NSString *)message - stack:(NSArray *)stack - exceptionId:(double)exceptionId; -- (void)reportSoftException:(NSString *)message - stack:(NSArray *)stack - exceptionId:(double)exceptionId; -- (void)reportException:(JS::NativeExceptionsManager::ExceptionData &)data; -- (void)updateExceptionMessage:(NSString *)message - stack:(NSArray *)stack - exceptionId:(double)exceptionId; -- (void)dismissRedbox; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeExceptionsManager' - */ - class JSI_EXPORT NativeExceptionsManagerSpecJSI : public ObjCTurboModule { - public: - NativeExceptionsManagerSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook -inline double JS::NativeCameraRollManager::GetPhotosParams::first() const -{ - id const p = _v[@\\"first\\"]; - return RCTBridgingToDouble(p); -} -inline NSString *JS::NativeCameraRollManager::GetPhotosParams::after() const -{ - id const p = _v[@\\"after\\"]; - return RCTBridgingToOptionalString(p); -} -inline NSString *JS::NativeCameraRollManager::GetPhotosParams::groupName() const -{ - id const p = _v[@\\"groupName\\"]; - return RCTBridgingToOptionalString(p); -} -inline NSString *JS::NativeCameraRollManager::GetPhotosParams::groupTypes() const -{ - id const p = _v[@\\"groupTypes\\"]; - return RCTBridgingToOptionalString(p); -} -inline NSString *JS::NativeCameraRollManager::GetPhotosParams::assetType() const -{ - id const p = _v[@\\"assetType\\"]; - return RCTBridgingToOptionalString(p); -} -inline std::optional JS::NativeCameraRollManager::GetPhotosParams::maxSize() const -{ - id const p = _v[@\\"maxSize\\"]; - return RCTBridgingToOptionalDouble(p); -} -inline std::optional> JS::NativeCameraRollManager::GetPhotosParams::mimeTypes() const -{ - id const p = _v[@\\"mimeTypes\\"]; - return RCTBridgingToOptionalVec(p, ^NSString *(id itemValue_0) { return RCTBridgingToString(itemValue_0); }); -} -inline std::optional JS::NativeExceptionsManager::StackFrame::column() const -{ - id const p = _v[@\\"column\\"]; - return RCTBridgingToOptionalDouble(p); -} -inline NSString *JS::NativeExceptionsManager::StackFrame::file() const -{ - id const p = _v[@\\"file\\"]; - return RCTBridgingToString(p); -} -inline std::optional JS::NativeExceptionsManager::StackFrame::lineNumber() const -{ - id const p = _v[@\\"lineNumber\\"]; - return RCTBridgingToOptionalDouble(p); -} -inline NSString *JS::NativeExceptionsManager::StackFrame::methodName() const -{ - id const p = _v[@\\"methodName\\"]; - return RCTBridgingToString(p); -} -inline std::optional JS::NativeExceptionsManager::StackFrame::collapse() const -{ - id const p = _v[@\\"collapse\\"]; - return RCTBridgingToOptionalBool(p); -} -inline NSString *JS::NativeExceptionsManager::ExceptionData::message() const -{ - id const p = _v[@\\"message\\"]; - return RCTBridgingToString(p); -} -inline NSString *JS::NativeExceptionsManager::ExceptionData::originalMessage() const -{ - id const p = _v[@\\"originalMessage\\"]; - return RCTBridgingToString(p); -} -inline NSString *JS::NativeExceptionsManager::ExceptionData::name() const -{ - id const p = _v[@\\"name\\"]; - return RCTBridgingToString(p); -} -inline NSString *JS::NativeExceptionsManager::ExceptionData::componentStack() const -{ - id const p = _v[@\\"componentStack\\"]; - return RCTBridgingToString(p); -} -inline facebook::react::LazyVector JS::NativeExceptionsManager::ExceptionData::stack() const -{ - id const p = _v[@\\"stack\\"]; - return RCTBridgingToVec(p, ^JS::NativeExceptionsManager::StackFrame(id itemValue_0) { return JS::NativeExceptionsManager::StackFrame(itemValue_0); }); -} -inline double JS::NativeExceptionsManager::ExceptionData::id_() const -{ - id const p = _v[@\\"id\\"]; - return RCTBridgingToDouble(p); -} -inline bool JS::NativeExceptionsManager::ExceptionData::isFatal() const -{ - id const p = _v[@\\"isFatal\\"]; - return RCTBridgingToBool(p); -} -inline id _Nullable JS::NativeExceptionsManager::ExceptionData::extraData() const -{ - id const p = _v[@\\"extraData\\"]; - return p; -} -", -} -`; - -exports[`GenerateModuleHObjCpp can generate fixture simple_native_modules 1`] = ` -Map { - "simple_native_modules.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleObjCpp - * - * We create an umbrella header (and corresponding implementation) here since - * Cxx compilation in BUCK has a limitation: source-code producing genrule()s - * must have a single output. More files => more genrule()s => slower builds. - */ - -#ifndef __cplusplus -#error This file must be compiled as Obj-C++. If you are importing it, you must change your file extension to .mm. -#endif -#import -#import -#import -#import -#import -#import -#import -#import -#import -#import - -namespace JS { - namespace NativeSampleTurboModule { - struct Constants { - - struct Builder { - struct Input { - RCTRequired const1; - RCTRequired const2; - RCTRequired const3; - }; - - /** Initialize with a set of values */ - Builder(const Input i); - /** Initialize with an existing Constants */ - Builder(Constants i); - /** Builds the object. Generally used only by the infrastructure. */ - NSDictionary *buildUnsafeRawValue() const { return _factory(); }; - private: - NSDictionary *(^_factory)(void); - }; - - static Constants fromUnsafeRawValue(NSDictionary *const v) { return {v}; } - NSDictionary *unsafeRawValue() const { return _v; } - private: - Constants(NSDictionary *const v) : _v(v) {} - NSDictionary *_v; - }; - } -} -@protocol NativeSampleTurboModuleSpec - -- (void)voidFunc; -- (NSNumber *)getBool:(BOOL)arg; -- (NSNumber *)getNumber:(double)arg; -- (NSString *)getString:(NSString *)arg; -- (NSArray *)getArray:(NSArray *)arg; -- (NSDictionary *)getObject:(NSDictionary *)arg; -- (NSNumber *)getRootTag:(double)arg; -- (NSDictionary *)getValue:(double)x - y:(NSString *)y - z:(NSDictionary *)z; -- (void)getValueWithCallback:(RCTResponseSenderBlock)callback; -- (void)getValueWithPromise:(BOOL)error - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject; -- (void)getValueWithOptionalArg:(NSDictionary *)parameter - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject; -- (NSString *)getEnums:(double)enumInt - enumFloat:(double)enumFloat - enumString:(NSString *)enumString; -- (facebook::react::ModuleConstants)constantsToExport; -- (facebook::react::ModuleConstants)getConstants; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeSampleTurboModule' - */ - class JSI_EXPORT NativeSampleTurboModuleSpecJSI : public ObjCTurboModule { - public: - NativeSampleTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook -inline JS::NativeSampleTurboModule::Constants::Builder::Builder(const Input i) : _factory(^{ - NSMutableDictionary *d = [NSMutableDictionary new]; - auto const1 = i.const1.get(); - d[@\\"const1\\"] = @(const1); - auto const2 = i.const2.get(); - d[@\\"const2\\"] = @(const2); - auto const3 = i.const3.get(); - d[@\\"const3\\"] = const3; - return d; -}) {} -inline JS::NativeSampleTurboModule::Constants::Builder::Builder(Constants i) : _factory(^{ - return i.unsafeRawValue(); -}) {} -", -} -`; - -exports[`GenerateModuleHObjCpp can generate fixture two_modules_different_files 1`] = ` -Map { - "two_modules_different_files.h" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleObjCpp - * - * We create an umbrella header (and corresponding implementation) here since - * Cxx compilation in BUCK has a limitation: source-code producing genrule()s - * must have a single output. More files => more genrule()s => slower builds. - */ - -#ifndef __cplusplus -#error This file must be compiled as Obj-C++. If you are importing it, you must change your file extension to .mm. -#endif -#import -#import -#import -#import -#import -#import -#import -#import -#import -#import - - -@protocol NativeSampleTurboModuleSpec - -- (void)voidFunc; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeSampleTurboModule' - */ - class JSI_EXPORT NativeSampleTurboModuleSpecJSI : public ObjCTurboModule { - public: - NativeSampleTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook - -@protocol NativeSampleTurboModule2Spec - -- (void)voidFunc; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeSampleTurboModule2' - */ - class JSI_EXPORT NativeSampleTurboModule2SpecJSI : public ObjCTurboModule { - public: - NativeSampleTurboModule2SpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook - - -", -} -`; diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJavaSpec-test.js.snap b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJavaSpec-test.js.snap deleted file mode 100644 index 473878ebefa9..000000000000 --- a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJavaSpec-test.js.snap +++ /dev/null @@ -1,457 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GenerateModuleJavaSpec can generate fixture SampleWithUppercaseName 1`] = ` -Map { - "java/com/facebook/fbreact/specs/NativeSampleTurboModuleSpec.java" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleJavaSpec.js - * - * @nolint - */ - -package com.facebook.fbreact.specs; - -import com.facebook.proguard.annotations.DoNotStrip; -import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.bridge.ReactContextBaseJavaModule; -import com.facebook.react.bridge.ReactMethod; -import com.facebook.react.bridge.ReactModuleWithSpec; -import com.facebook.react.turbomodule.core.interfaces.TurboModule; - -public abstract class NativeSampleTurboModuleSpec extends ReactContextBaseJavaModule implements ReactModuleWithSpec, TurboModule { - public NativeSampleTurboModuleSpec(ReactApplicationContext reactContext) { - super(reactContext); - } - - -} -", -} -`; - -exports[`GenerateModuleJavaSpec can generate fixture complex_objects 1`] = ` -Map { - "java/com/facebook/fbreact/specs/NativeSampleTurboModuleSpec.java" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleJavaSpec.js - * - * @nolint - */ - -package com.facebook.fbreact.specs; - -import com.facebook.proguard.annotations.DoNotStrip; -import com.facebook.react.bridge.Callback; -import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.bridge.ReactContextBaseJavaModule; -import com.facebook.react.bridge.ReactMethod; -import com.facebook.react.bridge.ReactModuleWithSpec; -import com.facebook.react.bridge.ReadableArray; -import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.bridge.WritableArray; -import com.facebook.react.bridge.WritableMap; -import com.facebook.react.turbomodule.core.interfaces.TurboModule; -import javax.annotation.Nullable; - -public abstract class NativeSampleTurboModuleSpec extends ReactContextBaseJavaModule implements ReactModuleWithSpec, TurboModule { - public NativeSampleTurboModuleSpec(ReactApplicationContext reactContext) { - super(reactContext); - } - - @ReactMethod(isBlockingSynchronousMethod = true) - @DoNotStrip - public abstract WritableMap difficult(ReadableMap A); - - @ReactMethod - @DoNotStrip - public abstract void optionals(ReadableMap A); - - @ReactMethod - @DoNotStrip - public void optionalMethod(ReadableMap options, Callback callback, ReadableArray extras) {} - - @ReactMethod - @DoNotStrip - public abstract void getArrays(ReadableMap options); - - @ReactMethod(isBlockingSynchronousMethod = true) - @DoNotStrip - public abstract @Nullable WritableMap getNullableObject(); - - @ReactMethod(isBlockingSynchronousMethod = true) - @DoNotStrip - public abstract @Nullable WritableMap getNullableGenericObject(); - - @ReactMethod(isBlockingSynchronousMethod = true) - @DoNotStrip - public abstract @Nullable WritableArray getNullableArray(); -} -", -} -`; - -exports[`GenerateModuleJavaSpec can generate fixture cxx_only_native_modules 1`] = `Map {}`; - -exports[`GenerateModuleJavaSpec can generate fixture empty_native_modules 1`] = ` -Map { - "java/com/facebook/fbreact/specs/NativeSampleTurboModuleSpec.java" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleJavaSpec.js - * - * @nolint - */ - -package com.facebook.fbreact.specs; - -import com.facebook.proguard.annotations.DoNotStrip; -import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.bridge.ReactContextBaseJavaModule; -import com.facebook.react.bridge.ReactMethod; -import com.facebook.react.bridge.ReactModuleWithSpec; -import com.facebook.react.turbomodule.core.interfaces.TurboModule; - -public abstract class NativeSampleTurboModuleSpec extends ReactContextBaseJavaModule implements ReactModuleWithSpec, TurboModule { - public NativeSampleTurboModuleSpec(ReactApplicationContext reactContext) { - super(reactContext); - } - - -} -", -} -`; - -exports[`GenerateModuleJavaSpec can generate fixture native_modules_with_type_aliases 1`] = ` -Map { - "java/com/facebook/fbreact/specs/AliasTurboModuleSpec.java" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleJavaSpec.js - * - * @nolint - */ - -package com.facebook.fbreact.specs; - -import com.facebook.proguard.annotations.DoNotStrip; -import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.bridge.ReactContextBaseJavaModule; -import com.facebook.react.bridge.ReactMethod; -import com.facebook.react.bridge.ReactModuleWithSpec; -import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.turbomodule.core.interfaces.TurboModule; - -public abstract class AliasTurboModuleSpec extends ReactContextBaseJavaModule implements ReactModuleWithSpec, TurboModule { - public AliasTurboModuleSpec(ReactApplicationContext reactContext) { - super(reactContext); - } - - @ReactMethod - @DoNotStrip - public abstract void cropImage(ReadableMap cropData); -} -", -} -`; - -exports[`GenerateModuleJavaSpec can generate fixture real_module_example 1`] = ` -Map { - "java/com/facebook/fbreact/specs/NativeCameraRollManagerSpec.java" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleJavaSpec.js - * - * @nolint - */ - -package com.facebook.fbreact.specs; - -import com.facebook.proguard.annotations.DoNotStrip; -import com.facebook.react.bridge.Promise; -import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.bridge.ReactContextBaseJavaModule; -import com.facebook.react.bridge.ReactMethod; -import com.facebook.react.bridge.ReactModuleWithSpec; -import com.facebook.react.bridge.ReadableArray; -import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.turbomodule.core.interfaces.TurboModule; - -public abstract class NativeCameraRollManagerSpec extends ReactContextBaseJavaModule implements ReactModuleWithSpec, TurboModule { - public NativeCameraRollManagerSpec(ReactApplicationContext reactContext) { - super(reactContext); - } - - @ReactMethod - @DoNotStrip - public abstract void getPhotos(ReadableMap params, Promise promise); - - @ReactMethod - @DoNotStrip - public abstract void saveToCameraRoll(String uri, String type, Promise promise); - - @ReactMethod - @DoNotStrip - public abstract void deletePhotos(ReadableArray assets, Promise promise); -} -", - "java/com/facebook/fbreact/specs/NativeExceptionsManagerSpec.java" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleJavaSpec.js - * - * @nolint - */ - -package com.facebook.fbreact.specs; - -import com.facebook.proguard.annotations.DoNotStrip; -import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.bridge.ReactContextBaseJavaModule; -import com.facebook.react.bridge.ReactMethod; -import com.facebook.react.bridge.ReactModuleWithSpec; -import com.facebook.react.bridge.ReadableArray; -import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.turbomodule.core.interfaces.TurboModule; - -public abstract class NativeExceptionsManagerSpec extends ReactContextBaseJavaModule implements ReactModuleWithSpec, TurboModule { - public NativeExceptionsManagerSpec(ReactApplicationContext reactContext) { - super(reactContext); - } - - @ReactMethod - @DoNotStrip - public abstract void reportFatalException(String message, ReadableArray stack, double exceptionId); - - @ReactMethod - @DoNotStrip - public abstract void reportSoftException(String message, ReadableArray stack, double exceptionId); - - @ReactMethod - @DoNotStrip - public void reportException(ReadableMap data) {} - - @ReactMethod - @DoNotStrip - public abstract void updateExceptionMessage(String message, ReadableArray stack, double exceptionId); - - @ReactMethod - @DoNotStrip - public void dismissRedbox() {} -} -", -} -`; - -exports[`GenerateModuleJavaSpec can generate fixture simple_native_modules 1`] = ` -Map { - "java/com/facebook/fbreact/specs/NativeSampleTurboModuleSpec.java" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleJavaSpec.js - * - * @nolint - */ - -package com.facebook.fbreact.specs; - -import com.facebook.proguard.annotations.DoNotStrip; -import com.facebook.react.bridge.Callback; -import com.facebook.react.bridge.Promise; -import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.bridge.ReactContextBaseJavaModule; -import com.facebook.react.bridge.ReactMethod; -import com.facebook.react.bridge.ReactModuleWithSpec; -import com.facebook.react.bridge.ReadableArray; -import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.bridge.WritableArray; -import com.facebook.react.bridge.WritableMap; -import com.facebook.react.common.build.ReactBuildConfig; -import com.facebook.react.turbomodule.core.interfaces.TurboModule; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import javax.annotation.Nullable; - -public abstract class NativeSampleTurboModuleSpec extends ReactContextBaseJavaModule implements ReactModuleWithSpec, TurboModule { - public NativeSampleTurboModuleSpec(ReactApplicationContext reactContext) { - super(reactContext); - } - - protected abstract Map getTypedExportedConstants(); - - @Override - @DoNotStrip - public final @Nullable Map getConstants() { - Map constants = getTypedExportedConstants(); - if (ReactBuildConfig.DEBUG || ReactBuildConfig.IS_INTERNAL_BUILD) { - Set obligatoryFlowConstants = new HashSet<>(Arrays.asList( - \\"const1\\", - \\"const2\\", - \\"const3\\" - )); - Set optionalFlowConstants = new HashSet<>(); - Set undeclaredConstants = new HashSet<>(constants.keySet()); - undeclaredConstants.removeAll(obligatoryFlowConstants); - undeclaredConstants.removeAll(optionalFlowConstants); - if (!undeclaredConstants.isEmpty()) { - throw new IllegalStateException(String.format(\\"Native Module Flow doesn't declare constants: %s\\", undeclaredConstants)); - } - undeclaredConstants = obligatoryFlowConstants; - undeclaredConstants.removeAll(constants.keySet()); - if (!undeclaredConstants.isEmpty()) { - throw new IllegalStateException(String.format(\\"Native Module doesn't fill in constants: %s\\", undeclaredConstants)); - } - } - return constants; - } - - @ReactMethod - @DoNotStrip - public abstract void voidFunc(); - - @ReactMethod(isBlockingSynchronousMethod = true) - @DoNotStrip - public abstract boolean getBool(boolean arg); - - @ReactMethod(isBlockingSynchronousMethod = true) - @DoNotStrip - public abstract double getNumber(double arg); - - @ReactMethod(isBlockingSynchronousMethod = true) - @DoNotStrip - public abstract String getString(String arg); - - @ReactMethod(isBlockingSynchronousMethod = true) - @DoNotStrip - public abstract WritableArray getArray(ReadableArray arg); - - @ReactMethod(isBlockingSynchronousMethod = true) - @DoNotStrip - public abstract WritableMap getObject(ReadableMap arg); - - @ReactMethod(isBlockingSynchronousMethod = true) - @DoNotStrip - public abstract double getRootTag(double arg); - - @ReactMethod(isBlockingSynchronousMethod = true) - @DoNotStrip - public abstract WritableMap getValue(double x, String y, ReadableMap z); - - @ReactMethod - @DoNotStrip - public abstract void getValueWithCallback(Callback callback); - - @ReactMethod - @DoNotStrip - public abstract void getValueWithPromise(boolean error, Promise promise); - - @ReactMethod - @DoNotStrip - public abstract void getValueWithOptionalArg(ReadableMap parameter, Promise promise); - - @ReactMethod(isBlockingSynchronousMethod = true) - @DoNotStrip - public abstract String getEnums(double enumInt, double enumFloat, String enumString); -} -", -} -`; - -exports[`GenerateModuleJavaSpec can generate fixture two_modules_different_files 1`] = ` -Map { - "java/com/facebook/fbreact/specs/NativeSampleTurboModuleSpec.java" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleJavaSpec.js - * - * @nolint - */ - -package com.facebook.fbreact.specs; - -import com.facebook.proguard.annotations.DoNotStrip; -import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.bridge.ReactContextBaseJavaModule; -import com.facebook.react.bridge.ReactMethod; -import com.facebook.react.bridge.ReactModuleWithSpec; -import com.facebook.react.turbomodule.core.interfaces.TurboModule; - -public abstract class NativeSampleTurboModuleSpec extends ReactContextBaseJavaModule implements ReactModuleWithSpec, TurboModule { - public NativeSampleTurboModuleSpec(ReactApplicationContext reactContext) { - super(reactContext); - } - - @ReactMethod - @DoNotStrip - public abstract void voidFunc(); -} -", - "java/com/facebook/fbreact/specs/NativeSampleTurboModule2Spec.java" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleJavaSpec.js - * - * @nolint - */ - -package com.facebook.fbreact.specs; - -import com.facebook.proguard.annotations.DoNotStrip; -import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.bridge.ReactContextBaseJavaModule; -import com.facebook.react.bridge.ReactMethod; -import com.facebook.react.bridge.ReactModuleWithSpec; -import com.facebook.react.turbomodule.core.interfaces.TurboModule; - -public abstract class NativeSampleTurboModule2Spec extends ReactContextBaseJavaModule implements ReactModuleWithSpec, TurboModule { - public NativeSampleTurboModule2Spec(ReactApplicationContext reactContext) { - super(reactContext); - } - - @ReactMethod - @DoNotStrip - public abstract void voidFunc(); -} -", -} -`; diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJniCpp-test.js.snap b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJniCpp-test.js.snap deleted file mode 100644 index bb1428ed7ae0..000000000000 --- a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJniCpp-test.js.snap +++ /dev/null @@ -1,479 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GenerateModuleJniCpp can generate fixture SampleWithUppercaseName 1`] = ` -Map { - "jni/SampleWithUppercaseName-generated.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleJniCpp.js - */ - -#include \\"SampleWithUppercaseName.h\\" - -namespace facebook { -namespace react { - - - -NativeSampleTurboModuleSpecJSI::NativeSampleTurboModuleSpecJSI(const JavaTurboModule::InitParams ¶ms) - : JavaTurboModule(params) { - -} - -std::shared_ptr SampleWithUppercaseName_ModuleProvider(const std::string &moduleName, const JavaTurboModule::InitParams ¶ms) { - if (moduleName == \\"SampleTurboModule\\") { - return std::make_shared(params); - } - return nullptr; -} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateModuleJniCpp can generate fixture complex_objects 1`] = ` -Map { - "jni/complex_objects-generated.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleJniCpp.js - */ - -#include \\"complex_objects.h\\" - -namespace facebook { -namespace react { - -static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_difficult(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, ObjectKind, \\"difficult\\", \\"(Lcom/facebook/react/bridge/ReadableMap;)Lcom/facebook/react/bridge/WritableMap;\\", args, count, cachedMethodId); -} - -static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_optionals(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, VoidKind, \\"optionals\\", \\"(Lcom/facebook/react/bridge/ReadableMap;)V\\", args, count, cachedMethodId); -} - -static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_optionalMethod(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, VoidKind, \\"optionalMethod\\", \\"(Lcom/facebook/react/bridge/ReadableMap;Lcom/facebook/react/bridge/Callback;Lcom/facebook/react/bridge/ReadableArray;)V\\", args, count, cachedMethodId); -} - -static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getArrays(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, VoidKind, \\"getArrays\\", \\"(Lcom/facebook/react/bridge/ReadableMap;)V\\", args, count, cachedMethodId); -} - -static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getNullableObject(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, ObjectKind, \\"getNullableObject\\", \\"()Lcom/facebook/react/bridge/WritableMap;\\", args, count, cachedMethodId); -} - -static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getNullableGenericObject(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, ObjectKind, \\"getNullableGenericObject\\", \\"()Lcom/facebook/react/bridge/WritableMap;\\", args, count, cachedMethodId); -} - -static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getNullableArray(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, ArrayKind, \\"getNullableArray\\", \\"()Lcom/facebook/react/bridge/WritableArray;\\", args, count, cachedMethodId); -} - -NativeSampleTurboModuleSpecJSI::NativeSampleTurboModuleSpecJSI(const JavaTurboModule::InitParams ¶ms) - : JavaTurboModule(params) { - methodMap_[\\"difficult\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_difficult}; - methodMap_[\\"optionals\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_optionals}; - methodMap_[\\"optionalMethod\\"] = MethodMetadata {3, __hostFunction_NativeSampleTurboModuleSpecJSI_optionalMethod}; - methodMap_[\\"getArrays\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getArrays}; - methodMap_[\\"getNullableObject\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleSpecJSI_getNullableObject}; - methodMap_[\\"getNullableGenericObject\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleSpecJSI_getNullableGenericObject}; - methodMap_[\\"getNullableArray\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleSpecJSI_getNullableArray}; -} - -std::shared_ptr complex_objects_ModuleProvider(const std::string &moduleName, const JavaTurboModule::InitParams ¶ms) { - if (moduleName == \\"SampleTurboModule\\") { - return std::make_shared(params); - } - return nullptr; -} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateModuleJniCpp can generate fixture cxx_only_native_modules 1`] = ` -Map { - "jni/cxx_only_native_modules-generated.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleJniCpp.js - */ - -#include \\"cxx_only_native_modules.h\\" - -namespace facebook { -namespace react { - - - -std::shared_ptr cxx_only_native_modules_ModuleProvider(const std::string &moduleName, const JavaTurboModule::InitParams ¶ms) { - - return nullptr; -} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateModuleJniCpp can generate fixture empty_native_modules 1`] = ` -Map { - "jni/empty_native_modules-generated.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleJniCpp.js - */ - -#include \\"empty_native_modules.h\\" - -namespace facebook { -namespace react { - - - -NativeSampleTurboModuleSpecJSI::NativeSampleTurboModuleSpecJSI(const JavaTurboModule::InitParams ¶ms) - : JavaTurboModule(params) { - -} - -std::shared_ptr empty_native_modules_ModuleProvider(const std::string &moduleName, const JavaTurboModule::InitParams ¶ms) { - if (moduleName == \\"SampleTurboModule\\") { - return std::make_shared(params); - } - return nullptr; -} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateModuleJniCpp can generate fixture native_modules_with_type_aliases 1`] = ` -Map { - "jni/native_modules_with_type_aliases-generated.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleJniCpp.js - */ - -#include \\"native_modules_with_type_aliases.h\\" - -namespace facebook { -namespace react { - - - -static facebook::jsi::Value __hostFunction_AliasTurboModuleSpecJSI_cropImage(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, VoidKind, \\"cropImage\\", \\"(Lcom/facebook/react/bridge/ReadableMap;)V\\", args, count, cachedMethodId); -} - -AliasTurboModuleSpecJSI::AliasTurboModuleSpecJSI(const JavaTurboModule::InitParams ¶ms) - : JavaTurboModule(params) { - methodMap_[\\"cropImage\\"] = MethodMetadata {1, __hostFunction_AliasTurboModuleSpecJSI_cropImage}; -} - -std::shared_ptr native_modules_with_type_aliases_ModuleProvider(const std::string &moduleName, const JavaTurboModule::InitParams ¶ms) { - if (moduleName == \\"AliasTurboModule\\") { - return std::make_shared(params); - } - return nullptr; -} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateModuleJniCpp can generate fixture real_module_example 1`] = ` -Map { - "jni/real_module_example-generated.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleJniCpp.js - */ - -#include \\"real_module_example.h\\" - -namespace facebook { -namespace react { - - - -static facebook::jsi::Value __hostFunction_NativeCameraRollManagerSpecJSI_getPhotos(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, PromiseKind, \\"getPhotos\\", \\"(Lcom/facebook/react/bridge/ReadableMap;Lcom/facebook/react/bridge/Promise;)V\\", args, count, cachedMethodId); -} - -static facebook::jsi::Value __hostFunction_NativeCameraRollManagerSpecJSI_saveToCameraRoll(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, PromiseKind, \\"saveToCameraRoll\\", \\"(Ljava/lang/String;Ljava/lang/String;Lcom/facebook/react/bridge/Promise;)V\\", args, count, cachedMethodId); -} - -static facebook::jsi::Value __hostFunction_NativeCameraRollManagerSpecJSI_deletePhotos(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, PromiseKind, \\"deletePhotos\\", \\"(Lcom/facebook/react/bridge/ReadableArray;Lcom/facebook/react/bridge/Promise;)V\\", args, count, cachedMethodId); -} - -NativeCameraRollManagerSpecJSI::NativeCameraRollManagerSpecJSI(const JavaTurboModule::InitParams ¶ms) - : JavaTurboModule(params) { - methodMap_[\\"getPhotos\\"] = MethodMetadata {1, __hostFunction_NativeCameraRollManagerSpecJSI_getPhotos}; - methodMap_[\\"saveToCameraRoll\\"] = MethodMetadata {2, __hostFunction_NativeCameraRollManagerSpecJSI_saveToCameraRoll}; - methodMap_[\\"deletePhotos\\"] = MethodMetadata {1, __hostFunction_NativeCameraRollManagerSpecJSI_deletePhotos}; -} -static facebook::jsi::Value __hostFunction_NativeExceptionsManagerSpecJSI_reportFatalException(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, VoidKind, \\"reportFatalException\\", \\"(Ljava/lang/String;Lcom/facebook/react/bridge/ReadableArray;D)V\\", args, count, cachedMethodId); -} - -static facebook::jsi::Value __hostFunction_NativeExceptionsManagerSpecJSI_reportSoftException(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, VoidKind, \\"reportSoftException\\", \\"(Ljava/lang/String;Lcom/facebook/react/bridge/ReadableArray;D)V\\", args, count, cachedMethodId); -} - -static facebook::jsi::Value __hostFunction_NativeExceptionsManagerSpecJSI_reportException(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, VoidKind, \\"reportException\\", \\"(Lcom/facebook/react/bridge/ReadableMap;)V\\", args, count, cachedMethodId); -} - -static facebook::jsi::Value __hostFunction_NativeExceptionsManagerSpecJSI_updateExceptionMessage(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, VoidKind, \\"updateExceptionMessage\\", \\"(Ljava/lang/String;Lcom/facebook/react/bridge/ReadableArray;D)V\\", args, count, cachedMethodId); -} - -static facebook::jsi::Value __hostFunction_NativeExceptionsManagerSpecJSI_dismissRedbox(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, VoidKind, \\"dismissRedbox\\", \\"()V\\", args, count, cachedMethodId); -} - -NativeExceptionsManagerSpecJSI::NativeExceptionsManagerSpecJSI(const JavaTurboModule::InitParams ¶ms) - : JavaTurboModule(params) { - methodMap_[\\"reportFatalException\\"] = MethodMetadata {3, __hostFunction_NativeExceptionsManagerSpecJSI_reportFatalException}; - methodMap_[\\"reportSoftException\\"] = MethodMetadata {3, __hostFunction_NativeExceptionsManagerSpecJSI_reportSoftException}; - methodMap_[\\"reportException\\"] = MethodMetadata {1, __hostFunction_NativeExceptionsManagerSpecJSI_reportException}; - methodMap_[\\"updateExceptionMessage\\"] = MethodMetadata {3, __hostFunction_NativeExceptionsManagerSpecJSI_updateExceptionMessage}; - methodMap_[\\"dismissRedbox\\"] = MethodMetadata {0, __hostFunction_NativeExceptionsManagerSpecJSI_dismissRedbox}; -} - -std::shared_ptr real_module_example_ModuleProvider(const std::string &moduleName, const JavaTurboModule::InitParams ¶ms) { - if (moduleName == \\"CameraRollManager\\") { - return std::make_shared(params); - } - if (moduleName == \\"ExceptionsManager\\") { - return std::make_shared(params); - } - return nullptr; -} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateModuleJniCpp can generate fixture simple_native_modules 1`] = ` -Map { - "jni/simple_native_modules-generated.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleJniCpp.js - */ - -#include \\"simple_native_modules.h\\" - -namespace facebook { -namespace react { - -static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getConstants(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, ObjectKind, \\"getConstants\\", \\"()Ljava/util/Map;\\", args, count, cachedMethodId); -} - -static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_voidFunc(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, VoidKind, \\"voidFunc\\", \\"()V\\", args, count, cachedMethodId); -} - -static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getBool(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, BooleanKind, \\"getBool\\", \\"(Z)Z\\", args, count, cachedMethodId); -} - -static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getNumber(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, NumberKind, \\"getNumber\\", \\"(D)D\\", args, count, cachedMethodId); -} - -static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getString(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, StringKind, \\"getString\\", \\"(Ljava/lang/String;)Ljava/lang/String;\\", args, count, cachedMethodId); -} - -static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getArray(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, ArrayKind, \\"getArray\\", \\"(Lcom/facebook/react/bridge/ReadableArray;)Lcom/facebook/react/bridge/WritableArray;\\", args, count, cachedMethodId); -} - -static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getObject(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, ObjectKind, \\"getObject\\", \\"(Lcom/facebook/react/bridge/ReadableMap;)Lcom/facebook/react/bridge/WritableMap;\\", args, count, cachedMethodId); -} - -static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getRootTag(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, NumberKind, \\"getRootTag\\", \\"(D)D\\", args, count, cachedMethodId); -} - -static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getValue(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, ObjectKind, \\"getValue\\", \\"(DLjava/lang/String;Lcom/facebook/react/bridge/ReadableMap;)Lcom/facebook/react/bridge/WritableMap;\\", args, count, cachedMethodId); -} - -static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getValueWithCallback(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, VoidKind, \\"getValueWithCallback\\", \\"(Lcom/facebook/react/bridge/Callback;)V\\", args, count, cachedMethodId); -} - -static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getValueWithPromise(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, PromiseKind, \\"getValueWithPromise\\", \\"(ZLcom/facebook/react/bridge/Promise;)V\\", args, count, cachedMethodId); -} - -static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getValueWithOptionalArg(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, PromiseKind, \\"getValueWithOptionalArg\\", \\"(Lcom/facebook/react/bridge/ReadableMap;Lcom/facebook/react/bridge/Promise;)V\\", args, count, cachedMethodId); -} - -static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getEnums(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, StringKind, \\"getEnums\\", \\"(DDLjava/lang/String;)Ljava/lang/String;\\", args, count, cachedMethodId); -} - -NativeSampleTurboModuleSpecJSI::NativeSampleTurboModuleSpecJSI(const JavaTurboModule::InitParams ¶ms) - : JavaTurboModule(params) { - methodMap_[\\"getConstants\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleSpecJSI_getConstants}; - methodMap_[\\"voidFunc\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleSpecJSI_voidFunc}; - methodMap_[\\"getBool\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getBool}; - methodMap_[\\"getNumber\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getNumber}; - methodMap_[\\"getString\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getString}; - methodMap_[\\"getArray\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getArray}; - methodMap_[\\"getObject\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getObject}; - methodMap_[\\"getRootTag\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getRootTag}; - methodMap_[\\"getValue\\"] = MethodMetadata {3, __hostFunction_NativeSampleTurboModuleSpecJSI_getValue}; - methodMap_[\\"getValueWithCallback\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getValueWithCallback}; - methodMap_[\\"getValueWithPromise\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getValueWithPromise}; - methodMap_[\\"getValueWithOptionalArg\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getValueWithOptionalArg}; - methodMap_[\\"getEnums\\"] = MethodMetadata {3, __hostFunction_NativeSampleTurboModuleSpecJSI_getEnums}; -} - -std::shared_ptr simple_native_modules_ModuleProvider(const std::string &moduleName, const JavaTurboModule::InitParams ¶ms) { - if (moduleName == \\"SampleTurboModule\\") { - return std::make_shared(params); - } - return nullptr; -} - -} // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateModuleJniCpp can generate fixture two_modules_different_files 1`] = ` -Map { - "jni/two_modules_different_files-generated.cpp" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleJniCpp.js - */ - -#include \\"two_modules_different_files.h\\" - -namespace facebook { -namespace react { - -static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_voidFunc(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, VoidKind, \\"voidFunc\\", \\"()V\\", args, count, cachedMethodId); -} - -NativeSampleTurboModuleSpecJSI::NativeSampleTurboModuleSpecJSI(const JavaTurboModule::InitParams ¶ms) - : JavaTurboModule(params) { - methodMap_[\\"voidFunc\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleSpecJSI_voidFunc}; -} - - -static facebook::jsi::Value __hostFunction_NativeSampleTurboModule2SpecJSI_voidFunc(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule).invokeJavaMethod(rt, VoidKind, \\"voidFunc\\", \\"()V\\", args, count, cachedMethodId); -} - -NativeSampleTurboModule2SpecJSI::NativeSampleTurboModule2SpecJSI(const JavaTurboModule::InitParams ¶ms) - : JavaTurboModule(params) { - methodMap_[\\"voidFunc\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModule2SpecJSI_voidFunc}; -} - -std::shared_ptr two_modules_different_files_ModuleProvider(const std::string &moduleName, const JavaTurboModule::InitParams ¶ms) { - if (moduleName == \\"SampleTurboModule\\") { - return std::make_shared(params); - } - if (moduleName == \\"SampleTurboModule2\\") { - return std::make_shared(params); - } - return nullptr; -} - -} // namespace react -} // namespace facebook -", -} -`; diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJniH-test.js.snap b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJniH-test.js.snap deleted file mode 100644 index 26467d5eb841..000000000000 --- a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJniH-test.js.snap +++ /dev/null @@ -1,914 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GenerateModuleJniH can generate fixture SampleWithUppercaseName 1`] = ` -Map { - "jni/SampleWithUppercaseName.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleJniH.js - */ - -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -/** - * JNI C++ class for module 'NativeSampleTurboModule' - */ -class JSI_EXPORT NativeSampleTurboModuleSpecJSI : public JavaTurboModule { -public: - NativeSampleTurboModuleSpecJSI(const JavaTurboModule::InitParams ¶ms); -}; - - -JSI_EXPORT -std::shared_ptr SampleWithUppercaseName_ModuleProvider(const std::string &moduleName, const JavaTurboModule::InitParams ¶ms); - -} // namespace react -} // namespace facebook -", - "jni/Android.mk" => "# 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. - -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE := react_codegen_SampleWithUppercaseName - -LOCAL_C_INCLUDES := $(LOCAL_PATH) - -LOCAL_SRC_FILES := $(wildcard $(LOCAL_PATH)/*.cpp) $(wildcard $(LOCAL_PATH)/react/renderer/components/SampleWithUppercaseName/*.cpp) -LOCAL_SRC_FILES := $(subst $(LOCAL_PATH)/,,$(LOCAL_SRC_FILES)) - -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) $(LOCAL_PATH)/react/renderer/components/SampleWithUppercaseName - -LOCAL_SHARED_LIBRARIES := libfbjni libfolly_runtime libglog libjsi libreact_codegen_rncore libreact_debug libreact_nativemodule_core libreact_render_core libreact_render_debug libreact_render_graphics libreact_render_imagemanager libreact_render_mapbuffer librrc_image librrc_view libturbomodulejsijni libyoga - -LOCAL_CFLAGS := \\\\ - -DLOG_TAG=\\\\\\"ReactNative\\\\\\" - -LOCAL_CFLAGS += -fexceptions -frtti -std=c++17 -Wall - -include $(BUILD_SHARED_LIBRARY) -", - "jni/CMakeLists.txt" => "# 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. - -cmake_minimum_required(VERSION 3.13) -set(CMAKE_VERBOSE_MAKEFILE on) - -file(GLOB react_codegen_SRCS CONFIGURE_DEPENDS *.cpp react/renderer/components/SampleWithUppercaseName/*.cpp) - -add_library( - react_codegen_SampleWithUppercaseName - SHARED - \${react_codegen_SRCS} -) - -target_include_directories(react_codegen_SampleWithUppercaseName PUBLIC . react/renderer/components/SampleWithUppercaseName) - -target_link_libraries( - react_codegen_SampleWithUppercaseName - fbjni - folly_runtime - glog - jsi - react_codegen_rncore - react_debug - react_nativemodule_core - react_render_core - react_render_debug - react_render_graphics - react_render_imagemanager - rrc_image - rrc_view - turbomodulejsijni - yoga -) - -target_compile_options( - react_codegen_SampleWithUppercaseName - PRIVATE - -DLOG_TAG=\\\\\\"ReactNative\\\\\\" - -fexceptions - -frtti - -std=c++17 - -Wall -) -", -} -`; - -exports[`GenerateModuleJniH can generate fixture complex_objects 1`] = ` -Map { - "jni/complex_objects.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleJniH.js - */ - -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -/** - * JNI C++ class for module 'NativeSampleTurboModule' - */ -class JSI_EXPORT NativeSampleTurboModuleSpecJSI : public JavaTurboModule { -public: - NativeSampleTurboModuleSpecJSI(const JavaTurboModule::InitParams ¶ms); -}; - - -JSI_EXPORT -std::shared_ptr complex_objects_ModuleProvider(const std::string &moduleName, const JavaTurboModule::InitParams ¶ms); - -} // namespace react -} // namespace facebook -", - "jni/Android.mk" => "# 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. - -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE := react_codegen_complex_objects - -LOCAL_C_INCLUDES := $(LOCAL_PATH) - -LOCAL_SRC_FILES := $(wildcard $(LOCAL_PATH)/*.cpp) $(wildcard $(LOCAL_PATH)/react/renderer/components/complex_objects/*.cpp) -LOCAL_SRC_FILES := $(subst $(LOCAL_PATH)/,,$(LOCAL_SRC_FILES)) - -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) $(LOCAL_PATH)/react/renderer/components/complex_objects - -LOCAL_SHARED_LIBRARIES := libfbjni libfolly_runtime libglog libjsi libreact_codegen_rncore libreact_debug libreact_nativemodule_core libreact_render_core libreact_render_debug libreact_render_graphics libreact_render_imagemanager libreact_render_mapbuffer librrc_image librrc_view libturbomodulejsijni libyoga - -LOCAL_CFLAGS := \\\\ - -DLOG_TAG=\\\\\\"ReactNative\\\\\\" - -LOCAL_CFLAGS += -fexceptions -frtti -std=c++17 -Wall - -include $(BUILD_SHARED_LIBRARY) -", - "jni/CMakeLists.txt" => "# 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. - -cmake_minimum_required(VERSION 3.13) -set(CMAKE_VERBOSE_MAKEFILE on) - -file(GLOB react_codegen_SRCS CONFIGURE_DEPENDS *.cpp react/renderer/components/complex_objects/*.cpp) - -add_library( - react_codegen_complex_objects - SHARED - \${react_codegen_SRCS} -) - -target_include_directories(react_codegen_complex_objects PUBLIC . react/renderer/components/complex_objects) - -target_link_libraries( - react_codegen_complex_objects - fbjni - folly_runtime - glog - jsi - react_codegen_rncore - react_debug - react_nativemodule_core - react_render_core - react_render_debug - react_render_graphics - react_render_imagemanager - rrc_image - rrc_view - turbomodulejsijni - yoga -) - -target_compile_options( - react_codegen_complex_objects - PRIVATE - -DLOG_TAG=\\\\\\"ReactNative\\\\\\" - -fexceptions - -frtti - -std=c++17 - -Wall -) -", -} -`; - -exports[`GenerateModuleJniH can generate fixture cxx_only_native_modules 1`] = ` -Map { - "jni/cxx_only_native_modules.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleJniH.js - */ - -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - - - -JSI_EXPORT -std::shared_ptr cxx_only_native_modules_ModuleProvider(const std::string &moduleName, const JavaTurboModule::InitParams ¶ms); - -} // namespace react -} // namespace facebook -", - "jni/Android.mk" => "# 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. - -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE := react_codegen_cxx_only_native_modules - -LOCAL_C_INCLUDES := $(LOCAL_PATH) - -LOCAL_SRC_FILES := $(wildcard $(LOCAL_PATH)/*.cpp) $(wildcard $(LOCAL_PATH)/react/renderer/components/cxx_only_native_modules/*.cpp) -LOCAL_SRC_FILES := $(subst $(LOCAL_PATH)/,,$(LOCAL_SRC_FILES)) - -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) $(LOCAL_PATH)/react/renderer/components/cxx_only_native_modules - -LOCAL_SHARED_LIBRARIES := libfbjni libfolly_runtime libglog libjsi libreact_codegen_rncore libreact_debug libreact_nativemodule_core libreact_render_core libreact_render_debug libreact_render_graphics libreact_render_imagemanager libreact_render_mapbuffer librrc_image librrc_view libturbomodulejsijni libyoga - -LOCAL_CFLAGS := \\\\ - -DLOG_TAG=\\\\\\"ReactNative\\\\\\" - -LOCAL_CFLAGS += -fexceptions -frtti -std=c++17 -Wall - -include $(BUILD_SHARED_LIBRARY) -", - "jni/CMakeLists.txt" => "# 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. - -cmake_minimum_required(VERSION 3.13) -set(CMAKE_VERBOSE_MAKEFILE on) - -file(GLOB react_codegen_SRCS CONFIGURE_DEPENDS *.cpp react/renderer/components/cxx_only_native_modules/*.cpp) - -add_library( - react_codegen_cxx_only_native_modules - SHARED - \${react_codegen_SRCS} -) - -target_include_directories(react_codegen_cxx_only_native_modules PUBLIC . react/renderer/components/cxx_only_native_modules) - -target_link_libraries( - react_codegen_cxx_only_native_modules - fbjni - folly_runtime - glog - jsi - react_codegen_rncore - react_debug - react_nativemodule_core - react_render_core - react_render_debug - react_render_graphics - react_render_imagemanager - rrc_image - rrc_view - turbomodulejsijni - yoga -) - -target_compile_options( - react_codegen_cxx_only_native_modules - PRIVATE - -DLOG_TAG=\\\\\\"ReactNative\\\\\\" - -fexceptions - -frtti - -std=c++17 - -Wall -) -", -} -`; - -exports[`GenerateModuleJniH can generate fixture empty_native_modules 1`] = ` -Map { - "jni/empty_native_modules.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleJniH.js - */ - -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -/** - * JNI C++ class for module 'NativeSampleTurboModule' - */ -class JSI_EXPORT NativeSampleTurboModuleSpecJSI : public JavaTurboModule { -public: - NativeSampleTurboModuleSpecJSI(const JavaTurboModule::InitParams ¶ms); -}; - - -JSI_EXPORT -std::shared_ptr empty_native_modules_ModuleProvider(const std::string &moduleName, const JavaTurboModule::InitParams ¶ms); - -} // namespace react -} // namespace facebook -", - "jni/Android.mk" => "# 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. - -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE := react_codegen_empty_native_modules - -LOCAL_C_INCLUDES := $(LOCAL_PATH) - -LOCAL_SRC_FILES := $(wildcard $(LOCAL_PATH)/*.cpp) $(wildcard $(LOCAL_PATH)/react/renderer/components/empty_native_modules/*.cpp) -LOCAL_SRC_FILES := $(subst $(LOCAL_PATH)/,,$(LOCAL_SRC_FILES)) - -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) $(LOCAL_PATH)/react/renderer/components/empty_native_modules - -LOCAL_SHARED_LIBRARIES := libfbjni libfolly_runtime libglog libjsi libreact_codegen_rncore libreact_debug libreact_nativemodule_core libreact_render_core libreact_render_debug libreact_render_graphics libreact_render_imagemanager libreact_render_mapbuffer librrc_image librrc_view libturbomodulejsijni libyoga - -LOCAL_CFLAGS := \\\\ - -DLOG_TAG=\\\\\\"ReactNative\\\\\\" - -LOCAL_CFLAGS += -fexceptions -frtti -std=c++17 -Wall - -include $(BUILD_SHARED_LIBRARY) -", - "jni/CMakeLists.txt" => "# 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. - -cmake_minimum_required(VERSION 3.13) -set(CMAKE_VERBOSE_MAKEFILE on) - -file(GLOB react_codegen_SRCS CONFIGURE_DEPENDS *.cpp react/renderer/components/empty_native_modules/*.cpp) - -add_library( - react_codegen_empty_native_modules - SHARED - \${react_codegen_SRCS} -) - -target_include_directories(react_codegen_empty_native_modules PUBLIC . react/renderer/components/empty_native_modules) - -target_link_libraries( - react_codegen_empty_native_modules - fbjni - folly_runtime - glog - jsi - react_codegen_rncore - react_debug - react_nativemodule_core - react_render_core - react_render_debug - react_render_graphics - react_render_imagemanager - rrc_image - rrc_view - turbomodulejsijni - yoga -) - -target_compile_options( - react_codegen_empty_native_modules - PRIVATE - -DLOG_TAG=\\\\\\"ReactNative\\\\\\" - -fexceptions - -frtti - -std=c++17 - -Wall -) -", -} -`; - -exports[`GenerateModuleJniH can generate fixture native_modules_with_type_aliases 1`] = ` -Map { - "jni/native_modules_with_type_aliases.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleJniH.js - */ - -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -/** - * JNI C++ class for module 'AliasTurboModule' - */ -class JSI_EXPORT AliasTurboModuleSpecJSI : public JavaTurboModule { -public: - AliasTurboModuleSpecJSI(const JavaTurboModule::InitParams ¶ms); -}; - - -JSI_EXPORT -std::shared_ptr native_modules_with_type_aliases_ModuleProvider(const std::string &moduleName, const JavaTurboModule::InitParams ¶ms); - -} // namespace react -} // namespace facebook -", - "jni/Android.mk" => "# 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. - -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE := react_codegen_native_modules_with_type_aliases - -LOCAL_C_INCLUDES := $(LOCAL_PATH) - -LOCAL_SRC_FILES := $(wildcard $(LOCAL_PATH)/*.cpp) $(wildcard $(LOCAL_PATH)/react/renderer/components/native_modules_with_type_aliases/*.cpp) -LOCAL_SRC_FILES := $(subst $(LOCAL_PATH)/,,$(LOCAL_SRC_FILES)) - -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) $(LOCAL_PATH)/react/renderer/components/native_modules_with_type_aliases - -LOCAL_SHARED_LIBRARIES := libfbjni libfolly_runtime libglog libjsi libreact_codegen_rncore libreact_debug libreact_nativemodule_core libreact_render_core libreact_render_debug libreact_render_graphics libreact_render_imagemanager libreact_render_mapbuffer librrc_image librrc_view libturbomodulejsijni libyoga - -LOCAL_CFLAGS := \\\\ - -DLOG_TAG=\\\\\\"ReactNative\\\\\\" - -LOCAL_CFLAGS += -fexceptions -frtti -std=c++17 -Wall - -include $(BUILD_SHARED_LIBRARY) -", - "jni/CMakeLists.txt" => "# 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. - -cmake_minimum_required(VERSION 3.13) -set(CMAKE_VERBOSE_MAKEFILE on) - -file(GLOB react_codegen_SRCS CONFIGURE_DEPENDS *.cpp react/renderer/components/native_modules_with_type_aliases/*.cpp) - -add_library( - react_codegen_native_modules_with_type_aliases - SHARED - \${react_codegen_SRCS} -) - -target_include_directories(react_codegen_native_modules_with_type_aliases PUBLIC . react/renderer/components/native_modules_with_type_aliases) - -target_link_libraries( - react_codegen_native_modules_with_type_aliases - fbjni - folly_runtime - glog - jsi - react_codegen_rncore - react_debug - react_nativemodule_core - react_render_core - react_render_debug - react_render_graphics - react_render_imagemanager - rrc_image - rrc_view - turbomodulejsijni - yoga -) - -target_compile_options( - react_codegen_native_modules_with_type_aliases - PRIVATE - -DLOG_TAG=\\\\\\"ReactNative\\\\\\" - -fexceptions - -frtti - -std=c++17 - -Wall -) -", -} -`; - -exports[`GenerateModuleJniH can generate fixture real_module_example 1`] = ` -Map { - "jni/real_module_example.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleJniH.js - */ - -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -/** - * JNI C++ class for module 'NativeCameraRollManager' - */ -class JSI_EXPORT NativeCameraRollManagerSpecJSI : public JavaTurboModule { -public: - NativeCameraRollManagerSpecJSI(const JavaTurboModule::InitParams ¶ms); -}; - -/** - * JNI C++ class for module 'NativeExceptionsManager' - */ -class JSI_EXPORT NativeExceptionsManagerSpecJSI : public JavaTurboModule { -public: - NativeExceptionsManagerSpecJSI(const JavaTurboModule::InitParams ¶ms); -}; - - -JSI_EXPORT -std::shared_ptr real_module_example_ModuleProvider(const std::string &moduleName, const JavaTurboModule::InitParams ¶ms); - -} // namespace react -} // namespace facebook -", - "jni/Android.mk" => "# 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. - -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE := react_codegen_real_module_example - -LOCAL_C_INCLUDES := $(LOCAL_PATH) - -LOCAL_SRC_FILES := $(wildcard $(LOCAL_PATH)/*.cpp) $(wildcard $(LOCAL_PATH)/react/renderer/components/real_module_example/*.cpp) -LOCAL_SRC_FILES := $(subst $(LOCAL_PATH)/,,$(LOCAL_SRC_FILES)) - -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) $(LOCAL_PATH)/react/renderer/components/real_module_example - -LOCAL_SHARED_LIBRARIES := libfbjni libfolly_runtime libglog libjsi libreact_codegen_rncore libreact_debug libreact_nativemodule_core libreact_render_core libreact_render_debug libreact_render_graphics libreact_render_imagemanager libreact_render_mapbuffer librrc_image librrc_view libturbomodulejsijni libyoga - -LOCAL_CFLAGS := \\\\ - -DLOG_TAG=\\\\\\"ReactNative\\\\\\" - -LOCAL_CFLAGS += -fexceptions -frtti -std=c++17 -Wall - -include $(BUILD_SHARED_LIBRARY) -", - "jni/CMakeLists.txt" => "# 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. - -cmake_minimum_required(VERSION 3.13) -set(CMAKE_VERBOSE_MAKEFILE on) - -file(GLOB react_codegen_SRCS CONFIGURE_DEPENDS *.cpp react/renderer/components/real_module_example/*.cpp) - -add_library( - react_codegen_real_module_example - SHARED - \${react_codegen_SRCS} -) - -target_include_directories(react_codegen_real_module_example PUBLIC . react/renderer/components/real_module_example) - -target_link_libraries( - react_codegen_real_module_example - fbjni - folly_runtime - glog - jsi - react_codegen_rncore - react_debug - react_nativemodule_core - react_render_core - react_render_debug - react_render_graphics - react_render_imagemanager - rrc_image - rrc_view - turbomodulejsijni - yoga -) - -target_compile_options( - react_codegen_real_module_example - PRIVATE - -DLOG_TAG=\\\\\\"ReactNative\\\\\\" - -fexceptions - -frtti - -std=c++17 - -Wall -) -", -} -`; - -exports[`GenerateModuleJniH can generate fixture simple_native_modules 1`] = ` -Map { - "jni/simple_native_modules.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleJniH.js - */ - -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -/** - * JNI C++ class for module 'NativeSampleTurboModule' - */ -class JSI_EXPORT NativeSampleTurboModuleSpecJSI : public JavaTurboModule { -public: - NativeSampleTurboModuleSpecJSI(const JavaTurboModule::InitParams ¶ms); -}; - - -JSI_EXPORT -std::shared_ptr simple_native_modules_ModuleProvider(const std::string &moduleName, const JavaTurboModule::InitParams ¶ms); - -} // namespace react -} // namespace facebook -", - "jni/Android.mk" => "# 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. - -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE := react_codegen_simple_native_modules - -LOCAL_C_INCLUDES := $(LOCAL_PATH) - -LOCAL_SRC_FILES := $(wildcard $(LOCAL_PATH)/*.cpp) $(wildcard $(LOCAL_PATH)/react/renderer/components/simple_native_modules/*.cpp) -LOCAL_SRC_FILES := $(subst $(LOCAL_PATH)/,,$(LOCAL_SRC_FILES)) - -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) $(LOCAL_PATH)/react/renderer/components/simple_native_modules - -LOCAL_SHARED_LIBRARIES := libfbjni libfolly_runtime libglog libjsi libreact_codegen_rncore libreact_debug libreact_nativemodule_core libreact_render_core libreact_render_debug libreact_render_graphics libreact_render_imagemanager libreact_render_mapbuffer librrc_image librrc_view libturbomodulejsijni libyoga - -LOCAL_CFLAGS := \\\\ - -DLOG_TAG=\\\\\\"ReactNative\\\\\\" - -LOCAL_CFLAGS += -fexceptions -frtti -std=c++17 -Wall - -include $(BUILD_SHARED_LIBRARY) -", - "jni/CMakeLists.txt" => "# 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. - -cmake_minimum_required(VERSION 3.13) -set(CMAKE_VERBOSE_MAKEFILE on) - -file(GLOB react_codegen_SRCS CONFIGURE_DEPENDS *.cpp react/renderer/components/simple_native_modules/*.cpp) - -add_library( - react_codegen_simple_native_modules - SHARED - \${react_codegen_SRCS} -) - -target_include_directories(react_codegen_simple_native_modules PUBLIC . react/renderer/components/simple_native_modules) - -target_link_libraries( - react_codegen_simple_native_modules - fbjni - folly_runtime - glog - jsi - react_codegen_rncore - react_debug - react_nativemodule_core - react_render_core - react_render_debug - react_render_graphics - react_render_imagemanager - rrc_image - rrc_view - turbomodulejsijni - yoga -) - -target_compile_options( - react_codegen_simple_native_modules - PRIVATE - -DLOG_TAG=\\\\\\"ReactNative\\\\\\" - -fexceptions - -frtti - -std=c++17 - -Wall -) -", -} -`; - -exports[`GenerateModuleJniH can generate fixture two_modules_different_files 1`] = ` -Map { - "jni/two_modules_different_files.h" => " -/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleJniH.js - */ - -#pragma once - -#include -#include -#include - -namespace facebook { -namespace react { - -/** - * JNI C++ class for module 'NativeSampleTurboModule' - */ -class JSI_EXPORT NativeSampleTurboModuleSpecJSI : public JavaTurboModule { -public: - NativeSampleTurboModuleSpecJSI(const JavaTurboModule::InitParams ¶ms); -}; - -/** - * JNI C++ class for module 'NativeSampleTurboModule2' - */ -class JSI_EXPORT NativeSampleTurboModule2SpecJSI : public JavaTurboModule { -public: - NativeSampleTurboModule2SpecJSI(const JavaTurboModule::InitParams ¶ms); -}; - - -JSI_EXPORT -std::shared_ptr two_modules_different_files_ModuleProvider(const std::string &moduleName, const JavaTurboModule::InitParams ¶ms); - -} // namespace react -} // namespace facebook -", - "jni/Android.mk" => "# 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. - -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE := react_codegen_two_modules_different_files - -LOCAL_C_INCLUDES := $(LOCAL_PATH) - -LOCAL_SRC_FILES := $(wildcard $(LOCAL_PATH)/*.cpp) $(wildcard $(LOCAL_PATH)/react/renderer/components/two_modules_different_files/*.cpp) -LOCAL_SRC_FILES := $(subst $(LOCAL_PATH)/,,$(LOCAL_SRC_FILES)) - -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) $(LOCAL_PATH)/react/renderer/components/two_modules_different_files - -LOCAL_SHARED_LIBRARIES := libfbjni libfolly_runtime libglog libjsi libreact_codegen_rncore libreact_debug libreact_nativemodule_core libreact_render_core libreact_render_debug libreact_render_graphics libreact_render_imagemanager libreact_render_mapbuffer librrc_image librrc_view libturbomodulejsijni libyoga - -LOCAL_CFLAGS := \\\\ - -DLOG_TAG=\\\\\\"ReactNative\\\\\\" - -LOCAL_CFLAGS += -fexceptions -frtti -std=c++17 -Wall - -include $(BUILD_SHARED_LIBRARY) -", - "jni/CMakeLists.txt" => "# 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. - -cmake_minimum_required(VERSION 3.13) -set(CMAKE_VERBOSE_MAKEFILE on) - -file(GLOB react_codegen_SRCS CONFIGURE_DEPENDS *.cpp react/renderer/components/two_modules_different_files/*.cpp) - -add_library( - react_codegen_two_modules_different_files - SHARED - \${react_codegen_SRCS} -) - -target_include_directories(react_codegen_two_modules_different_files PUBLIC . react/renderer/components/two_modules_different_files) - -target_link_libraries( - react_codegen_two_modules_different_files - fbjni - folly_runtime - glog - jsi - react_codegen_rncore - react_debug - react_nativemodule_core - react_render_core - react_render_debug - react_render_graphics - react_render_imagemanager - rrc_image - rrc_view - turbomodulejsijni - yoga -) - -target_compile_options( - react_codegen_two_modules_different_files - PRIVATE - -DLOG_TAG=\\\\\\"ReactNative\\\\\\" - -fexceptions - -frtti - -std=c++17 - -Wall -) -", -} -`; diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleMm-test.js.snap b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleMm-test.js.snap deleted file mode 100644 index 867858ae3252..000000000000 --- a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleMm-test.js.snap +++ /dev/null @@ -1,546 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`GenerateModuleMm can generate fixture SampleWithUppercaseName 1`] = ` -Map { - "SampleWithUppercaseName-generated.mm" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleObjCpp - * - * We create an umbrella header (and corresponding implementation) here since - * Cxx compilation in BUCK has a limitation: source-code producing genrule()s - * must have a single output. More files => more genrule()s => slower builds. - */ - -#import \\"SampleWithUppercaseName.h\\" - - -namespace facebook { - namespace react { - - - NativeSampleTurboModuleSpecJSI::NativeSampleTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms) - : ObjCTurboModule(params) { - - } - } // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateModuleMm can generate fixture complex_objects 1`] = ` -Map { - "complex_objects-generated.mm" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleObjCpp - * - * We create an umbrella header (and corresponding implementation) here since - * Cxx compilation in BUCK has a limitation: source-code producing genrule()s - * must have a single output. More files => more genrule()s => slower builds. - */ - -#import \\"complex_objects.h\\" - -@implementation RCTCxxConvert (NativeSampleTurboModule_SpecDifficultAE) -+ (RCTManagedPointer *)JS_NativeSampleTurboModule_SpecDifficultAE:(id)json -{ - return facebook::react::managedPointer(json); -} -@end -@implementation RCTCxxConvert (NativeSampleTurboModule_SpecDifficultA) -+ (RCTManagedPointer *)JS_NativeSampleTurboModule_SpecDifficultA:(id)json -{ - return facebook::react::managedPointer(json); -} -@end -@implementation RCTCxxConvert (NativeSampleTurboModule_SpecOptionalsAOptionalObjectProperty) -+ (RCTManagedPointer *)JS_NativeSampleTurboModule_SpecOptionalsAOptionalObjectProperty:(id)json -{ - return facebook::react::managedPointer(json); -} -@end -@implementation RCTCxxConvert (NativeSampleTurboModule_SpecOptionalsA) -+ (RCTManagedPointer *)JS_NativeSampleTurboModule_SpecOptionalsA:(id)json -{ - return facebook::react::managedPointer(json); -} -@end -@implementation RCTCxxConvert (NativeSampleTurboModule_SpecGetArraysOptionsArrayOfObjectsElement) -+ (RCTManagedPointer *)JS_NativeSampleTurboModule_SpecGetArraysOptionsArrayOfObjectsElement:(id)json -{ - return facebook::react::managedPointer(json); -} -@end -@implementation RCTCxxConvert (NativeSampleTurboModule_SpecGetArraysOptions) -+ (RCTManagedPointer *)JS_NativeSampleTurboModule_SpecGetArraysOptions:(id)json -{ - return facebook::react::managedPointer(json); -} -@end -namespace facebook { - namespace react { - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_difficult(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"difficult\\", @selector(difficult:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_optionals(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, VoidKind, \\"optionals\\", @selector(optionals:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_optionalMethod(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, VoidKind, \\"optionalMethod\\", @selector(optionalMethod:callback:extras:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getArrays(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, VoidKind, \\"getArrays\\", @selector(getArrays:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getNullableObject(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getNullableObject\\", @selector(getNullableObject), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getNullableGenericObject(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getNullableGenericObject\\", @selector(getNullableGenericObject), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getNullableArray(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ArrayKind, \\"getNullableArray\\", @selector(getNullableArray), args, count); - } - - NativeSampleTurboModuleSpecJSI::NativeSampleTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms) - : ObjCTurboModule(params) { - - methodMap_[\\"difficult\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_difficult}; - setMethodArgConversionSelector(@\\"difficult\\", 0, @\\"JS_NativeSampleTurboModule_SpecDifficultA:\\"); - - methodMap_[\\"optionals\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_optionals}; - setMethodArgConversionSelector(@\\"optionals\\", 0, @\\"JS_NativeSampleTurboModule_SpecOptionalsA:\\"); - - methodMap_[\\"optionalMethod\\"] = MethodMetadata {3, __hostFunction_NativeSampleTurboModuleSpecJSI_optionalMethod}; - - - methodMap_[\\"getArrays\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getArrays}; - setMethodArgConversionSelector(@\\"getArrays\\", 0, @\\"JS_NativeSampleTurboModule_SpecGetArraysOptions:\\"); - - methodMap_[\\"getNullableObject\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleSpecJSI_getNullableObject}; - - - methodMap_[\\"getNullableGenericObject\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleSpecJSI_getNullableGenericObject}; - - - methodMap_[\\"getNullableArray\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleSpecJSI_getNullableArray}; - - } - } // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateModuleMm can generate fixture cxx_only_native_modules 1`] = ` -Map { - "cxx_only_native_modules-generated.mm" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleObjCpp - * - * We create an umbrella header (and corresponding implementation) here since - * Cxx compilation in BUCK has a limitation: source-code producing genrule()s - * must have a single output. More files => more genrule()s => slower builds. - */ - -#import \\"cxx_only_native_modules.h\\" - - -", -} -`; - -exports[`GenerateModuleMm can generate fixture empty_native_modules 1`] = ` -Map { - "empty_native_modules-generated.mm" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleObjCpp - * - * We create an umbrella header (and corresponding implementation) here since - * Cxx compilation in BUCK has a limitation: source-code producing genrule()s - * must have a single output. More files => more genrule()s => slower builds. - */ - -#import \\"empty_native_modules.h\\" - - -namespace facebook { - namespace react { - - - NativeSampleTurboModuleSpecJSI::NativeSampleTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms) - : ObjCTurboModule(params) { - - } - } // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateModuleMm can generate fixture native_modules_with_type_aliases 1`] = ` -Map { - "native_modules_with_type_aliases-generated.mm" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleObjCpp - * - * We create an umbrella header (and corresponding implementation) here since - * Cxx compilation in BUCK has a limitation: source-code producing genrule()s - * must have a single output. More files => more genrule()s => slower builds. - */ - -#import \\"native_modules_with_type_aliases.h\\" - -@implementation RCTCxxConvert (AliasTurboModule_OptionsOffset) -+ (RCTManagedPointer *)JS_AliasTurboModule_OptionsOffset:(id)json -{ - return facebook::react::managedPointer(json); -} -@end -@implementation RCTCxxConvert (AliasTurboModule_OptionsSize) -+ (RCTManagedPointer *)JS_AliasTurboModule_OptionsSize:(id)json -{ - return facebook::react::managedPointer(json); -} -@end -@implementation RCTCxxConvert (AliasTurboModule_OptionsDisplaySize) -+ (RCTManagedPointer *)JS_AliasTurboModule_OptionsDisplaySize:(id)json -{ - return facebook::react::managedPointer(json); -} -@end -@implementation RCTCxxConvert (AliasTurboModule_Options) -+ (RCTManagedPointer *)JS_AliasTurboModule_Options:(id)json -{ - return facebook::react::managedPointer(json); -} -@end -namespace facebook { - namespace react { - - static facebook::jsi::Value __hostFunction_AliasTurboModuleSpecJSI_cropImage(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, VoidKind, \\"cropImage\\", @selector(cropImage:), args, count); - } - - AliasTurboModuleSpecJSI::AliasTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms) - : ObjCTurboModule(params) { - - methodMap_[\\"cropImage\\"] = MethodMetadata {1, __hostFunction_AliasTurboModuleSpecJSI_cropImage}; - setMethodArgConversionSelector(@\\"cropImage\\", 0, @\\"JS_AliasTurboModule_Options:\\"); - } - } // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateModuleMm can generate fixture real_module_example 1`] = ` -Map { - "real_module_example-generated.mm" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleObjCpp - * - * We create an umbrella header (and corresponding implementation) here since - * Cxx compilation in BUCK has a limitation: source-code producing genrule()s - * must have a single output. More files => more genrule()s => slower builds. - */ - -#import \\"real_module_example.h\\" - -@implementation RCTCxxConvert (NativeCameraRollManager_GetPhotosParams) -+ (RCTManagedPointer *)JS_NativeCameraRollManager_GetPhotosParams:(id)json -{ - return facebook::react::managedPointer(json); -} -@end -namespace facebook { - namespace react { - - static facebook::jsi::Value __hostFunction_NativeCameraRollManagerSpecJSI_getPhotos(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, PromiseKind, \\"getPhotos\\", @selector(getPhotos:resolve:reject:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeCameraRollManagerSpecJSI_saveToCameraRoll(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, PromiseKind, \\"saveToCameraRoll\\", @selector(saveToCameraRoll:type:resolve:reject:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeCameraRollManagerSpecJSI_deletePhotos(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, PromiseKind, \\"deletePhotos\\", @selector(deletePhotos:resolve:reject:), args, count); - } - - NativeCameraRollManagerSpecJSI::NativeCameraRollManagerSpecJSI(const ObjCTurboModule::InitParams ¶ms) - : ObjCTurboModule(params) { - - methodMap_[\\"getPhotos\\"] = MethodMetadata {1, __hostFunction_NativeCameraRollManagerSpecJSI_getPhotos}; - setMethodArgConversionSelector(@\\"getPhotos\\", 0, @\\"JS_NativeCameraRollManager_GetPhotosParams:\\"); - - methodMap_[\\"saveToCameraRoll\\"] = MethodMetadata {2, __hostFunction_NativeCameraRollManagerSpecJSI_saveToCameraRoll}; - - - methodMap_[\\"deletePhotos\\"] = MethodMetadata {1, __hostFunction_NativeCameraRollManagerSpecJSI_deletePhotos}; - - } - } // namespace react -} // namespace facebook -@implementation RCTCxxConvert (NativeExceptionsManager_StackFrame) -+ (RCTManagedPointer *)JS_NativeExceptionsManager_StackFrame:(id)json -{ - return facebook::react::managedPointer(json); -} -@end -@implementation RCTCxxConvert (NativeExceptionsManager_ExceptionData) -+ (RCTManagedPointer *)JS_NativeExceptionsManager_ExceptionData:(id)json -{ - return facebook::react::managedPointer(json); -} -@end -namespace facebook { - namespace react { - - static facebook::jsi::Value __hostFunction_NativeExceptionsManagerSpecJSI_reportFatalException(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, VoidKind, \\"reportFatalException\\", @selector(reportFatalException:stack:exceptionId:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeExceptionsManagerSpecJSI_reportSoftException(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, VoidKind, \\"reportSoftException\\", @selector(reportSoftException:stack:exceptionId:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeExceptionsManagerSpecJSI_reportException(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, VoidKind, \\"reportException\\", @selector(reportException:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeExceptionsManagerSpecJSI_updateExceptionMessage(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, VoidKind, \\"updateExceptionMessage\\", @selector(updateExceptionMessage:stack:exceptionId:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeExceptionsManagerSpecJSI_dismissRedbox(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, VoidKind, \\"dismissRedbox\\", @selector(dismissRedbox), args, count); - } - - NativeExceptionsManagerSpecJSI::NativeExceptionsManagerSpecJSI(const ObjCTurboModule::InitParams ¶ms) - : ObjCTurboModule(params) { - - methodMap_[\\"reportFatalException\\"] = MethodMetadata {3, __hostFunction_NativeExceptionsManagerSpecJSI_reportFatalException}; - - - methodMap_[\\"reportSoftException\\"] = MethodMetadata {3, __hostFunction_NativeExceptionsManagerSpecJSI_reportSoftException}; - - - methodMap_[\\"reportException\\"] = MethodMetadata {1, __hostFunction_NativeExceptionsManagerSpecJSI_reportException}; - setMethodArgConversionSelector(@\\"reportException\\", 0, @\\"JS_NativeExceptionsManager_ExceptionData:\\"); - - methodMap_[\\"updateExceptionMessage\\"] = MethodMetadata {3, __hostFunction_NativeExceptionsManagerSpecJSI_updateExceptionMessage}; - - - methodMap_[\\"dismissRedbox\\"] = MethodMetadata {0, __hostFunction_NativeExceptionsManagerSpecJSI_dismissRedbox}; - - } - } // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateModuleMm can generate fixture simple_native_modules 1`] = ` -Map { - "simple_native_modules-generated.mm" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleObjCpp - * - * We create an umbrella header (and corresponding implementation) here since - * Cxx compilation in BUCK has a limitation: source-code producing genrule()s - * must have a single output. More files => more genrule()s => slower builds. - */ - -#import \\"simple_native_modules.h\\" - - -namespace facebook { - namespace react { - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_voidFunc(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, VoidKind, \\"voidFunc\\", @selector(voidFunc), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getBool(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, BooleanKind, \\"getBool\\", @selector(getBool:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getNumber(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, NumberKind, \\"getNumber\\", @selector(getNumber:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getString(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, StringKind, \\"getString\\", @selector(getString:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getArray(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ArrayKind, \\"getArray\\", @selector(getArray:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getObject(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getObject\\", @selector(getObject:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getRootTag(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, NumberKind, \\"getRootTag\\", @selector(getRootTag:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getValue(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getValue\\", @selector(getValue:y:z:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getValueWithCallback(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, VoidKind, \\"getValueWithCallback\\", @selector(getValueWithCallback:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getValueWithPromise(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, PromiseKind, \\"getValueWithPromise\\", @selector(getValueWithPromise:resolve:reject:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getValueWithOptionalArg(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, PromiseKind, \\"getValueWithOptionalArg\\", @selector(getValueWithOptionalArg:resolve:reject:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getEnums(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, StringKind, \\"getEnums\\", @selector(getEnums:enumFloat:enumString:), args, count); - } - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getConstants(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getConstants\\", @selector(getConstants), args, count); - } - - NativeSampleTurboModuleSpecJSI::NativeSampleTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms) - : ObjCTurboModule(params) { - - methodMap_[\\"voidFunc\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleSpecJSI_voidFunc}; - - - methodMap_[\\"getBool\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getBool}; - - - methodMap_[\\"getNumber\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getNumber}; - - - methodMap_[\\"getString\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getString}; - - - methodMap_[\\"getArray\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getArray}; - - - methodMap_[\\"getObject\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getObject}; - - - methodMap_[\\"getRootTag\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getRootTag}; - - - methodMap_[\\"getValue\\"] = MethodMetadata {3, __hostFunction_NativeSampleTurboModuleSpecJSI_getValue}; - - - methodMap_[\\"getValueWithCallback\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getValueWithCallback}; - - - methodMap_[\\"getValueWithPromise\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getValueWithPromise}; - - - methodMap_[\\"getValueWithOptionalArg\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getValueWithOptionalArg}; - - - methodMap_[\\"getEnums\\"] = MethodMetadata {3, __hostFunction_NativeSampleTurboModuleSpecJSI_getEnums}; - - - methodMap_[\\"getConstants\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleSpecJSI_getConstants}; - - } - } // namespace react -} // namespace facebook -", -} -`; - -exports[`GenerateModuleMm can generate fixture two_modules_different_files 1`] = ` -Map { - "two_modules_different_files-generated.mm" => "/** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). - * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. - * - * @generated by codegen project: GenerateModuleObjCpp - * - * We create an umbrella header (and corresponding implementation) here since - * Cxx compilation in BUCK has a limitation: source-code producing genrule()s - * must have a single output. More files => more genrule()s => slower builds. - */ - -#import \\"two_modules_different_files.h\\" - - -namespace facebook { - namespace react { - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_voidFunc(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, VoidKind, \\"voidFunc\\", @selector(voidFunc), args, count); - } - - NativeSampleTurboModuleSpecJSI::NativeSampleTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms) - : ObjCTurboModule(params) { - - methodMap_[\\"voidFunc\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleSpecJSI_voidFunc}; - - } - } // namespace react -} // namespace facebook - -namespace facebook { - namespace react { - - static facebook::jsi::Value __hostFunction_NativeSampleTurboModule2SpecJSI_voidFunc(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, VoidKind, \\"voidFunc\\", @selector(voidFunc), args, count); - } - - NativeSampleTurboModule2SpecJSI::NativeSampleTurboModule2SpecJSI(const ObjCTurboModule::InitParams ¶ms) - : ObjCTurboModule(params) { - - methodMap_[\\"voidFunc\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModule2SpecJSI_voidFunc}; - - } - } // namespace react -} // namespace facebook -", -} -`; diff --git a/packages/react-native-codegen/src/parsers/__tests__/error-utils-test.js b/packages/react-native-codegen/src/parsers/__tests__/error-utils-test.js deleted file mode 100644 index 58c4081abdb1..000000000000 --- a/packages/react-native-codegen/src/parsers/__tests__/error-utils-test.js +++ /dev/null @@ -1,654 +0,0 @@ -/** - * 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 - * @flow strict-local - * @oncall react_native - */ - -'use strict'; - -const { - throwIfModuleInterfaceNotFound, - throwIfMoreThanOneModuleRegistryCalls, - throwIfModuleInterfaceIsMisnamed, - throwIfUnusedModuleInterfaceParserError, - throwIfWrongNumberOfCallExpressionArgs, - throwIfIncorrectModuleRegistryCallTypeParameterParserError, - throwIfUnsupportedFunctionReturnTypeAnnotationParserError, - throwIfMoreThanOneModuleInterfaceParserError, - throwIfModuleTypeIsUnsupported, - throwIfUntypedModule, - throwIfUnsupportedFunctionParamTypeAnnotationParserError, -} = require('../error-utils'); -const { - UnsupportedModulePropertyParserError, - ModuleInterfaceNotFoundParserError, - MoreThanOneModuleRegistryCallsParserError, - MisnamedModuleInterfaceParserError, - UnusedModuleInterfaceParserError, - IncorrectModuleRegistryCallArityParserError, - IncorrectModuleRegistryCallTypeParameterParserError, - UnsupportedFunctionReturnTypeAnnotationParserError, - UntypedModuleRegistryCallParserError, - MoreThanOneModuleInterfaceParserError, - UnsupportedFunctionParamTypeAnnotationParserError, -} = require('../errors'); - -describe('throwIfModuleInterfaceIsMisnamed', () => { - it("don't throw error if module interface name is Spec", () => { - const nativeModuleName = 'moduleName'; - const specId = {name: 'Spec'}; - const parserType = 'Flow'; - - expect(() => { - throwIfModuleInterfaceIsMisnamed(nativeModuleName, specId, parserType); - }).not.toThrow(MisnamedModuleInterfaceParserError); - }); - it('throw error if module interface is misnamed', () => { - const nativeModuleName = 'moduleName'; - const specId = {name: 'Name'}; - const parserType = 'TypeScript'; - - expect(() => { - throwIfModuleInterfaceIsMisnamed(nativeModuleName, specId, parserType); - }).toThrow(MisnamedModuleInterfaceParserError); - }); -}); - -describe('throwIfModuleInterfaceNotFound', () => { - it('throw error if there are zero module specs', () => { - const nativeModuleName = 'moduleName'; - const specId = {name: 'Name'}; - const parserType = 'TypeScript'; - - expect(() => { - throwIfModuleInterfaceNotFound(0, nativeModuleName, specId, parserType); - }).toThrow(ModuleInterfaceNotFoundParserError); - }); - - it("don't throw error if there is at least one module spec", () => { - const nativeModuleName = 'moduleName'; - const specId = {name: 'Spec'}; - const parserType = 'Flow'; - - expect(() => { - throwIfModuleInterfaceNotFound(1, nativeModuleName, specId, parserType); - }).not.toThrow(ModuleInterfaceNotFoundParserError); - }); -}); - -describe('throwIfMoreThanOneModuleRegistryCalls', () => { - it('throw error if module registry calls more than one', () => { - const nativeModuleName = 'moduleName'; - const callExpressions = [ - {name: 'callExpression1'}, - {name: 'callExpression2'}, - ]; - const parserType = 'Flow'; - - expect(() => { - throwIfMoreThanOneModuleRegistryCalls( - nativeModuleName, - callExpressions, - callExpressions.length, - parserType, - ); - }).toThrow(MoreThanOneModuleRegistryCallsParserError); - }); - it("don't throw error if single module registry call", () => { - const nativeModuleName = 'moduleName'; - const callExpressions = [{name: 'callExpression1'}]; - const parserType = 'TypeScript'; - - expect(() => { - throwIfMoreThanOneModuleRegistryCalls( - nativeModuleName, - callExpressions, - callExpressions.length, - parserType, - ); - }).not.toThrow(MoreThanOneModuleRegistryCallsParserError); - }); -}); - -describe('throwIfUnusedModuleInterfaceParserError', () => { - it('throw error if unused module', () => { - const nativeModuleName = 'moduleName'; - const callExpressions: Array<$FlowFixMe> = []; - const spec = {name: 'Spec'}; - const parserType = 'Flow'; - expect(() => { - throwIfUnusedModuleInterfaceParserError( - nativeModuleName, - spec, - callExpressions, - parserType, - ); - }).toThrow(UnusedModuleInterfaceParserError); - }); - - it("don't throw error if module is used", () => { - const nativeModuleName = 'moduleName'; - const callExpressions = [{name: 'callExpression1'}]; - const spec = {name: 'Spec'}; - const parserType = 'TypeScript'; - expect(() => { - throwIfUnusedModuleInterfaceParserError( - nativeModuleName, - spec, - callExpressions, - parserType, - ); - }).not.toThrow(UnusedModuleInterfaceParserError); - }); -}); - -describe('throwErrorIfWrongNumberOfCallExpressionArgs', () => { - it('throw error if wrong number of call expression args is used', () => { - const nativeModuleName = 'moduleName'; - const flowCallExpression: {argument: Array<$FlowFixMe>} = {argument: []}; - const methodName = 'methodName'; - const numberOfCallExpressionArgs = flowCallExpression.argument.length; - const language = 'Flow'; - expect(() => { - throwIfWrongNumberOfCallExpressionArgs( - nativeModuleName, - flowCallExpression, - methodName, - numberOfCallExpressionArgs, - language, - ); - }).toThrow(IncorrectModuleRegistryCallArityParserError); - }); - - it("don't throw error if correct number of call expression args is used", () => { - const nativeModuleName = 'moduleName'; - const flowCallExpression = {argument: ['argument']}; - const methodName = 'methodName'; - const numberOfCallExpressionArgs = flowCallExpression.argument.length; - const language = 'Flow'; - expect(() => { - throwIfWrongNumberOfCallExpressionArgs( - nativeModuleName, - flowCallExpression, - methodName, - numberOfCallExpressionArgs, - language, - ); - }).not.toThrow(IncorrectModuleRegistryCallArityParserError); - }); -}); - -describe('throwIfUnsupportedFunctionReturnTypeAnnotationParserError', () => { - const returnTypeAnnotation = { - returnType: '', - }, - nativeModuleName = 'moduleName', - invalidReturnType = 'FunctionTypeAnnotation', - language = 'Flow'; - - it('do not throw error if cxxOnly is true', () => { - const cxxOnly = true, - returnType = 'FunctionTypeAnnotation'; - - expect(() => { - throwIfUnsupportedFunctionReturnTypeAnnotationParserError( - nativeModuleName, - returnTypeAnnotation, - invalidReturnType, - language, - cxxOnly, - returnType, - ); - }).not.toThrow(UnsupportedFunctionReturnTypeAnnotationParserError); - }); - - it('do not throw error if returnTypeAnnotation type is not FunctionTypeAnnotation', () => { - const cxxOnly = false, - returnType = ''; - - expect(() => { - throwIfUnsupportedFunctionReturnTypeAnnotationParserError( - nativeModuleName, - returnTypeAnnotation, - invalidReturnType, - language, - cxxOnly, - returnType, - ); - }).not.toThrow(UnsupportedFunctionReturnTypeAnnotationParserError); - }); - - it('throw error if cxxOnly is false and returnTypeAnnotation type is FunctionTypeAnnotation', () => { - const cxxOnly = false, - returnType = 'FunctionTypeAnnotation'; - - expect(() => { - throwIfUnsupportedFunctionReturnTypeAnnotationParserError( - nativeModuleName, - returnTypeAnnotation, - invalidReturnType, - language, - cxxOnly, - returnType, - ); - }).toThrow(UnsupportedFunctionReturnTypeAnnotationParserError); - }); -}); - -describe('throwIfIncorrectModuleRegistryCallTypeParameterParserError', () => { - const nativeModuleName = 'moduleName'; - const methodName = 'methodName'; - const moduleName = 'moduleName'; - it('throw error if flowTypeArguments type is incorrect', () => { - const flowTypeArguments = { - type: '', - params: [ - { - type: 'GenericTypeAnnotation', - id: { - name: 'Spec', - }, - }, - ], - }; - - const parserType = 'Flow'; - - expect(() => { - throwIfIncorrectModuleRegistryCallTypeParameterParserError( - nativeModuleName, - flowTypeArguments, - methodName, - moduleName, - parserType, - ); - }).toThrow(IncorrectModuleRegistryCallTypeParameterParserError); - }); - - it('throw error if flowTypeArguments params length is not 1', () => { - const flowTypeArguments: $FlowFixMe = { - type: 'TypeParameterInstantiation', - params: [], - }; - - const parserType = 'Flow'; - - expect(() => { - throwIfIncorrectModuleRegistryCallTypeParameterParserError( - nativeModuleName, - flowTypeArguments, - methodName, - moduleName, - parserType, - ); - }).toThrow(IncorrectModuleRegistryCallTypeParameterParserError); - }); - - it('throw error if flowTypeArguments params type is not GenericTypeAnnotation', () => { - const flowTypeArguments = { - type: 'TypeParameterInstantiation', - params: [ - { - type: '', - id: { - name: 'Spec', - }, - }, - ], - }; - - const parserType = 'Flow'; - - expect(() => { - throwIfIncorrectModuleRegistryCallTypeParameterParserError( - nativeModuleName, - flowTypeArguments, - methodName, - moduleName, - parserType, - ); - }).toThrow(IncorrectModuleRegistryCallTypeParameterParserError); - }); - - it('throw error if flowTypeArguments params id name is not Spec', () => { - const flowTypeArguments = { - type: 'TypeParameterInstantiation', - params: [ - { - type: 'GenericTypeAnnotation', - id: { - name: '', - }, - }, - ], - }; - - const parserType = 'Flow'; - - expect(() => { - throwIfIncorrectModuleRegistryCallTypeParameterParserError( - nativeModuleName, - flowTypeArguments, - methodName, - moduleName, - parserType, - ); - }).toThrow(IncorrectModuleRegistryCallTypeParameterParserError); - }); - - it('do not throw error if flowTypeArguments are correct', () => { - const flowTypeArguments = { - type: 'TypeParameterInstantiation', - params: [ - { - type: 'GenericTypeAnnotation', - id: { - name: 'Spec', - }, - }, - ], - }; - - const parserType = 'Flow'; - - expect(() => { - throwIfIncorrectModuleRegistryCallTypeParameterParserError( - nativeModuleName, - flowTypeArguments, - methodName, - moduleName, - parserType, - ); - }).not.toThrow(IncorrectModuleRegistryCallTypeParameterParserError); - }); - - it('throw error if typeScriptTypeArguments type not correct', () => { - const typeScriptTypeArguments = { - type: '', - params: [ - { - type: 'TSTypeReference', - typeName: { - name: 'Spec', - }, - }, - ], - }; - - const parserType = 'TypeScript'; - - expect(() => { - throwIfIncorrectModuleRegistryCallTypeParameterParserError( - nativeModuleName, - typeScriptTypeArguments, - methodName, - moduleName, - parserType, - ); - }).toThrow(IncorrectModuleRegistryCallTypeParameterParserError); - }); - - it('throw error if typeScriptTypeArguments params length is not equal to 1', () => { - const typeScriptTypeArguments: $FlowFixMe = { - type: 'TSTypeParameterInstantiation', - params: [], - }; - - const parserType = 'TypeScript'; - - expect(() => { - throwIfIncorrectModuleRegistryCallTypeParameterParserError( - nativeModuleName, - typeScriptTypeArguments, - methodName, - moduleName, - parserType, - ); - }).toThrow(IncorrectModuleRegistryCallTypeParameterParserError); - }); - - it('throw error if typeScriptTypeArguments params type is not TSTypeReference', () => { - const typeScriptTypeArguments = { - type: 'TSTypeParameterInstantiation', - params: [ - { - type: '', - typeName: { - name: 'Spec', - }, - }, - ], - }; - - const parserType = 'TypeScript'; - - expect(() => { - throwIfIncorrectModuleRegistryCallTypeParameterParserError( - nativeModuleName, - typeScriptTypeArguments, - methodName, - moduleName, - parserType, - ); - }).toThrow(IncorrectModuleRegistryCallTypeParameterParserError); - }); - - it('throw error if typeScriptTypeArguments params typeName name is not Spec', () => { - const typeScriptTypeArguments = { - type: 'TSTypeParameterInstantiation', - params: [ - { - type: 'TSTypeReference', - typeName: { - name: '', - }, - }, - ], - }; - - const parserType = 'TypeScript'; - - expect(() => { - throwIfIncorrectModuleRegistryCallTypeParameterParserError( - nativeModuleName, - typeScriptTypeArguments, - methodName, - moduleName, - parserType, - ); - }).toThrow(IncorrectModuleRegistryCallTypeParameterParserError); - }); - - it('do not throw error if typeScriptTypeArguments are correct', () => { - const typeScriptTypeArguments = { - type: 'TSTypeParameterInstantiation', - params: [ - { - type: 'TSTypeReference', - typeName: { - name: 'Spec', - }, - }, - ], - }; - - const parserType = 'TypeScript'; - - expect(() => { - throwIfIncorrectModuleRegistryCallTypeParameterParserError( - nativeModuleName, - typeScriptTypeArguments, - methodName, - moduleName, - parserType, - ); - }).not.toThrow(IncorrectModuleRegistryCallTypeParameterParserError); - }); -}); - -describe('throwIfUntypedModule', () => { - const hasteModuleName = 'moduleName'; - const methodName = 'methodName'; - const moduleName = 'moduleName'; - const callExpressions: Array<$FlowFixMe> = []; - - it('should throw error if module does not have a type', () => { - const typeArguments = null; - const language = 'Flow'; - expect(() => - throwIfUntypedModule( - typeArguments, - hasteModuleName, - callExpressions, - methodName, - moduleName, - language, - ), - ).toThrowError(UntypedModuleRegistryCallParserError); - }); - - it('should not throw error if module have a type', () => { - const typeArguments: $FlowFixMe = { - type: 'TSTypeParameterInstantiations', - params: [], - }; - - const language = 'TypeScript'; - expect(() => - throwIfUntypedModule( - typeArguments, - hasteModuleName, - callExpressions, - methodName, - moduleName, - language, - ), - ).not.toThrowError(UntypedModuleRegistryCallParserError); - }); -}); - -describe('throwIfModuleTypeIsUnsupported', () => { - const hasteModuleName = 'moduleName'; - const property = {value: 'value', key: {name: 'name'}}; - it("don't throw error if module type is FunctionTypeAnnotation in Flow", () => { - const value = {type: 'FunctionTypeAnnotation'}; - const language = 'Flow'; - - expect(() => { - throwIfModuleTypeIsUnsupported( - hasteModuleName, - property.value, - property.key.name, - value.type, - language, - ); - }).not.toThrow(UnsupportedModulePropertyParserError); - }); - it('throw error if module type is unsupported in Flow', () => { - const value = {type: ''}; - const language = 'Flow'; - - expect(() => { - throwIfModuleTypeIsUnsupported( - hasteModuleName, - property.value, - property.key.name, - value.type, - language, - ); - }).toThrow(UnsupportedModulePropertyParserError); - }); - it("don't throw error if module type is TSFunctionType in TypeScript", () => { - const value = {type: 'TSFunctionType'}; - const language = 'TypeScript'; - - expect(() => { - throwIfModuleTypeIsUnsupported( - hasteModuleName, - property.value, - property.key.name, - value.type, - language, - ); - }).not.toThrow(UnsupportedModulePropertyParserError); - }); - it("don't throw error if module type is TSMethodSignature in TypeScript", () => { - const value = {type: 'TSMethodSignature'}; - const language = 'TypeScript'; - - expect(() => { - throwIfModuleTypeIsUnsupported( - hasteModuleName, - property.value, - property.key.name, - value.type, - language, - ); - }).not.toThrow(UnsupportedModulePropertyParserError); - }); - it('throw error if module type is unsupported in TypeScript', () => { - const value = {type: ''}; - const language = 'TypeScript'; - - expect(() => { - throwIfModuleTypeIsUnsupported( - hasteModuleName, - property.value, - property.key.name, - value.type, - language, - ); - }).toThrow(UnsupportedModulePropertyParserError); - }); -}); - -describe('throwIfMoreThanOneModuleInterfaceParserError', () => { - it("don't throw error if module specs length is <= 1", () => { - const nativeModuleName = 'moduleName'; - const moduleSpecs = []; - const parserType = 'Flow'; - - expect(() => { - throwIfMoreThanOneModuleInterfaceParserError( - nativeModuleName, - moduleSpecs, - parserType, - ); - }).not.toThrow(MoreThanOneModuleInterfaceParserError); - }); - it('throw error if module specs is > 1 ', () => { - const nativeModuleName = 'moduleName'; - const moduleSpecs = [{id: {name: 'Name-1'}}, {id: {name: 'Name-2'}}]; - const parserType = 'TypeScript'; - - expect(() => { - throwIfMoreThanOneModuleInterfaceParserError( - nativeModuleName, - moduleSpecs, - parserType, - ); - }).toThrow(MoreThanOneModuleInterfaceParserError); - }); -}); - -describe('throwIfUnsupportedFunctionParamTypeAnnotationParserError', () => { - const nativeModuleName = 'moduleName'; - const languageParamTypeAnnotation = {type: 'VoidTypeAnnotation'}; - const paramName = 'paramName'; - it('throws an UnsupportedFunctionParamTypeAnnotationParserError', () => { - const paramTypeAnnotationType = 'VoidTypeAnnotation'; - expect(() => { - throwIfUnsupportedFunctionParamTypeAnnotationParserError( - nativeModuleName, - languageParamTypeAnnotation, - paramName, - paramTypeAnnotationType, - ); - }).toThrow(UnsupportedFunctionParamTypeAnnotationParserError); - }); -}); diff --git a/packages/react-native-codegen/src/parsers/__tests__/parsers-commons-test.js b/packages/react-native-codegen/src/parsers/__tests__/parsers-commons-test.js deleted file mode 100644 index 7e0237fa924d..000000000000 --- a/packages/react-native-codegen/src/parsers/__tests__/parsers-commons-test.js +++ /dev/null @@ -1,708 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use-strict'; - -import {assertGenericTypeAnnotationHasExactlyOneTypeParameter} from '../parsers-commons'; -import type {ParserType} from '../errors'; -const { - wrapNullable, - unwrapNullable, - emitMixedTypeAnnotation, - emitUnionTypeAnnotation, -} = require('../parsers-commons.js'); -const {UnsupportedUnionTypeAnnotationParserError} = require('../errors'); -import type {UnionTypeAnnotationMemberType} from '../../CodegenSchema'; - -describe('wrapNullable', () => { - describe('when nullable is true', () => { - it('returns nullable type annotation', () => { - const result = wrapNullable(true, { - type: 'BooleanTypeAnnotation', - }); - const expected = { - type: 'NullableTypeAnnotation', - typeAnnotation: { - type: 'BooleanTypeAnnotation', - }, - }; - - expect(result).toEqual(expected); - }); - }); - describe('when nullable is false', () => { - it('returns non nullable type annotation', () => { - const result = wrapNullable(false, { - type: 'BooleanTypeAnnotation', - }); - const expected = { - type: 'BooleanTypeAnnotation', - }; - - expect(result).toEqual(expected); - }); - }); -}); - -describe('unwrapNullable', () => { - describe('when type annotation is nullable', () => { - it('returns original type annotation', () => { - const result = unwrapNullable({ - type: 'NullableTypeAnnotation', - typeAnnotation: { - type: 'BooleanTypeAnnotation', - }, - }); - const expected = [ - { - type: 'BooleanTypeAnnotation', - }, - true, - ]; - - expect(result).toEqual(expected); - }); - }); - describe('when type annotation is not nullable', () => { - it('returns original type annotation', () => { - const result = unwrapNullable({ - type: 'BooleanTypeAnnotation', - }); - const expected = [ - { - type: 'BooleanTypeAnnotation', - }, - false, - ]; - - expect(result).toEqual(expected); - }); - }); -}); - -describe('assertGenericTypeAnnotationHasExactlyOneTypeParameter', () => { - const moduleName = 'testModuleName'; - - it("doesn't throw any Error when typeAnnotation has exactly one typeParameter", () => { - const typeAnnotation = { - typeParameters: { - type: 'TypeParameterInstantiation', - params: [1], - }, - }; - expect(() => - assertGenericTypeAnnotationHasExactlyOneTypeParameter( - moduleName, - typeAnnotation, - 'Flow', - ), - ).not.toThrow(); - }); - - it('throws an IncorrectlyParameterizedGenericParserError if typeParameters is null', () => { - const typeAnnotation = { - typeParameters: null, - id: { - name: 'typeAnnotationName', - }, - }; - expect(() => - assertGenericTypeAnnotationHasExactlyOneTypeParameter( - moduleName, - typeAnnotation, - 'Flow', - ), - ).toThrowErrorMatchingInlineSnapshot( - `"Module testModuleName: Generic 'typeAnnotationName' must have type parameters."`, - ); - }); - - it('throws an error if typeAnnotation.typeParameters.type is not TypeParameterInstantiation when language is Flow', () => { - const flowTypeAnnotation = { - typeParameters: { - type: 'wrongType', - params: [1], - }, - id: { - name: 'typeAnnotationName', - }, - }; - expect(() => - assertGenericTypeAnnotationHasExactlyOneTypeParameter( - moduleName, - flowTypeAnnotation, - 'Flow', - ), - ).toThrowErrorMatchingInlineSnapshot( - `"assertGenericTypeAnnotationHasExactlyOneTypeParameter: Type parameters must be an AST node of type 'TypeParameterInstantiation'"`, - ); - }); - - it('throws an error if typeAnnotation.typeParameters.type is not TSTypeParameterInstantiation when language is TypeScript', () => { - const typeScriptTypeAnnotation = { - typeParameters: { - type: 'wrongType', - params: [1], - }, - typeName: { - name: 'typeAnnotationName', - }, - }; - expect(() => - assertGenericTypeAnnotationHasExactlyOneTypeParameter( - moduleName, - typeScriptTypeAnnotation, - 'TypeScript', - ), - ).toThrowErrorMatchingInlineSnapshot( - `"assertGenericTypeAnnotationHasExactlyOneTypeParameter: Type parameters must be an AST node of type 'TSTypeParameterInstantiation'"`, - ); - }); - - it("throws an IncorrectlyParameterizedGenericParserError if typeParameters don't have 1 exactly parameter for Flow", () => { - const language: ParserType = 'Flow'; - const typeAnnotationWithTwoParams = { - typeParameters: { - params: [1, 2], - type: 'TypeParameterInstantiation', - }, - id: { - name: 'typeAnnotationName', - }, - }; - expect(() => - assertGenericTypeAnnotationHasExactlyOneTypeParameter( - moduleName, - typeAnnotationWithTwoParams, - language, - ), - ).toThrowErrorMatchingInlineSnapshot( - `"Module testModuleName: Generic 'typeAnnotationName' must have exactly one type parameter."`, - ); - - const typeAnnotationWithNoParams = { - typeParameters: { - params: [], - type: 'TypeParameterInstantiation', - }, - id: { - name: 'typeAnnotationName', - }, - }; - expect(() => - assertGenericTypeAnnotationHasExactlyOneTypeParameter( - moduleName, - typeAnnotationWithNoParams, - language, - ), - ).toThrowErrorMatchingInlineSnapshot( - `"Module testModuleName: Generic 'typeAnnotationName' must have exactly one type parameter."`, - ); - }); - - it("throws an IncorrectlyParameterizedGenericParserError if typeParameters don't have 1 exactly parameter for TS", () => { - const language: ParserType = 'TypeScript'; - const typeAnnotationWithTwoParams = { - typeParameters: { - params: [1, 2], - type: 'TSTypeParameterInstantiation', - }, - typeName: { - name: 'typeAnnotationName', - }, - }; - expect(() => - assertGenericTypeAnnotationHasExactlyOneTypeParameter( - moduleName, - typeAnnotationWithTwoParams, - language, - ), - ).toThrowErrorMatchingInlineSnapshot( - `"Module testModuleName: Generic 'typeAnnotationName' must have exactly one type parameter."`, - ); - - const typeAnnotationWithNoParams = { - typeParameters: { - params: [], - type: 'TSTypeParameterInstantiation', - }, - typeName: { - name: 'typeAnnotationName', - }, - }; - expect(() => - assertGenericTypeAnnotationHasExactlyOneTypeParameter( - moduleName, - typeAnnotationWithNoParams, - language, - ), - ).toThrowErrorMatchingInlineSnapshot( - `"Module testModuleName: Generic 'typeAnnotationName' must have exactly one type parameter."`, - ); - }); -}); - -describe('emitMixedTypeAnnotation', () => { - describe('when nullable is true', () => { - it('returns nullable type annotation', () => { - const result = emitMixedTypeAnnotation(true); - const expected = { - type: 'NullableTypeAnnotation', - typeAnnotation: { - type: 'MixedTypeAnnotation', - }, - }; - - expect(result).toEqual(expected); - }); - }); - describe('when nullable is false', () => { - it('returns non nullable type annotation', () => { - const result = emitMixedTypeAnnotation(false); - const expected = { - type: 'MixedTypeAnnotation', - }; - - expect(result).toEqual(expected); - }); - }); -}); - -describe('emitUnionTypeAnnotation', () => { - const hasteModuleName = 'SampleTurboModule'; - - describe('when language is flow', () => { - const language: ParserType = 'Flow'; - - describe('when members type is numeric', () => { - const typeAnnotation = { - type: 'UnionTypeAnnotation', - types: [ - {type: 'NumberLiteralTypeAnnotation'}, - {type: 'NumberLiteralTypeAnnotation'}, - ], - }; - describe('when nullable is true', () => { - it('returns nullable type annotation', () => { - const result = emitUnionTypeAnnotation( - true, - hasteModuleName, - typeAnnotation, - language, - ); - - const expected = { - type: 'NullableTypeAnnotation', - typeAnnotation: { - type: 'UnionTypeAnnotation', - memberType: 'NumberTypeAnnotation', - }, - }; - - expect(result).toEqual(expected); - }); - }); - - describe('when nullable is false', () => { - it('returns non nullable type annotation', () => { - const result = emitUnionTypeAnnotation( - false, - hasteModuleName, - typeAnnotation, - language, - ); - - const expected = { - type: 'UnionTypeAnnotation', - memberType: 'NumberTypeAnnotation', - }; - - expect(result).toEqual(expected); - }); - }); - }); - - describe('when members type is string', () => { - const typeAnnotation = { - type: 'UnionTypeAnnotation', - types: [ - {type: 'StringLiteralTypeAnnotation'}, - {type: 'StringLiteralTypeAnnotation'}, - ], - }; - describe('when nullable is true', () => { - it('returns nullable type annotation', () => { - const result = emitUnionTypeAnnotation( - true, - hasteModuleName, - typeAnnotation, - language, - ); - - const expected = { - type: 'NullableTypeAnnotation', - typeAnnotation: { - type: 'UnionTypeAnnotation', - memberType: 'StringTypeAnnotation', - }, - }; - - expect(result).toEqual(expected); - }); - }); - - describe('when nullable is false', () => { - it('returns non nullable type annotation', () => { - const result = emitUnionTypeAnnotation( - false, - hasteModuleName, - typeAnnotation, - language, - ); - - const expected = { - type: 'UnionTypeAnnotation', - memberType: 'StringTypeAnnotation', - }; - - expect(result).toEqual(expected); - }); - }); - }); - - describe('when members type is object', () => { - const typeAnnotation = { - type: 'UnionTypeAnnotation', - types: [{type: 'ObjectTypeAnnotation'}, {type: 'ObjectTypeAnnotation'}], - }; - describe('when nullable is true', () => { - it('returns nullable type annotation', () => { - const result = emitUnionTypeAnnotation( - true, - hasteModuleName, - typeAnnotation, - language, - ); - - const expected = { - type: 'NullableTypeAnnotation', - typeAnnotation: { - type: 'UnionTypeAnnotation', - memberType: 'ObjectTypeAnnotation', - }, - }; - - expect(result).toEqual(expected); - }); - }); - - describe('when nullable is false', () => { - it('returns non nullable type annotation', () => { - const result = emitUnionTypeAnnotation( - false, - hasteModuleName, - typeAnnotation, - language, - ); - - const expected = { - type: 'UnionTypeAnnotation', - memberType: 'ObjectTypeAnnotation', - }; - - expect(result).toEqual(expected); - }); - }); - }); - - describe('when members type is mixed', () => { - const typeAnnotation = { - type: 'UnionTypeAnnotation', - types: [ - {type: 'NumberLiteralTypeAnnotation'}, - {type: 'StringLiteralTypeAnnotation'}, - {type: 'ObjectTypeAnnotation'}, - ], - }; - const unionTypes: UnionTypeAnnotationMemberType[] = [ - 'NumberTypeAnnotation', - 'StringTypeAnnotation', - 'ObjectTypeAnnotation', - ]; - describe('when nullable is true', () => { - it('throws an excpetion', () => { - const expected = new UnsupportedUnionTypeAnnotationParserError( - hasteModuleName, - typeAnnotation, - unionTypes, - language, - ); - - expect(() => { - emitUnionTypeAnnotation( - true, - hasteModuleName, - typeAnnotation, - language, - ); - }).toThrow(expected); - }); - }); - - describe('when nullable is false', () => { - it('throws an excpetion', () => { - const expected = new UnsupportedUnionTypeAnnotationParserError( - hasteModuleName, - typeAnnotation, - unionTypes, - language, - ); - - expect(() => { - emitUnionTypeAnnotation( - false, - hasteModuleName, - typeAnnotation, - language, - ); - }).toThrow(expected); - }); - }); - }); - }); - - describe('when language is typescript', () => { - const language: ParserType = 'TypeScript'; - - describe('when members type is numeric', () => { - const typeAnnotation = { - type: 'TSUnionType', - types: [ - { - type: 'TSLiteralType', - literal: {type: 'NumericLiteral'}, - }, - { - type: 'TSLiteralType', - literal: {type: 'NumericLiteral'}, - }, - ], - }; - describe('when nullable is true', () => { - it('returns nullable type annotation', () => { - const result = emitUnionTypeAnnotation( - true, - hasteModuleName, - typeAnnotation, - language, - ); - - const expected = { - type: 'NullableTypeAnnotation', - typeAnnotation: { - type: 'UnionTypeAnnotation', - memberType: 'NumberTypeAnnotation', - }, - }; - - expect(result).toEqual(expected); - }); - }); - - describe('when nullable is false', () => { - it('returns non nullable type annotation', () => { - const result = emitUnionTypeAnnotation( - false, - hasteModuleName, - typeAnnotation, - language, - ); - - const expected = { - type: 'UnionTypeAnnotation', - memberType: 'NumberTypeAnnotation', - }; - - expect(result).toEqual(expected); - }); - }); - }); - - describe('when members type is string', () => { - const typeAnnotation = { - type: 'TSUnionType', - types: [ - { - type: 'TSLiteralType', - literal: {type: 'StringLiteral'}, - }, - { - type: 'TSLiteralType', - literal: {type: 'StringLiteral'}, - }, - ], - }; - describe('when nullable is true', () => { - it('returns nullable type annotation', () => { - const result = emitUnionTypeAnnotation( - true, - hasteModuleName, - typeAnnotation, - language, - ); - - const expected = { - type: 'NullableTypeAnnotation', - typeAnnotation: { - type: 'UnionTypeAnnotation', - memberType: 'StringTypeAnnotation', - }, - }; - - expect(result).toEqual(expected); - }); - }); - - describe('when nullable is false', () => { - it('returns non nullable type annotation', () => { - const result = emitUnionTypeAnnotation( - false, - hasteModuleName, - typeAnnotation, - language, - ); - - const expected = { - type: 'UnionTypeAnnotation', - memberType: 'StringTypeAnnotation', - }; - - expect(result).toEqual(expected); - }); - }); - }); - - describe('when members type is object', () => { - const typeAnnotation = { - type: 'TSUnionType', - types: [ - { - type: 'TSLiteralType', - }, - { - type: 'TSLiteralType', - }, - ], - }; - describe('when nullable is true', () => { - it('returns nullable type annotation', () => { - const result = emitUnionTypeAnnotation( - true, - hasteModuleName, - typeAnnotation, - language, - ); - - const expected = { - type: 'NullableTypeAnnotation', - typeAnnotation: { - type: 'UnionTypeAnnotation', - memberType: 'ObjectTypeAnnotation', - }, - }; - - expect(result).toEqual(expected); - }); - }); - - describe('when nullable is false', () => { - it('returns non nullable type annotation', () => { - const result = emitUnionTypeAnnotation( - false, - hasteModuleName, - typeAnnotation, - language, - ); - - const expected = { - type: 'UnionTypeAnnotation', - memberType: 'ObjectTypeAnnotation', - }; - - expect(result).toEqual(expected); - }); - }); - }); - - describe('when members type is mixed', () => { - const typeAnnotation = { - type: 'TSUnionType', - types: [ - { - type: 'TSLiteralType', - literal: {type: 'NumericLiteral'}, - }, - { - type: 'TSLiteralType', - literal: {type: 'StringLiteral'}, - }, - { - type: 'TSLiteralType', - }, - ], - }; - const unionTypes = [ - 'NumberTypeAnnotation', - 'StringTypeAnnotation', - 'ObjectTypeAnnotation', - ]; - describe('when nullable is true', () => { - it('throws an excpetion', () => { - const expected = new UnsupportedUnionTypeAnnotationParserError( - hasteModuleName, - typeAnnotation, - unionTypes, - language, - ); - - expect(() => { - emitUnionTypeAnnotation( - true, - hasteModuleName, - typeAnnotation, - language, - ); - }).toThrow(expected); - }); - }); - - describe('when nullable is false', () => { - it('throws an excpetion', () => { - const expected = new UnsupportedUnionTypeAnnotationParserError( - hasteModuleName, - typeAnnotation, - unionTypes, - language, - ); - - expect(() => { - emitUnionTypeAnnotation( - false, - hasteModuleName, - typeAnnotation, - language, - ); - }).toThrow(expected); - }); - }); - }); - }); -}); diff --git a/packages/react-native-codegen/src/parsers/__tests__/parsers-primitives-test.js b/packages/react-native-codegen/src/parsers/__tests__/parsers-primitives-test.js deleted file mode 100644 index b64c48f776a3..000000000000 --- a/packages/react-native-codegen/src/parsers/__tests__/parsers-primitives-test.js +++ /dev/null @@ -1,454 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use-strict'; - -const { - emitBoolean, - emitDouble, - emitFloat, - emitNumber, - emitInt32, - emitObject, - emitPromise, - emitRootTag, - emitVoid, - emitString, - emitStringish, - typeAliasResolution, -} = require('../parsers-primitives.js'); - -describe('emitBoolean', () => { - describe('when nullable is true', () => { - it('returns nullable type annotation', () => { - const result = emitBoolean(true); - const expected = { - type: 'NullableTypeAnnotation', - typeAnnotation: { - type: 'BooleanTypeAnnotation', - }, - }; - - expect(result).toEqual(expected); - }); - }); - describe('when nullable is false', () => { - it('returns non nullable type annotation', () => { - const result = emitBoolean(false); - const expected = { - type: 'BooleanTypeAnnotation', - }; - - expect(result).toEqual(expected); - }); - }); -}); - -describe('emitInt32', () => { - describe('when nullable is true', () => { - it('returns nullable type annotation', () => { - const result = emitInt32(true); - const expected = { - type: 'NullableTypeAnnotation', - typeAnnotation: { - type: 'Int32TypeAnnotation', - }, - }; - - expect(result).toEqual(expected); - }); - }); - describe('when nullable is false', () => { - it('returns non nullable type annotation', () => { - const result = emitInt32(false); - const expected = { - type: 'Int32TypeAnnotation', - }; - - expect(result).toEqual(expected); - }); - }); -}); - -describe('emitNumber', () => { - describe('when nullable is true', () => { - it('returns nullable type annotation', () => { - const result = emitNumber(true); - const expected = { - type: 'NullableTypeAnnotation', - typeAnnotation: { - type: 'NumberTypeAnnotation', - }, - }; - - expect(result).toEqual(expected); - }); - }); - describe('when nullable is false', () => { - it('returns non nullable type annotation', () => { - const result = emitNumber(false); - const expected = { - type: 'NumberTypeAnnotation', - }; - - expect(result).toEqual(expected); - }); - }); -}); - -describe('emitRootTag', () => { - const reservedTypeAnnotation = { - type: 'ReservedTypeAnnotation', - name: 'RootTag', - }; - - describe('when nullable is true', () => { - it('returns nullable type annotation', () => { - const result = emitRootTag(true); - - expect(result).toEqual({ - type: 'NullableTypeAnnotation', - typeAnnotation: reservedTypeAnnotation, - }); - }); - }); - - describe('when nullable is false', () => { - it('returns non nullable type annotation', () => { - const result = emitRootTag(false); - - expect(result).toEqual(reservedTypeAnnotation); - }); - }); -}); - -describe('emitStringish', () => { - describe('when nullable is true', () => { - it('returns nullable type annotation', () => { - const result = emitStringish(true); - const expected = { - type: 'NullableTypeAnnotation', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }; - - expect(result).toEqual(expected); - }); - }); - - describe('when nullable is false', () => { - it('returns non nullable type annotation', () => { - const result = emitStringish(false); - const expected = { - type: 'StringTypeAnnotation', - }; - - expect(result).toEqual(expected); - }); - }); -}); - -describe('emitString', () => { - describe('when nullable is true', () => { - it('returns nullable type annotation', () => { - const result = emitString(true); - const expected = { - type: 'NullableTypeAnnotation', - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }; - - expect(result).toEqual(expected); - }); - }); - - describe('when nullable is false', () => { - it('returns non nullable type annotation', () => { - const result = emitString(false); - const expected = { - type: 'StringTypeAnnotation', - }; - - expect(result).toEqual(expected); - }); - }); -}); - -describe('emitDouble', () => { - describe('when nullable is true', () => { - it('returns nullable type annotation', () => { - const result = emitDouble(true); - const expected = { - type: 'NullableTypeAnnotation', - typeAnnotation: { - type: 'DoubleTypeAnnotation', - }, - }; - - expect(result).toEqual(expected); - }); - }); - describe('when nullable is false', () => { - it('returns non nullable type annotation', () => { - const result = emitDouble(false); - const expected = { - type: 'DoubleTypeAnnotation', - }; - - expect(result).toEqual(expected); - }); - }); -}); - -describe('emitVoid', () => { - describe('when nullable is true', () => { - it('returns nullable type annotation', () => { - const result = emitVoid(true); - const expected = { - type: 'NullableTypeAnnotation', - typeAnnotation: { - type: 'VoidTypeAnnotation', - }, - }; - - expect(result).toEqual(expected); - }); - }); - describe('when nullable is false', () => { - it('returns non nullable type annotation', () => { - const result = emitVoid(false); - const expected = { - type: 'VoidTypeAnnotation', - }; - - expect(result).toEqual(expected); - }); - }); -}); - -describe('typeAliasResolution', () => { - const objectTypeAnnotation = { - type: 'ObjectTypeAnnotation', - properties: [ - { - name: 'Foo', - optional: false, - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }, - ], - }; - - describe('when typeAliasResolutionStatus is successful', () => { - const typeAliasResolutionStatus = {successful: true, aliasName: 'Foo'}; - - describe('when nullable is true', () => { - it('returns nullable TypeAliasTypeAnnotation and map it in aliasMap', () => { - const aliasMap = {}; - const result = typeAliasResolution( - typeAliasResolutionStatus, - objectTypeAnnotation, - aliasMap, - true, - ); - - expect(aliasMap).toEqual({Foo: objectTypeAnnotation}); - expect(result).toEqual({ - type: 'NullableTypeAnnotation', - typeAnnotation: { - type: 'TypeAliasTypeAnnotation', - name: 'Foo', - }, - }); - }); - }); - - describe('when nullable is false', () => { - it('returns non nullable TypeAliasTypeAnnotation and map it in aliasMap', () => { - const aliasMap = {}; - const result = typeAliasResolution( - typeAliasResolutionStatus, - objectTypeAnnotation, - aliasMap, - false, - ); - - expect(aliasMap).toEqual({Foo: objectTypeAnnotation}); - expect(result).toEqual({ - type: 'TypeAliasTypeAnnotation', - name: 'Foo', - }); - }); - }); - }); - - describe('when typeAliasResolutionStatus is not successful', () => { - const typeAliasResolutionStatus = {successful: false}; - - describe('when nullable is true', () => { - it('returns nullable ObjectTypeAnnotation', () => { - const aliasMap = {}; - const result = typeAliasResolution( - typeAliasResolutionStatus, - objectTypeAnnotation, - aliasMap, - true, - ); - - expect(aliasMap).toEqual({}); - expect(result).toEqual({ - type: 'NullableTypeAnnotation', - typeAnnotation: objectTypeAnnotation, - }); - }); - }); - - describe('when nullable is false', () => { - it('returns non nullable ObjectTypeAnnotation', () => { - const aliasMap = {}; - const result = typeAliasResolution( - typeAliasResolutionStatus, - objectTypeAnnotation, - aliasMap, - false, - ); - - expect(aliasMap).toEqual({}); - expect(result).toEqual(objectTypeAnnotation); - }); - }); - }); -}); - -describe('emitPromise', () => { - const moduleName = 'testModuleName'; - const language = 'Flow'; - describe("when typeAnnotation doesn't have exactly one typeParameter", () => { - const typeAnnotation = { - typeParameters: { - params: [1, 2], - type: 'TypeParameterInstantiation', - }, - id: { - name: 'typeAnnotationName', - }, - }; - it('throws an IncorrectlyParameterizedGenericParserError error', () => { - const nullable = false; - expect(() => - emitPromise(moduleName, typeAnnotation, language, nullable), - ).toThrow(); - }); - }); - - describe("when typeAnnotation doesn't has exactly one typeParameter", () => { - const typeAnnotation = { - typeParameters: { - params: [1], - type: 'TypeParameterInstantiation', - }, - id: { - name: 'typeAnnotationName', - }, - }; - - describe('when nullable is true', () => { - const nullable = true; - it('returns nullable type annotation', () => { - const result = emitPromise( - moduleName, - typeAnnotation, - language, - nullable, - ); - const expected = { - type: 'NullableTypeAnnotation', - typeAnnotation: { - type: 'PromiseTypeAnnotation', - }, - }; - - expect(result).toEqual(expected); - }); - }); - describe('when nullable is false', () => { - const nullable = false; - it('returns non nullable type annotation', () => { - const result = emitPromise( - moduleName, - typeAnnotation, - language, - nullable, - ); - const expected = { - type: 'PromiseTypeAnnotation', - }; - - expect(result).toEqual(expected); - }); - }); - }); -}); - -describe('emitObject', () => { - describe('when nullable is true', () => { - it('returns nullable type annotation', () => { - const result = emitObject(true); - const expected = { - type: 'NullableTypeAnnotation', - typeAnnotation: { - type: 'GenericObjectTypeAnnotation', - }, - }; - - expect(result).toEqual(expected); - }); - }); - describe('when nullable is false', () => { - it('returns non nullable type annotation', () => { - const result = emitObject(false); - const expected = { - type: 'GenericObjectTypeAnnotation', - }; - - expect(result).toEqual(expected); - }); - }); - - describe('emitFloat', () => { - describe('when nullable is true', () => { - it('returns nullable type annotation', () => { - const result = emitFloat(true); - const expected = { - type: 'NullableTypeAnnotation', - typeAnnotation: { - type: 'FloatTypeAnnotation', - }, - }; - - expect(result).toEqual(expected); - }); - }); - describe('when nullable is false', () => { - it('returns non nullable type annotation', () => { - const result = emitFloat(false); - const expected = { - type: 'FloatTypeAnnotation', - }; - - expect(result).toEqual(expected); - }); - }); - }); -}); diff --git a/packages/react-native-codegen/src/parsers/__tests__/utils-test.js b/packages/react-native-codegen/src/parsers/__tests__/utils-test.js deleted file mode 100644 index caf08e01f603..000000000000 --- a/packages/react-native-codegen/src/parsers/__tests__/utils-test.js +++ /dev/null @@ -1,584 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const { - extractNativeModuleName, - createParserErrorCapturer, - verifyPlatforms, - visit, - buildSchemaFromConfigType, - isModuleRegistryCall, -} = require('../utils.js'); -const {ParserError} = require('../errors'); - -beforeEach(() => { - jest.clearAllMocks(); -}); - -describe('extractnativeModuleName', () => { - it('return filename when it ends with .js', () => { - const filename = '/some_folder/NativeModule.js'; - const nativeModuleName = extractNativeModuleName(filename); - expect(nativeModuleName).toBe('NativeModule'); - }); - it('return filename when it ends with .ts', () => { - const filename = '/some_folder/NativeModule.ts'; - const nativeModuleName = extractNativeModuleName(filename); - expect(nativeModuleName).toBe('NativeModule'); - }); - it('return filename when it ends with .tsx', () => { - const filename = '/some_folder/NativeModule.tsx'; - const nativeModuleName = extractNativeModuleName(filename); - expect(nativeModuleName).toBe('NativeModule'); - }); - it('return filename when it ends with .android.js', () => { - const filename = '/some_folder/NativeModule.android.js'; - const nativeModuleName = extractNativeModuleName(filename); - expect(nativeModuleName).toBe('NativeModule'); - }); - it('return filename when it ends with .android.ts', () => { - const filename = '/some_folder/NativeModule.android.ts'; - const nativeModuleName = extractNativeModuleName(filename); - expect(nativeModuleName).toBe('NativeModule'); - }); - it('return filename when it ends with .android.tsx', () => { - const filename = '/some_folder/NativeModule.android.tsx'; - const nativeModuleName = extractNativeModuleName(filename); - expect(nativeModuleName).toBe('NativeModule'); - }); - it('return filename when it ends with .ios.js', () => { - const filename = '/some_folder/NativeModule.ios.ts'; - const nativeModuleName = extractNativeModuleName(filename); - expect(nativeModuleName).toBe('NativeModule'); - }); - it('return filename when it ends with .ios.ts', () => { - const filename = '/some_folder/NativeModule.ios.ts'; - const nativeModuleName = extractNativeModuleName(filename); - expect(nativeModuleName).toBe('NativeModule'); - }); - it('return filename when it ends with .ios.tsx', () => { - const filename = '/some_folder/NativeModule.ios.tsx'; - const nativeModuleName = extractNativeModuleName(filename); - expect(nativeModuleName).toBe('NativeModule'); - }); - it('return filename when it ends with .windows.js', () => { - const filename = '/some_folder/NativeModule.windows.js'; - const nativeModuleName = extractNativeModuleName(filename); - expect(nativeModuleName).toBe('NativeModule'); - }); -}); - -describe('createParserErrorCapturer', () => { - describe("when function doesn't throw", () => { - it("returns result and doesn't change errors array", () => { - const [errors, guard] = createParserErrorCapturer(); - const fn = () => 'result'; - - const result = guard(fn); - expect(result).toBe('result'); - expect(errors).toHaveLength(0); - }); - }); - - describe('when function throws a ParserError', () => { - it('returns null and adds the error in errors array instead of throwing it', () => { - const [errors, guard] = createParserErrorCapturer(); - const ErrorThrown = new ParserError( - 'moduleName', - null, - 'Something went wrong :(', - ); - const fn = () => { - throw ErrorThrown; - }; - - const result = guard(fn); - expect(result).toBe(null); - expect(errors).toHaveLength(1); - expect(errors[0]).toEqual(ErrorThrown); - expect(() => guard(fn)).not.toThrow(); - }); - }); - - describe('when function throws another error', () => { - it("throws the error and doesn't change errors array", () => { - const [errors, guard] = createParserErrorCapturer(); - const errorMessage = 'Something else went wrong :('; - const fn = () => { - throw new Error(errorMessage); - }; - - expect(() => guard(fn)).toThrow(errorMessage); - expect(errors).toHaveLength(0); - }); - }); -}); - -describe('verifyPlatforms', () => { - it('exclude android given an iOS only module', () => { - let result = verifyPlatforms('NativeSampleTurboModule', [ - 'SampleTurboModuleIOS', - ]); - - expect(result.cxxOnly).toBe(false); - expect(result.excludedPlatforms).toEqual(['android']); - - result = verifyPlatforms('NativeSampleTurboModuleIOS', [ - 'SampleTurboModule', - ]); - expect(result.cxxOnly).toBe(false); - expect(result.excludedPlatforms).toEqual(['android']); - - result = verifyPlatforms('NativeSampleTurboModuleIOS', [ - 'SampleTurboModuleIOS', - ]); - expect(result.cxxOnly).toBe(false); - expect(result.excludedPlatforms).toEqual(['android']); - }); - - it('exclude iOS given an android only module', () => { - let result = verifyPlatforms('NativeSampleTurboModule', [ - 'SampleTurboModuleAndroid', - ]); - - expect(result.cxxOnly).toBe(false); - expect(result.excludedPlatforms).toEqual(['iOS']); - - result = verifyPlatforms('NativeSampleTurboModuleAndroid', [ - 'SampleTurboModule', - ]); - expect(result.cxxOnly).toBe(false); - expect(result.excludedPlatforms).toEqual(['iOS']); - - result = verifyPlatforms('NativeSampleTurboModuleAndroid', [ - 'SampleTurboModuleAndroid', - ]); - expect(result.cxxOnly).toBe(false); - expect(result.excludedPlatforms).toEqual(['iOS']); - }); - - it('exclude iOS and android given a Cxx only module', () => { - let result = verifyPlatforms('NativeSampleTurboModule', [ - 'SampleTurboModuleCxx', - ]); - - expect(result.cxxOnly).toBe(true); - expect(result.excludedPlatforms).toEqual(['iOS', 'android']); - - result = verifyPlatforms('NativeSampleTurboModuleCxx', [ - 'SampleTurboModule', - ]); - expect(result.cxxOnly).toBe(true); - expect(result.excludedPlatforms).toEqual(['iOS', 'android']); - - result = verifyPlatforms('NativeSampleTurboModuleCxx', [ - 'SampleTurboModuleCxx', - ]); - expect(result.cxxOnly).toBe(true); - expect(result.excludedPlatforms).toEqual(['iOS', 'android']); - }); -}); - -describe('visit', () => { - describe('when the astNode is null', () => { - it("doesn't call the visitor function", () => { - const visitorFunction = jest.fn(); - const visitor = { - itemType: visitorFunction, - }; - - const astNode = null; - - visit(astNode, visitor); - - expect(visitorFunction).not.toHaveBeenCalled(); - }); - }); - - describe('when the astNode is not an object', () => { - it("doesn't call the visitor function", () => { - const visitorFunction = jest.fn(); - const visitor = { - itemType: visitorFunction, - }; - - const astNode = 'astNode'; - - visit(astNode, visitor); - - expect(visitorFunction).not.toHaveBeenCalled(); - }); - }); - - describe('when the astNode is an object', () => { - describe("when the astNode has a string type that doesn't exist in the visitor object", () => { - it("doesn't call the visitor function", () => { - const visitorFunction = jest.fn(); - const visitor = { - itemType: visitorFunction, - }; - - const astNode = {type: 'itemTypeNotInVisitor'}; - - visit(astNode, visitor); - - expect(visitorFunction).not.toHaveBeenCalled(); - }); - }); - - describe('when the astNode has a string type that exists in the visitor object', () => { - it("doesn't call the visitor function", () => { - const visitorFunction = jest.fn(); - const visitor = { - itemType: visitorFunction, - }; - - const astNode = {type: 'itemType'}; - - visit(astNode, visitor); - - expect(visitorFunction).toHaveBeenCalledTimes(1); - }); - }); - - describe("when the astNode doesn't have a string type", () => { - it('iterates on every values of the astNode', () => { - const visitorFunction = jest.fn(); - const visitor = { - itemType1: visitorFunction, - itemType2: visitorFunction, - }; - - const astNode = { - firstChildNode: {type: 'itemType1'}, - secondChildNode: {type: 'itemType2'}, - thirdChildNode: {type: 'itemType3'}, - }; - - visit(astNode, visitor); - - expect(visitorFunction).toHaveBeenCalledTimes(2); - }); - }); - }); - - describe('when the astNode is an array', () => { - it('iterates on every values of the astNode', () => { - const visitorFunction = jest.fn(); - const visitor = { - itemType1: visitorFunction, - itemType2: visitorFunction, - }; - - const astNode = [ - {type: 'itemType1'}, - {type: 'itemType2'}, - {type: 'itemType3'}, - ]; - - visit(astNode, visitor); - - expect(visitorFunction).toHaveBeenCalledTimes(2); - }); - }); -}); - -describe('buildSchemaFromConfigType', () => { - const astMock = { - type: 'Program', - loc: { - source: null, - start: {line: 2, column: 10}, - end: {line: 16, column: 62}, - }, - range: [11, 373], - body: [], - comments: [], - errors: [], - }; - - const componentSchemaMock = { - filename: 'filename', - componentName: 'componentName', - extendsProps: [], - events: [], - props: [], - commands: [], - }; - - const moduleSchemaMock = { - type: 'NativeModule', - aliases: {}, - spec: {properties: []}, - moduleNames: [], - }; - - const wrapComponentSchemaMock = jest.fn(); - const buildComponentSchemaMock = jest.fn(() => componentSchemaMock); - const wrapModuleSchemaMock = jest.spyOn( - require('../parsers-commons'), - 'wrapModuleSchema', - ); - const buildModuleSchemaMock = jest.fn(() => moduleSchemaMock); - - const buildSchemaFromConfigTypeHelper = ( - configType: 'module' | 'component' | 'none', - filename: ?string, - ) => - buildSchemaFromConfigType( - configType, - filename, - astMock, - wrapComponentSchemaMock, - buildComponentSchemaMock, - buildModuleSchemaMock, - ); - - describe('when configType is none', () => { - it('returns an empty schema', () => { - const schema = buildSchemaFromConfigTypeHelper('none'); - - expect(schema).toEqual({modules: {}}); - }); - }); - - describe('when configType is component', () => { - it('calls buildComponentSchema with ast and wrapComponentSchema with the result', () => { - buildSchemaFromConfigTypeHelper('component'); - - expect(buildComponentSchemaMock).toHaveBeenCalledTimes(1); - expect(buildComponentSchemaMock).toHaveBeenCalledWith(astMock); - expect(wrapComponentSchemaMock).toHaveBeenCalledTimes(1); - expect(wrapComponentSchemaMock).toHaveBeenCalledWith(componentSchemaMock); - - expect(buildModuleSchemaMock).not.toHaveBeenCalled(); - expect(wrapModuleSchemaMock).not.toHaveBeenCalled(); - }); - }); - - describe('when configType is module', () => { - describe('when filename is undefined', () => { - it('throws an error', () => { - expect(() => buildSchemaFromConfigTypeHelper('module')).toThrow( - 'Filepath expected while parasing a module', - ); - }); - }); - - describe('when filename is null', () => { - it('throws an error', () => { - expect(() => buildSchemaFromConfigTypeHelper('module', null)).toThrow( - 'Filepath expected while parasing a module', - ); - }); - }); - - describe('when filename is defined and not null', () => { - describe('when buildModuleSchema throws', () => { - it('throws the error', () => { - const parserError = new ParserError( - 'moduleName', - astMock, - 'Something went wrong', - ); - buildModuleSchemaMock.mockImplementationOnce(() => { - throw parserError; - }); - - expect(() => - buildSchemaFromConfigTypeHelper('module', 'filename'), - ).toThrow(parserError); - }); - }); - - describe('when buildModuleSchema returns null', () => { - it('throws an error', () => { - // $FlowIgnore[incompatible-call] - This is to test an invariant - buildModuleSchemaMock.mockReturnValueOnce(null); - - expect(() => - buildSchemaFromConfigTypeHelper('module', 'filename'), - ).toThrow( - 'When there are no parsing errors, the schema should not be null', - ); - }); - }); - - describe('when buildModuleSchema returns a schema', () => { - it('calls buildModuleSchema with ast and wrapModuleSchema with the result', () => { - buildSchemaFromConfigTypeHelper('module', 'filename'); - - expect(buildModuleSchemaMock).toHaveBeenCalledTimes(1); - expect(buildModuleSchemaMock).toHaveBeenCalledWith( - 'filename', - astMock, - expect.any(Function), - ); - expect(wrapModuleSchemaMock).toHaveBeenCalledTimes(1); - expect(wrapModuleSchemaMock).toHaveBeenCalledWith( - moduleSchemaMock, - 'filename', - ); - - expect(buildComponentSchemaMock).not.toHaveBeenCalled(); - expect(wrapComponentSchemaMock).not.toHaveBeenCalled(); - }); - }); - }); - }); - - describe('isModuleRegistryCall', () => { - describe('when node is not of CallExpression type', () => { - it('returns false', () => { - const node = { - type: 'NotCallExpression', - }; - expect(isModuleRegistryCall(node)).toBe(false); - }); - }); - - describe('when node is of CallExpressionType', () => { - describe('when callee type is not of MemberExpression type', () => { - it('returns false', () => { - const node = { - type: 'CallExpression', - callee: { - type: 'NotMemberExpression', - }, - }; - expect(isModuleRegistryCall(node)).toBe(false); - }); - }); - - describe('when callee type is of MemberExpression type', () => { - describe('when memberExpression has an object of type different than "Identifier"', () => { - it('returns false', () => { - const node = { - type: 'CallExpression', - callee: { - type: 'MemberExpression', - object: { - type: 'NotIdentifier', - name: 'TurboModuleRegistry', - }, - }, - }; - expect(isModuleRegistryCall(node)).toBe(false); - }); - }); - - describe('when memberExpression has an object of name different than "TurboModuleRegistry"', () => { - it('returns false', () => { - const node = { - type: 'CallExpression', - callee: { - type: 'MemberExpression', - object: { - type: 'Identifier', - name: 'NotTurboModuleRegistry', - }, - }, - }; - expect(isModuleRegistryCall(node)).toBe(false); - }); - }); - - describe('when memberExpression has an object of type "Identifier" and name "TurboModuleRegistry', () => { - describe('when memberExpression has a property of type different than "Identifier"', () => { - it('returns false', () => { - const node = { - type: 'CallExpression', - callee: { - type: 'MemberExpression', - object: { - type: 'Identifier', - name: 'TurboModuleRegistry', - }, - property: { - type: 'NotIdentifier', - name: 'get', - }, - }, - }; - expect(isModuleRegistryCall(node)).toBe(false); - }); - }); - - describe('when memberExpression has a property of name different than "get" or "getEnforcing', () => { - it('returns false', () => { - const node = { - type: 'CallExpression', - callee: { - type: 'MemberExpression', - object: { - type: 'Identifier', - name: 'TurboModuleRegistry', - }, - property: { - type: 'Identifier', - name: 'NotGet', - }, - }, - }; - expect(isModuleRegistryCall(node)).toBe(false); - }); - }); - - describe('when memberExpression has a property of type "Identifier" and of name "get" or "getEnforcing', () => { - describe('when memberExpression is computed', () => { - it('returns false', () => { - const node = { - type: 'CallExpression', - callee: { - type: 'MemberExpression', - object: { - type: 'Identifier', - name: 'TurboModuleRegistry', - }, - property: { - type: 'Identifier', - name: 'get', - }, - computed: true, - }, - }; - expect(isModuleRegistryCall(node)).toBe(false); - }); - }); - - describe('when memberExpression is not computed', () => { - it('returns true', () => { - const node = { - type: 'CallExpression', - callee: { - type: 'MemberExpression', - object: { - type: 'Identifier', - name: 'TurboModuleRegistry', - }, - property: { - type: 'Identifier', - name: 'get', - }, - computed: false, - }, - }; - expect(isModuleRegistryCall(node)).toBe(true); - }); - }); - }); - }); - }); - }); - }); -}); diff --git a/packages/react-native-codegen/src/parsers/consistency/__tests__/checkComponentSnaps-test.js b/packages/react-native-codegen/src/parsers/consistency/__tests__/checkComponentSnaps-test.js deleted file mode 100644 index c1088b1f0b0c..000000000000 --- a/packages/react-native-codegen/src/parsers/consistency/__tests__/checkComponentSnaps-test.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 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 - * @oncall react_native - */ - -'use strict'; - -const {compareSnaps, compareTsArraySnaps} = require('../compareSnaps.js'); - -const flowFixtures = require('../../flow/components/__test_fixtures__/fixtures.js'); -const flowSnaps = require('../../../../src/parsers/flow/components/__tests__/__snapshots__/component-parser-test.js.snap'); -const flowExtraCases = []; -const tsFixtures = require('../../typescript/components/__test_fixtures__/fixtures.js'); -const tsSnaps = require('../../../../src/parsers/typescript/components/__tests__/__snapshots__/typescript-component-parser-test.js.snap'); -const tsExtraCases = [ - 'ARRAY2_PROP_TYPES_NO_EVENTS', - 'PROPS_AND_EVENTS_WITH_INTERFACES', -]; -const ignoredCases = ['ARRAY_PROP_TYPES_NO_EVENTS']; - -compareSnaps( - flowFixtures, - flowSnaps, - flowExtraCases, - tsFixtures, - tsSnaps, - tsExtraCases, - ignoredCases, -); -compareTsArraySnaps(tsSnaps, tsExtraCases); diff --git a/packages/react-native-codegen/src/parsers/consistency/__tests__/checkModuleSnaps-test.js b/packages/react-native-codegen/src/parsers/consistency/__tests__/checkModuleSnaps-test.js deleted file mode 100644 index 1e392b8dde6b..000000000000 --- a/packages/react-native-codegen/src/parsers/consistency/__tests__/checkModuleSnaps-test.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 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 - * @oncall react_native - */ - -'use strict'; - -const {compareSnaps, compareTsArraySnaps} = require('../compareSnaps.js'); - -const flowFixtures = require('../../flow/modules/__test_fixtures__/fixtures.js'); -const flowSnaps = require('../../../../src/parsers/flow/modules/__tests__/__snapshots__/module-parser-snapshot-test.js.snap'); -const flowExtraCases = []; -const tsFixtures = require('../../typescript/modules/__test_fixtures__/fixtures.js'); -const tsSnaps = require('../../../../src/parsers/typescript/modules/__tests__/__snapshots__/typescript-module-parser-snapshot-test.js.snap'); -const tsExtraCases = [ - 'NATIVE_MODULE_WITH_ARRAY2_WITH_ALIAS', - 'NATIVE_MODULE_WITH_ARRAY2_WITH_UNION_AND_TOUPLE', - 'NATIVE_MODULE_WITH_BASIC_ARRAY2', - 'NATIVE_MODULE_WITH_COMPLEX_ARRAY2', -]; -const ignoredCases = []; - -compareSnaps( - flowFixtures, - flowSnaps, - flowExtraCases, - tsFixtures, - tsSnaps, - tsExtraCases, - ignoredCases, -); -compareTsArraySnaps(tsSnaps, tsExtraCases); diff --git a/packages/react-native-codegen/src/parsers/consistency/compareSnaps.js b/packages/react-native-codegen/src/parsers/consistency/compareSnaps.js deleted file mode 100644 index 51e1b740ce96..000000000000 --- a/packages/react-native-codegen/src/parsers/consistency/compareSnaps.js +++ /dev/null @@ -1,92 +0,0 @@ -/** - * 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 - * @oncall react_native - */ - -'use strict'; - -function compareSnaps( - flowFixtures, - flowSnaps, - flowExtraCases, - tsFixtures, - tsSnaps, - tsExtraCases, - ignoredCases, -) { - const flowCases = Object.keys(flowFixtures).sort(); - const tsCases = Object.keys(tsFixtures).sort(); - const commonCases = flowCases.filter(name => tsCases.indexOf(name) !== -1); - - describe('RN Codegen Parsers', () => { - it('should not unintentionally contains test case for Flow but not for TypeScript', () => { - expect( - flowCases.filter(name => commonCases.indexOf(name) === -1), - ).toEqual(flowExtraCases); - }); - - it('should not unintentionally contains test case for TypeScript but not for Flow', () => { - expect(tsCases.filter(name => commonCases.indexOf(name) === -1)).toEqual( - tsExtraCases, - ); - }); - - for (const commonCase of commonCases) { - const flowSnap = - flowSnaps[ - `RN Codegen Flow Parser can generate fixture ${commonCase} 1` - ]; - const tsSnap = - tsSnaps[ - `RN Codegen TypeScript Parser can generate fixture ${commonCase} 1` - ]; - - it(`should be able to find the snapshot for Flow for case ${commonCase}`, () => { - expect(typeof flowSnap).toEqual('string'); - }); - - it(`should be able to find the snapshot for TypeScript for case ${commonCase}`, () => { - expect(typeof tsSnap).toEqual('string'); - }); - - if (ignoredCases.indexOf(commonCase) === -1) { - it(`should generate the same snapshot from Flow and TypeScript for fixture ${commonCase}`, () => { - expect(flowSnap).toEqual(tsSnap); - }); - } else { - it(`should generate the different snapshot from Flow and TypeScript for fixture ${commonCase}`, () => { - expect(flowSnap).not.toEqual(tsSnap); - }); - } - } - }); -} - -function compareTsArraySnaps(tsSnaps, tsExtraCases) { - for (const array2Case of tsExtraCases.filter( - name => name.indexOf('ARRAY2') !== -1, - )) { - const arrayCase = array2Case.replace('ARRAY2', 'ARRAY'); - it(`should generate the same snap from fixture ${arrayCase} and ${array2Case}`, () => { - expect( - tsSnaps[ - `RN Codegen TypeScript Parser can generate fixture ${arrayCase}` - ], - ).toEqual( - tsSnaps[ - `RN Codegen TypeScript Parser can generate fixture ${array2Case}` - ], - ); - }); - } -} - -module.exports = { - compareSnaps, - compareTsArraySnaps, -}; diff --git a/packages/react-native-codegen/src/parsers/error-utils.js b/packages/react-native-codegen/src/parsers/error-utils.js deleted file mode 100644 index 2d53c82c9e6f..000000000000 --- a/packages/react-native-codegen/src/parsers/error-utils.js +++ /dev/null @@ -1,281 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {NativeModuleTypeAnnotation} from '../CodegenSchema'; -import type {ParserType} from './errors'; - -const { - MisnamedModuleInterfaceParserError, - UnsupportedFunctionReturnTypeAnnotationParserError, - ModuleInterfaceNotFoundParserError, - MoreThanOneModuleRegistryCallsParserError, - UnusedModuleInterfaceParserError, - IncorrectModuleRegistryCallArityParserError, - IncorrectModuleRegistryCallTypeParameterParserError, - UnsupportedObjectPropertyValueTypeAnnotationParserError, - UntypedModuleRegistryCallParserError, - UnsupportedModulePropertyParserError, - MoreThanOneModuleInterfaceParserError, - UnsupportedFunctionParamTypeAnnotationParserError, -} = require('./errors.js'); - -function throwIfModuleInterfaceIsMisnamed( - nativeModuleName: string, - moduleSpecId: $FlowFixMe, - parserType: ParserType, -) { - if (moduleSpecId.name !== 'Spec') { - throw new MisnamedModuleInterfaceParserError( - nativeModuleName, - moduleSpecId, - parserType, - ); - } -} - -function throwIfModuleInterfaceNotFound( - numberOfModuleSpecs: number, - nativeModuleName: string, - ast: $FlowFixMe, - parserType: ParserType, -) { - if (numberOfModuleSpecs === 0) { - throw new ModuleInterfaceNotFoundParserError( - nativeModuleName, - ast, - parserType, - ); - } -} - -function throwIfMoreThanOneModuleRegistryCalls( - hasteModuleName: string, - callExpressions: $FlowFixMe, - callExpressionsLength: number, - language: ParserType, -) { - if (callExpressions.length > 1) { - throw new MoreThanOneModuleRegistryCallsParserError( - hasteModuleName, - callExpressions, - callExpressionsLength, - language, - ); - } -} - -function throwIfUnusedModuleInterfaceParserError( - nativeModuleName: string, - moduleSpec: $FlowFixMe, - callExpressions: $FlowFixMe, - language: ParserType, -) { - if (callExpressions.length === 0) { - throw new UnusedModuleInterfaceParserError( - nativeModuleName, - moduleSpec, - language, - ); - } -} - -function throwIfWrongNumberOfCallExpressionArgs( - nativeModuleName: string, - flowCallExpression: $FlowFixMe, - methodName: string, - numberOfCallExpressionArgs: number, - language: ParserType, -) { - if (numberOfCallExpressionArgs !== 1) { - throw new IncorrectModuleRegistryCallArityParserError( - nativeModuleName, - flowCallExpression, - methodName, - numberOfCallExpressionArgs, - language, - ); - } -} - -function throwIfIncorrectModuleRegistryCallTypeParameterParserError( - nativeModuleName: string, - typeArguments: $FlowFixMe, - methodName: string, - moduleName: string, - language: ParserType, -) { - function throwError() { - throw new IncorrectModuleRegistryCallTypeParameterParserError( - nativeModuleName, - typeArguments, - methodName, - moduleName, - language, - ); - } - - if (language === 'Flow') { - if ( - typeArguments.type !== 'TypeParameterInstantiation' || - typeArguments.params.length !== 1 || - typeArguments.params[0].type !== 'GenericTypeAnnotation' || - typeArguments.params[0].id.name !== 'Spec' - ) { - throwError(); - } - } else if (language === 'TypeScript') { - if ( - typeArguments.type !== 'TSTypeParameterInstantiation' || - typeArguments.params.length !== 1 || - typeArguments.params[0].type !== 'TSTypeReference' || - typeArguments.params[0].typeName.name !== 'Spec' - ) { - throwError(); - } - } -} - -function throwIfUnsupportedFunctionReturnTypeAnnotationParserError( - nativeModuleName: string, - returnTypeAnnotation: $FlowFixMe, - invalidReturnType: string, - language: ParserType, - cxxOnly: boolean, - returnType: string, -) { - if (!cxxOnly && returnType === 'FunctionTypeAnnotation') { - throw new UnsupportedFunctionReturnTypeAnnotationParserError( - nativeModuleName, - returnTypeAnnotation.returnType, - 'FunctionTypeAnnotation', - language, - ); - } -} - -function throwIfUntypedModule( - typeArguments: $FlowFixMe, - hasteModuleName: string, - callExpression: $FlowFixMe, - methodName: string, - $moduleName: string, - language: ParserType, -) { - if (typeArguments == null) { - throw new UntypedModuleRegistryCallParserError( - hasteModuleName, - callExpression, - methodName, - $moduleName, - language, - ); - } -} - -function throwIfModuleTypeIsUnsupported( - nativeModuleName: string, - propertyValue: $FlowFixMe, - propertyName: string, - propertyValueType: string, - language: ParserType, -) { - if (language === 'Flow' && propertyValueType !== 'FunctionTypeAnnotation') { - throw new UnsupportedModulePropertyParserError( - nativeModuleName, - propertyValue, - propertyName, - propertyValueType, - language, - ); - } else if ( - language === 'TypeScript' && - propertyValueType !== 'TSFunctionType' && - propertyValueType !== 'TSMethodSignature' - ) { - throw new UnsupportedModulePropertyParserError( - nativeModuleName, - propertyValue, - propertyName, - propertyValueType, - language, - ); - } -} - -const UnsupportedObjectPropertyTypeToInvalidPropertyValueTypeMap = { - FunctionTypeAnnotation: 'FunctionTypeAnnotation', - VoidTypeAnnotation: 'void', - PromiseTypeAnnotation: 'Promise', -}; - -function throwIfPropertyValueTypeIsUnsupported( - moduleName: string, - propertyValue: $FlowFixMe, - propertyKey: string, - type: string, - language: ParserType, -) { - const invalidPropertyValueType = - UnsupportedObjectPropertyTypeToInvalidPropertyValueTypeMap[type]; - - throw new UnsupportedObjectPropertyValueTypeAnnotationParserError( - moduleName, - propertyValue, - propertyKey, - invalidPropertyValueType, - language, - ); -} - -function throwIfMoreThanOneModuleInterfaceParserError( - nativeModuleName: string, - moduleSpecs: $ReadOnlyArray<$FlowFixMe>, - parserType: ParserType, -) { - if (moduleSpecs.length > 1) { - throw new MoreThanOneModuleInterfaceParserError( - nativeModuleName, - moduleSpecs, - moduleSpecs.map(node => node.id.name), - parserType, - ); - } -} - -function throwIfUnsupportedFunctionParamTypeAnnotationParserError( - nativeModuleName: string, - languageParamTypeAnnotation: $FlowFixMe, - paramName: string, - paramTypeAnnotationType: NativeModuleTypeAnnotation['type'], -) { - throw new UnsupportedFunctionParamTypeAnnotationParserError( - nativeModuleName, - languageParamTypeAnnotation, - paramName, - paramTypeAnnotationType, - ); -} - -module.exports = { - throwIfModuleInterfaceIsMisnamed, - throwIfUnsupportedFunctionReturnTypeAnnotationParserError, - throwIfModuleInterfaceNotFound, - throwIfMoreThanOneModuleRegistryCalls, - throwIfPropertyValueTypeIsUnsupported, - throwIfUnusedModuleInterfaceParserError, - throwIfWrongNumberOfCallExpressionArgs, - throwIfIncorrectModuleRegistryCallTypeParameterParserError, - throwIfUntypedModule, - throwIfModuleTypeIsUnsupported, - throwIfMoreThanOneModuleInterfaceParserError, - throwIfUnsupportedFunctionParamTypeAnnotationParserError, -}; diff --git a/packages/react-native-codegen/src/parsers/errors.js b/packages/react-native-codegen/src/parsers/errors.js deleted file mode 100644 index b736a5979b14..000000000000 --- a/packages/react-native-codegen/src/parsers/errors.js +++ /dev/null @@ -1,441 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type {UnionTypeAnnotationMemberType} from '../CodegenSchema'; - -import type {Parser} from './parser'; -export type ParserType = 'Flow' | 'TypeScript'; - -class ParserError extends Error { - nodes: $ReadOnlyArray<$FlowFixMe>; - constructor( - nativeModuleName: string, - astNodeOrNodes: $FlowFixMe, - message: string, - ) { - super(`Module ${nativeModuleName}: ${message}`); - - this.nodes = Array.isArray(astNodeOrNodes) - ? astNodeOrNodes - : [astNodeOrNodes]; - - // assign the error class name in your custom error (as a shortcut) - this.name = this.constructor.name; - - // capturing the stack trace keeps the reference to your error class - Error.captureStackTrace(this, this.constructor); - } -} -class MisnamedModuleInterfaceParserError extends ParserError { - constructor(nativeModuleName: string, id: $FlowFixMe, language: ParserType) { - super( - nativeModuleName, - id, - `All ${language} interfaces extending TurboModule must be called 'Spec'. Please rename ${language} interface '${id.name}' to 'Spec'.`, - ); - } -} - -class ModuleInterfaceNotFoundParserError extends ParserError { - constructor(nativeModuleName: string, ast: $FlowFixMe, language: ParserType) { - super( - nativeModuleName, - ast, - `No ${language} interfaces extending TurboModule were detected in this NativeModule spec.`, - ); - } -} - -class MoreThanOneModuleInterfaceParserError extends ParserError { - constructor( - nativeModuleName: string, - flowModuleInterfaces: $ReadOnlyArray<$FlowFixMe>, - names: $ReadOnlyArray, - language: ParserType, - ) { - const finalName = names[names.length - 1]; - const allButLastName = names.slice(0, -1); - const quote = (x: string) => `'${x}'`; - - const nameStr = - allButLastName.map(quote).join(', ') + ', and ' + quote(finalName); - - super( - nativeModuleName, - flowModuleInterfaces, - `Every NativeModule spec file must declare exactly one NativeModule ${language} interface. This file declares ${names.length}: ${nameStr}. Please remove the extraneous ${language} interface declarations.`, - ); - } -} - -class UnsupportedModulePropertyParserError extends ParserError { - constructor( - nativeModuleName: string, - propertyValue: $FlowFixMe, - propertyName: string, - invalidPropertyValueType: string, - language: ParserType, - ) { - super( - nativeModuleName, - propertyValue, - `${language} interfaces extending TurboModule must only contain 'FunctionTypeAnnotation's. Property '${propertyName}' refers to a '${invalidPropertyValueType}'.`, - ); - } -} - -class UnsupportedTypeAnnotationParserError extends ParserError { - +typeAnnotationType: string; - constructor( - nativeModuleName: string, - typeAnnotation: $FlowFixMe, - language: ParserType, - ) { - super( - nativeModuleName, - typeAnnotation, - `${language} type annotation '${typeAnnotation.type}' is unsupported in NativeModule specs.`, - ); - - this.typeAnnotationType = typeAnnotation.type; - } -} - -class UnsupportedGenericParserError extends ParserError { - // +genericName: string; - constructor( - nativeModuleName: string, - genericTypeAnnotation: $FlowFixMe, - parser: Parser, - ) { - const genericName = parser.nameForGenericTypeAnnotation( - genericTypeAnnotation, - ); - super( - nativeModuleName, - genericTypeAnnotation, - `Unrecognized generic type '${genericName}' in NativeModule spec.`, - ); - - // this.genericName = genericName; - } -} - -class MissingTypeParameterGenericParserError extends ParserError { - constructor( - nativeModuleName: string, - genericTypeAnnotation: $FlowFixMe, - language: ParserType, - ) { - const genericName = - language === 'TypeScript' - ? genericTypeAnnotation.typeName.name - : genericTypeAnnotation.id.name; - - super( - nativeModuleName, - genericTypeAnnotation, - `Generic '${genericName}' must have type parameters.`, - ); - } -} - -class MoreThanOneTypeParameterGenericParserError extends ParserError { - constructor( - nativeModuleName: string, - genericTypeAnnotation: $FlowFixMe, - language: ParserType, - ) { - const genericName = - language === 'TypeScript' - ? genericTypeAnnotation.typeName.name - : genericTypeAnnotation.id.name; - - super( - nativeModuleName, - genericTypeAnnotation, - `Generic '${genericName}' must have exactly one type parameter.`, - ); - } -} - -/** - * Array parsing errors - */ - -class UnsupportedArrayElementTypeAnnotationParserError extends ParserError { - constructor( - nativeModuleName: string, - arrayElementTypeAST: $FlowFixMe, - arrayType: 'Array' | '$ReadOnlyArray' | 'ReadonlyArray', - invalidArrayElementType: string, - language: ParserType, - ) { - super( - nativeModuleName, - arrayElementTypeAST, - `${arrayType} element types cannot be '${invalidArrayElementType}'.`, - ); - } -} - -/** - * Object parsing errors - */ - -class UnsupportedObjectPropertyTypeAnnotationParserError extends ParserError { - constructor( - nativeModuleName: string, - propertyAST: $FlowFixMe, - invalidPropertyType: string, - language: ParserType, - ) { - let message = `'ObjectTypeAnnotation' cannot contain '${invalidPropertyType}'.`; - - if ( - invalidPropertyType === 'ObjectTypeSpreadProperty' && - language !== 'TypeScript' - ) { - message = "Object spread isn't supported in 'ObjectTypeAnnotation's."; - } - - super(nativeModuleName, propertyAST, message); - } -} - -class UnsupportedObjectPropertyValueTypeAnnotationParserError extends ParserError { - constructor( - nativeModuleName: string, - propertyValueAST: $FlowFixMe, - propertyName: string, - invalidPropertyValueType: string, - language: ParserType, - ) { - super( - nativeModuleName, - propertyValueAST, - `Object property '${propertyName}' cannot have type '${invalidPropertyValueType}'.`, - ); - } -} - -/** - * Function parsing errors - */ - -class UnnamedFunctionParamParserError extends ParserError { - constructor( - functionParam: $FlowFixMe, - nativeModuleName: string, - language: ParserType, - ) { - super( - nativeModuleName, - functionParam, - 'All function parameters must be named.', - ); - } -} - -class UnsupportedFunctionParamTypeAnnotationParserError extends ParserError { - constructor( - nativeModuleName: string, - flowParamTypeAnnotation: $FlowFixMe, - paramName: string, - invalidParamType: string, - ) { - super( - nativeModuleName, - flowParamTypeAnnotation, - `Function parameter '${paramName}' cannot have type '${invalidParamType}'.`, - ); - } -} - -class UnsupportedFunctionReturnTypeAnnotationParserError extends ParserError { - constructor( - nativeModuleName: string, - flowReturnTypeAnnotation: $FlowFixMe, - invalidReturnType: string, - language: ParserType, - ) { - super( - nativeModuleName, - flowReturnTypeAnnotation, - `Function return cannot have type '${invalidReturnType}'.`, - ); - } -} - -/** - * Enum parsing errors - */ - -class UnsupportedEnumDeclarationParserError extends ParserError { - constructor( - nativeModuleName: string, - arrayElementTypeAST: $FlowFixMe, - memberType: string, - language: ParserType, - ) { - super( - nativeModuleName, - arrayElementTypeAST, - `Unexpected enum member type ${memberType}. Only string and number enum members are supported`, - ); - } -} - -/** - * Union parsing errors - */ - -class UnsupportedUnionTypeAnnotationParserError extends ParserError { - constructor( - nativeModuleName: string, - arrayElementTypeAST: $FlowFixMe, - types: UnionTypeAnnotationMemberType[], - language: ParserType, - ) { - super( - nativeModuleName, - arrayElementTypeAST, - `Union members must be of the same type, but multiple types were found ${types.join( - ', ', - )}'.`, - ); - } -} - -/** - * Module parsing errors - */ - -class UnusedModuleInterfaceParserError extends ParserError { - constructor( - nativeModuleName: string, - flowInterface: $FlowFixMe, - language: ParserType, - ) { - super( - nativeModuleName, - flowInterface, - "Unused NativeModule spec. Please load the NativeModule by calling TurboModuleRegistry.get('').", - ); - } -} - -class MoreThanOneModuleRegistryCallsParserError extends ParserError { - constructor( - nativeModuleName: string, - flowCallExpressions: $FlowFixMe, - numCalls: number, - language: ParserType, - ) { - super( - nativeModuleName, - flowCallExpressions, - `Every NativeModule spec file must contain exactly one NativeModule load. This file contains ${numCalls}. Please simplify this spec file, splitting it as necessary, to remove the extraneous loads.`, - ); - } -} - -class UntypedModuleRegistryCallParserError extends ParserError { - constructor( - nativeModuleName: string, - flowCallExpression: $FlowFixMe, - methodName: string, - moduleName: string, - language: ParserType, - ) { - super( - nativeModuleName, - flowCallExpression, - `Please type this NativeModule load: TurboModuleRegistry.${methodName}('${moduleName}').`, - ); - } -} - -class IncorrectModuleRegistryCallTypeParameterParserError extends ParserError { - constructor( - nativeModuleName: string, - flowTypeArguments: $FlowFixMe, - methodName: string, - moduleName: string, - language: ParserType, - ) { - super( - nativeModuleName, - flowTypeArguments, - `Please change these type arguments to reflect TurboModuleRegistry.${methodName}('${moduleName}').`, - ); - } -} - -class IncorrectModuleRegistryCallArityParserError extends ParserError { - constructor( - nativeModuleName: string, - flowCallExpression: $FlowFixMe, - methodName: string, - incorrectArity: number, - language: ParserType, - ) { - super( - nativeModuleName, - flowCallExpression, - `Please call TurboModuleRegistry.${methodName}() with exactly one argument. Detected ${incorrectArity}.`, - ); - } -} - -class IncorrectModuleRegistryCallArgumentTypeParserError extends ParserError { - constructor( - nativeModuleName: string, - flowArgument: $FlowFixMe, - methodName: string, - type: string, - language: ParserType, - ) { - const a = /[aeiouy]/.test(type.toLowerCase()) ? 'an' : 'a'; - super( - nativeModuleName, - flowArgument, - `Please call TurboModuleRegistry.${methodName}() with a string literal. Detected ${a} '${type}'`, - ); - } -} - -module.exports = { - ParserError, - MissingTypeParameterGenericParserError, - MoreThanOneTypeParameterGenericParserError, - MisnamedModuleInterfaceParserError, - ModuleInterfaceNotFoundParserError, - MoreThanOneModuleInterfaceParserError, - UnnamedFunctionParamParserError, - UnsupportedArrayElementTypeAnnotationParserError, - UnsupportedGenericParserError, - UnsupportedTypeAnnotationParserError, - UnsupportedFunctionParamTypeAnnotationParserError, - UnsupportedFunctionReturnTypeAnnotationParserError, - UnsupportedEnumDeclarationParserError, - UnsupportedUnionTypeAnnotationParserError, - UnsupportedModulePropertyParserError, - UnsupportedObjectPropertyTypeAnnotationParserError, - UnsupportedObjectPropertyValueTypeAnnotationParserError, - UnusedModuleInterfaceParserError, - MoreThanOneModuleRegistryCallsParserError, - UntypedModuleRegistryCallParserError, - IncorrectModuleRegistryCallTypeParameterParserError, - IncorrectModuleRegistryCallArityParserError, - IncorrectModuleRegistryCallArgumentTypeParserError, -}; diff --git a/packages/react-native-codegen/src/parsers/flow/components/__test_fixtures__/failures.js b/packages/react-native-codegen/src/parsers/flow/components/__test_fixtures__/failures.js deleted file mode 100644 index 1d7072636a48..000000000000 --- a/packages/react-native-codegen/src/parsers/flow/components/__test_fixtures__/failures.js +++ /dev/null @@ -1,600 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -// @licenselint-loose-mode - -'use strict'; - -const COMMANDS_DEFINED_INLINE = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -const codegenNativeCommands = require('codegenNativeCommands'); -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {Int32} from 'CodegenTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -export type ModuleProps = $ReadOnly<{| - ...ViewProps, - // No props -|}>; - -export const Commands = codegenNativeCommands<{ - +hotspotUpdate: (ref: React.Ref<'RCTView'>, x: Int32, y: Int32) => void, -}>({ - supportedCommands: ['hotspotUpdate'], -}); - -export default (codegenNativeComponent( - 'Module', -): HostComponent); -`; - -const COMMANDS_DEFINED_MULTIPLE_TIMES = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -const codegenNativeCommands = require('codegenNativeCommands'); -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {Int32} from 'CodegenTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -interface NativeCommands { - +hotspotUpdate: (viewRef: React.Ref<'RCTView'>, x: Int32, y: Int32) => void; -} - -export type ModuleProps = $ReadOnly<{| - ...ViewProps, - // No props or events -|}>; - -export const Commands = codegenNativeCommands({ - supportedCommands: ['hotspotUpdate'], -}); -export const Commands2 = codegenNativeCommands({ - supportedCommands: ['hotspotUpdate'], -}); - -export default (codegenNativeComponent( - 'Module', -): HostComponent); -`; - -const COMMANDS_DEFINED_WITHOUT_REF = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -const codegenNativeCommands = require('codegenNativeCommands'); -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {Int32} from 'CodegenTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -interface NativeCommands { - +hotspotUpdate: (x: Int32, y: Int32) => void; -} - -export type ModuleProps = $ReadOnly<{| - ...ViewProps, - // No props or events -|}>; - -export const Commands = codegenNativeCommands({ - supportedCommands: ['hotspotUpdate'], -}); - -export default (codegenNativeComponent( - 'Module', -): HostComponent); -`; - -const COMMANDS_DEFINED_WITH_NULLABLE_REF = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -const codegenNativeCommands = require('codegenNativeCommands'); -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {Int32} from 'CodegenTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -interface NativeCommands { - +hotspotUpdate: (viewRef: ?React.Ref<'RCTView'>, x: Int32, y: Int32) => void; -} - -export type ModuleProps = $ReadOnly<{| - ...ViewProps, - // No props or events -|}>; - -export const Commands = codegenNativeCommands({ - supportedCommands: ['hotspotUpdate'], -}); - -export default (codegenNativeComponent( - 'Module', -): HostComponent); -`; - -const COMMANDS_DEFINED_WITH_MISMATCHED_METHOD_NAMES = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -const codegenNativeCommands = require('codegenNativeCommands'); -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {Int32} from 'CodegenTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -interface NativeCommands { - +hotspotUpdate: (viewRef: React.Ref<'RCTView'>, x: Int32, y: Int32) => void; - +scrollTo: ( - viewRef: React.Ref<'RCTView'>, - y: Int32, - animated: boolean, - ) => void; -} - -export type ModuleProps = $ReadOnly<{| - ...ViewProps, - // No props or events -|}>; - -export const Commands = codegenNativeCommands({ - supportedCommands: ['scrollTo'], -}); - -export default (codegenNativeComponent( - 'Module', -): HostComponent); -`; - -const COMMANDS_DEFINED_WITHOUT_METHOD_NAMES = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -const codegenNativeCommands = require('codegenNativeCommands'); -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {Int32} from 'CodegenTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -interface NativeCommands { - +hotspotUpdate: (viewRef: React.Ref<'RCTView'>, x: Int32, y: Int32) => void; - +scrollTo: ( - viewRef: React.Ref<'RCTView'>, - y: Int32, - animated: boolean, - ) => void; -} - -export type ModuleProps = $ReadOnly<{| - ...ViewProps, - // No props or events -|}>; - -export const Commands = codegenNativeCommands(); - -export default (codegenNativeComponent( - 'Module', -): HostComponent); -`; - -const NULLABLE_WITH_DEFAULT = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {WithDefault, Float} from 'CodegenTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -export type ModuleProps = $ReadOnly<{| - ...ViewProps, - nullable_with_default: ?WithDefault, -|}>; - -export default (codegenNativeComponent( - 'Module', -): HostComponent); -`; - -const NON_OPTIONAL_KEY_WITH_DEFAULT_VALUE = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {WithDefault, Float} from 'CodegenTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -export type ModuleProps = $ReadOnly<{| - ...ViewProps, - required_key_with_default: WithDefault, -|}>; - -export default (codegenNativeComponent( - 'Module', -): HostComponent); -`; - -const PROPS_CONFLICT_NAMES = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -export type ModuleProps = $ReadOnly<{| - ...ViewProps, - isEnabled: string, - - isEnabled: boolean, -|}>; - -export default (codegenNativeComponent( - 'Module', -): HostComponent); -`; - -const PROPS_CONFLICT_WITH_SPREAD_PROPS = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -type PropsInFile = $ReadOnly<{| - isEnabled: boolean, -|}>; - -export type ModuleProps = $ReadOnly<{| - ...ViewProps, - - ...PropsInFile, - isEnabled: boolean, -|}>; - -export default (codegenNativeComponent( - 'Module', -): HostComponent); -`; - -const PROPS_SPREAD_CONFLICTS_WITH_PROPS = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -type PropsInFile = $ReadOnly<{| - isEnabled: boolean, -|}>; - -export type ModuleProps = $ReadOnly<{| - ...ViewProps, - - isEnabled: boolean, - ...PropsInFile, -|}>; - -export default (codegenNativeComponent( - 'Module', -): HostComponent); -`; - -const PROP_NUMBER_TYPE = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -export type ModuleProps = $ReadOnly<{| - ...ViewProps, - - someProp: number -|}>; - -export default (codegenNativeComponent( - 'Module', -): HostComponent); -`; - -const PROP_MIXED_ENUM = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -export type ModuleProps = $ReadOnly<{| - ...ViewProps, - - someProp?: WithDefault<'foo' | 1, 1> -|}>; - -export default (codegenNativeComponent( - 'Module', -): HostComponent); -`; - -const PROP_ENUM_BOOLEAN = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -export type ModuleProps = $ReadOnly<{| - ...ViewProps, - - someProp?: WithDefault -|}>; - -export default (codegenNativeComponent( - 'Module', -): HostComponent); -`; - -const PROP_ARRAY_MIXED_ENUM = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -export type ModuleProps = $ReadOnly<{| - ...ViewProps, - - someProp?: WithDefault<$ReadOnlyArray<'foo' | 1>, 1> -|}>; - -export default (codegenNativeComponent( - 'Module', -): HostComponent); -`; - -const PROP_ARRAY_ENUM_BOOLEAN = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -export type ModuleProps = $ReadOnly<{| - ...ViewProps, - - someProp?: WithDefault<$ReadOnlyArray, false> -|}>; - -export default (codegenNativeComponent( - 'Module', -): HostComponent); -`; - -const PROP_ARRAY_ENUM_INT = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -export type ModuleProps = $ReadOnly<{| - ...ViewProps, - - someProp?: WithDefault<$ReadOnlyArray<0 | 1>, 0> -|}>; - -export default (codegenNativeComponent( - 'Module', -): HostComponent); -`; - -module.exports = { - COMMANDS_DEFINED_INLINE, - COMMANDS_DEFINED_MULTIPLE_TIMES, - COMMANDS_DEFINED_WITH_MISMATCHED_METHOD_NAMES, - COMMANDS_DEFINED_WITHOUT_METHOD_NAMES, - COMMANDS_DEFINED_WITHOUT_REF, - COMMANDS_DEFINED_WITH_NULLABLE_REF, - NULLABLE_WITH_DEFAULT, - NON_OPTIONAL_KEY_WITH_DEFAULT_VALUE, - PROPS_CONFLICT_NAMES, - PROPS_CONFLICT_WITH_SPREAD_PROPS, - PROPS_SPREAD_CONFLICTS_WITH_PROPS, - PROP_NUMBER_TYPE, - PROP_MIXED_ENUM, - PROP_ENUM_BOOLEAN, - PROP_ARRAY_MIXED_ENUM, - PROP_ARRAY_ENUM_BOOLEAN, - PROP_ARRAY_ENUM_INT, -}; diff --git a/packages/react-native-codegen/src/parsers/flow/components/__test_fixtures__/fixtures.js b/packages/react-native-codegen/src/parsers/flow/components/__test_fixtures__/fixtures.js deleted file mode 100644 index c597a2d1f5df..000000000000 --- a/packages/react-native-codegen/src/parsers/flow/components/__test_fixtures__/fixtures.js +++ /dev/null @@ -1,1016 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -// @licenselint-loose-mode - -'use strict'; - -const EVENT_DEFINITION = ` - boolean_required: boolean, - boolean_optional_key?: boolean, - boolean_optional_value: ?boolean, - boolean_optional_both?: ?boolean, - - string_required: string, - string_optional_key?: string, - string_optional_value: ?string, - string_optional_both?: ?string, - - double_required: Double, - double_optional_key?: Double, - double_optional_value: ?Double, - double_optional_both?: ?Double, - - float_required: Float, - float_optional_key?: Float, - float_optional_value: ?Float, - float_optional_both?: ?Float, - - int32_required: Int32, - int32_optional_key?: Int32, - int32_optional_value: ?Int32, - int32_optional_both?: ?Int32, - - enum_required: ('small' | 'large'), - enum_optional_key?: ('small' | 'large'), - enum_optional_value: ?('small' | 'large'), - enum_optional_both?: ?('small' | 'large'), - - object_required: { - boolean_required: boolean, - }, - - object_optional_key?: { - string_optional_key?: string, - }, - - object_optional_value: ?{ - float_optional_value: ?Float, - }, - - object_optional_both?: ?{ - int32_optional_both?: ?Int32, - }, - - object_required_nested_2_layers: { - object_optional_nested_1_layer?: ?{ - boolean_required: Int32, - string_optional_key?: string, - double_optional_value: ?Double, - float_optional_value: ?Float, - int32_optional_both?: ?Int32, - } - }, - - object_readonly_required: $ReadOnly<{ - boolean_required: boolean, - }>, - - object_readonly_optional_key?: $ReadOnly<{ - string_optional_key?: string, - }>, - - object_readonly_optional_value: ?$ReadOnly<{ - float_optional_value: ?Float, - }>, - - object_readonly_optional_both?: ?$ReadOnly<{ - int32_optional_both?: ?Int32, - }>, -`; - -const ONE_OF_EACH_PROP_EVENT_DEFAULT_AND_OPTIONS = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type { - BubblingEventHandler, - DirectEventHandler, - WithDefault, -} from 'CodegenTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -type ModuleProps = $ReadOnly<{| - ...ViewProps, - - // Props - boolean_default_true_optional_both?: WithDefault, - - // Events - onDirectEventDefinedInlineNull: DirectEventHandler, - onBubblingEventDefinedInlineNull: BubblingEventHandler, -|}>; - -export default (codegenNativeComponent('Module', { - interfaceOnly: true, - paperComponentName: 'RCTModule', -}): HostComponent); -`; - -const ONE_OF_EACH_PROP_EVENT_DEFAULT_AND_OPTIONS_NO_CAST = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type { - BubblingEventHandler, - DirectEventHandler, - WithDefault, -} from 'CodegenTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -type ModuleProps = $ReadOnly<{| - ...ViewProps, - - // Props - boolean_default_true_optional_both?: WithDefault, - - // Events - onDirectEventDefinedInlineNull: DirectEventHandler, - onBubblingEventDefinedInlineNull: BubblingEventHandler, -|}>; - -export default codegenNativeComponent('Module', { - interfaceOnly: true, - excludedPlatforms: ['android'], - paperComponentName: 'RCTModule', -}); -`; - -const NO_PROPS_EVENTS_ONLY_DEPRECATED_VIEW_CONFIG_NAME_OPTION = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -type ModuleProps = $ReadOnly<{| - ...ViewProps, -|}>; - -export default (codegenNativeComponent('Module', { - deprecatedViewConfigName: 'DeprecateModuleName', -}): HostComponent); -`; - -const ALL_PROP_TYPES_NO_EVENTS = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {Int32, Double, Float, WithDefault} from 'CodegenTypes'; -import type {ImageSource} from 'ImageSource'; -import type {ColorValue, ColorArrayValue, PointValue, EdgeInsetsValue} from 'StyleSheetTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -type ModuleProps = $ReadOnly<{| - ...ViewProps, - - // Props - // Boolean props - boolean_required: boolean, - boolean_optional_key?: WithDefault, - boolean_optional_both?: WithDefault, - - // Boolean props, null default - boolean_null_optional_key?: WithDefault, - boolean_null_optional_both?: WithDefault, - - // String props - string_required: string, - string_optional_key?: WithDefault, - string_optional_both?: WithDefault, - - // String props, null default - string_null_optional_key?: WithDefault, - string_null_optional_both?: WithDefault, - - // Stringish props - stringish_required: Stringish, - stringish_optional_key?: WithDefault, - stringish_optional_both?: WithDefault, - - // Stringish props, null default - stringish_null_optional_key?: WithDefault, - stringish_null_optional_both?: WithDefault, - - // Double props - double_required: Double, - double_optional_key?: WithDefault, - double_optional_both?: WithDefault, - - // Float props - float_required: Float, - float_optional_key?: WithDefault, - float_optional_both?: WithDefault, - - // Float props, null default - float_null_optional_key?: WithDefault, - float_null_optional_both?: WithDefault, - - // Int32 props - int32_required: Int32, - int32_optional_key?: WithDefault, - int32_optional_both?: WithDefault, - - // String enum props - enum_optional_key?: WithDefault<'small' | 'large', 'small'>, - enum_optional_both?: WithDefault<'small' | 'large', 'small'>, - - // Int enum props - int_enum_optional_key?: WithDefault<0 | 1, 0>, - - // Object props - object_optional_key?: $ReadOnly<{| prop: string |}>, - object_optional_both?: ?$ReadOnly<{| prop: string |}>, - object_optional_value: ?$ReadOnly<{| prop: string |}>, - - // ImageSource props - image_required: ImageSource, - image_optional_value: ?ImageSource, - image_optional_both?: ?ImageSource, - - // ColorValue props - color_required: ColorValue, - color_optional_key?: ColorValue, - color_optional_value: ?ColorValue, - color_optional_both?: ?ColorValue, - - // ColorArrayValue props - color_array_required: ColorArrayValue, - color_array_optional_key?: ColorArrayValue, - color_array_optional_value: ?ColorArrayValue, - color_array_optional_both?: ?ColorArrayValue, - - // ProcessedColorValue props - processed_color_required: ProcessedColorValue, - processed_color_optional_key?: ProcessedColorValue, - processed_color_optional_value: ?ProcessedColorValue, - processed_color_optional_both?: ?ProcessedColorValue, - - // PointValue props - point_required: PointValue, - point_optional_key?: PointValue, - point_optional_value: ?PointValue, - point_optional_both?: ?PointValue, - - // EdgeInsets props - insets_required: EdgeInsetsValue, - insets_optional_key?: EdgeInsetsValue, - insets_optional_value: ?EdgeInsetsValue, - insets_optional_both?: ?EdgeInsetsValue, -|}>; - -export default (codegenNativeComponent( - 'Module', -): HostComponent); -`; - -const ARRAY_PROP_TYPES_NO_EVENTS = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {Int32, Double, Float, WithDefault} from 'CodegenTypes'; -import type {ImageSource} from 'ImageSource'; -import type {ColorValue, PointValue, ProcessColorValue, EdgeInsetsValue} from 'StyleSheetTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -type ObjectType = $ReadOnly<{| prop: string |}>; -type ArrayObjectType = $ReadOnlyArray<$ReadOnly<{| prop: string |}>>; - -type ModuleProps = $ReadOnly<{| - ...ViewProps, - - // Props - // Boolean props - array_boolean_required: $ReadOnlyArray, - array_boolean_optional_key?: $ReadOnlyArray, - array_boolean_optional_value: ?$ReadOnlyArray, - array_boolean_optional_both?: ?$ReadOnlyArray, - - // String props - array_string_required: $ReadOnlyArray, - array_string_optional_key?: $ReadOnlyArray, - array_string_optional_value: ?$ReadOnlyArray, - array_string_optional_both?: ?$ReadOnlyArray, - - // Double props - array_double_required: $ReadOnlyArray, - array_double_optional_key?: $ReadOnlyArray, - array_double_optional_value: ?$ReadOnlyArray, - array_double_optional_both?: ?$ReadOnlyArray, - - // Float props - array_float_required: $ReadOnlyArray, - array_float_optional_key?: $ReadOnlyArray, - array_float_optional_value: ?$ReadOnlyArray, - array_float_optional_both?: ?$ReadOnlyArray, - - // Int32 props - array_int32_required: $ReadOnlyArray, - array_int32_optional_key?: $ReadOnlyArray, - array_int32_optional_value: ?$ReadOnlyArray, - array_int32_optional_both?: ?$ReadOnlyArray, - - // String enum props - array_enum_optional_key?: WithDefault< - $ReadOnlyArray<'small' | 'large'>, - 'small', - >, - array_enum_optional_both?: WithDefault< - $ReadOnlyArray<'small' | 'large'>, - 'small', - >, - - // ImageSource props - array_image_required: $ReadOnlyArray, - array_image_optional_key?: $ReadOnlyArray, - array_image_optional_value: ?$ReadOnlyArray, - array_image_optional_both?: ?$ReadOnlyArray, - - // ColorValue props - array_color_required: $ReadOnlyArray, - array_color_optional_key?: $ReadOnlyArray, - array_color_optional_value: ?$ReadOnlyArray, - array_color_optional_both?: ?$ReadOnlyArray, - - // PointValue props - array_point_required: $ReadOnlyArray, - array_point_optional_key?: $ReadOnlyArray, - array_point_optional_value: ?$ReadOnlyArray, - array_point_optional_both?: ?$ReadOnlyArray, - - // EdgeInsetsValue props - array_insets_required: $ReadOnlyArray, - array_insets_optional_key?: $ReadOnlyArray, - array_insets_optional_value: ?$ReadOnlyArray, - array_insets_optional_both?: ?$ReadOnlyArray, - - // Object props - array_object_required: $ReadOnlyArray<$ReadOnly<{| prop: string |}>>, - array_object_optional_key?: $ReadOnlyArray<$ReadOnly<{| prop: string |}>>, - array_object_optional_value: ?ArrayObjectType, - array_object_optional_both?: ?$ReadOnlyArray, - - // Nested array object types - array_of_array_object_required: $ReadOnlyArray< - $ReadOnly<{| - // This needs to be the same name as the top level array above - array_object_required: $ReadOnlyArray<$ReadOnly<{| prop: string |}>>, - |}> - >, - array_of_array_object_optional_key?: $ReadOnlyArray< - $ReadOnly<{| - // This needs to be the same name as the top level array above - array_object_optional_key: $ReadOnlyArray<$ReadOnly<{| prop?: string |}>>, - |}> - >, - array_of_array_object_optional_value: ?$ReadOnlyArray< - $ReadOnly<{| - // This needs to be the same name as the top level array above - array_object_optional_value: $ReadOnlyArray<$ReadOnly<{| prop: ?string |}>>, - |}> - >, - array_of_array_object_optional_both?: ?$ReadOnlyArray< - $ReadOnly<{| - // This needs to be the same name as the top level array above - array_object_optional_both: $ReadOnlyArray<$ReadOnly<{| prop?: ?string |}>>, - |}> - >, - - // Nested array of array of object types - array_of_array_of_object_required: $ReadOnlyArray< - $ReadOnlyArray< - $ReadOnly<{| - prop: string, - |}>, - >, - >, - - // Nested array of array of object types (in file) - array_of_array_of_object_required_in_file: $ReadOnlyArray< - $ReadOnlyArray, - >, - - // Nested array of array of object types (with spread) - array_of_array_of_object_required_with_spread: $ReadOnlyArray< - $ReadOnlyArray< - $ReadOnly<{| - ...ObjectType - |}>, - >, - >, -|}>; - -export default (codegenNativeComponent( - 'Module', -): HostComponent); -`; - -const OBJECT_PROP_TYPES_NO_EVENTS = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {Int32, Double, Float, WithDefault} from 'CodegenTypes'; -import type {ImageSource} from 'ImageSource'; -import type {ColorValue, PointValue, EdgeInsetsValue} from 'StyleSheetTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -type ModuleProps = $ReadOnly<{| - ...ViewProps, - - // Props - // Boolean props - boolean_required: $ReadOnly<{|prop: boolean|}>, - boolean_optional: $ReadOnly<{|prop?: WithDefault|}>, - - // String props - string_required: $ReadOnly<{|prop: string|}>, - string_optional: $ReadOnly<{|prop?: WithDefault|}>, - - // Double props - double_required: $ReadOnly<{|prop: Double|}>, - double_optional: $ReadOnly<{|prop?: WithDefault|}>, - - // Float props - float_required: $ReadOnly<{|prop: Float|}>, - float_optional: $ReadOnly<{|prop?: WithDefault|}>, - - // Int32 props - int_required: $ReadOnly<{|prop: Int32|}>, - int_optional: $ReadOnly<{|prop?: WithDefault|}>, - - // String enum props - enum_optional: $ReadOnly<{| - prop?: WithDefault<$ReadOnlyArray<'small' | 'large'>, 'small'>, - |}>, - - // ImageSource props - image_required: $ReadOnly<{|prop: ImageSource|}>, - image_optional_key: $ReadOnly<{|prop?: ImageSource|}>, - image_optional_value: $ReadOnly<{|prop: ?ImageSource|}>, - image_optional_both: $ReadOnly<{|prop?: ?ImageSource|}>, - - // ColorValue props - color_required: $ReadOnly<{|prop: ColorValue|}>, - color_optional_key: $ReadOnly<{|prop?: ColorValue|}>, - color_optional_value: $ReadOnly<{|prop: ?ColorValue|}>, - color_optional_both: $ReadOnly<{|prop?: ?ColorValue|}>, - - // ProcessedColorValue props - processed_color_required: $ReadOnly<{|prop: ProcessedColorValue|}>, - processed_color_optional_key: $ReadOnly<{|prop?: ProcessedColorValue|}>, - processed_color_optional_value: $ReadOnly<{|prop: ?ProcessedColorValue|}>, - processed_color_optional_both: $ReadOnly<{|prop?: ?ProcessedColorValue|}>, - - // PointValue props - point_required: $ReadOnly<{|prop: PointValue|}>, - point_optional_key: $ReadOnly<{|prop?: PointValue|}>, - point_optional_value: $ReadOnly<{|prop: ?PointValue|}>, - point_optional_both: $ReadOnly<{|prop?: ?PointValue|}>, - - // EdgeInsetsValue props - insets_required: $ReadOnly<{|prop: EdgeInsetsValue|}>, - insets_optional_key: $ReadOnly<{|prop?: EdgeInsetsValue|}>, - insets_optional_value: $ReadOnly<{|prop: ?EdgeInsetsValue|}>, - insets_optional_both: $ReadOnly<{|prop?: ?EdgeInsetsValue|}>, - - // Nested object props - object_required: $ReadOnly<{|prop: $ReadOnly<{nestedProp: string}>|}>, - object_optional_key?: $ReadOnly<{|prop: $ReadOnly<{nestedProp: string}>|}>, - object_optional_value: ?$ReadOnly<{|prop: $ReadOnly<{nestedProp: string}>|}>, - object_optional_both?: ?$ReadOnly<{|prop: $ReadOnly<{nestedProp: string}>|}>, -|}>; - -export default (codegenNativeComponent( - 'Module', -): HostComponent); -`; - -const PROPS_ALIASED_LOCALLY = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -type DeepSpread = $ReadOnly<{| - otherStringProp: string, -|}>; - -export type PropsInFile = $ReadOnly<{| - ...DeepSpread, - isEnabled: boolean, - label: string, -|}>; - -export type ModuleProps = $ReadOnly<{| - ...ViewProps, - - ...PropsInFile, - - localType: $ReadOnly<{| - ...PropsInFile - |}>, - - localArr: $ReadOnlyArray -|}>; - -export default (codegenNativeComponent( - 'Module', -): HostComponent); -`; - -const EVENTS_DEFINED_INLINE_WITH_ALL_TYPES = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -import type {HostComponent} from 'react-native'; -const codegenNativeComponent = require('codegenNativeComponent'); - -import type { - Int32, - Double, - Float, - BubblingEventHandler, - DirectEventHandler, -} from 'CodegenTypes'; - -import type {ViewProps} from 'ViewPropTypes'; - -type ModuleProps = $ReadOnly<{| - ...ViewProps, - // No Props - - // Events - onDirectEventDefinedInline: - DirectEventHandler< - $ReadOnly<{| - ${EVENT_DEFINITION} - |}>, - >, - - onDirectEventDefinedInlineOptionalKey?: - DirectEventHandler< - $ReadOnly<{| - ${EVENT_DEFINITION} - |}>, - >, - - onDirectEventDefinedInlineOptionalValue: ? - DirectEventHandler< - $ReadOnly<{| - ${EVENT_DEFINITION} - |}>, - >, - - onDirectEventDefinedInlineOptionalBoth?: ? - DirectEventHandler< - $ReadOnly<{| - ${EVENT_DEFINITION} - |}>, - >, - - onDirectEventDefinedInlineWithPaperName?: ? - DirectEventHandler< - $ReadOnly<{| - ${EVENT_DEFINITION} - |}>, - 'paperDirectEventDefinedInlineWithPaperName', - >, - - onBubblingEventDefinedInline: - BubblingEventHandler< - $ReadOnly<{| - ${EVENT_DEFINITION} - |}>, - >, - - onBubblingEventDefinedInlineOptionalKey?: - BubblingEventHandler< - $ReadOnly<{| - ${EVENT_DEFINITION} - |}>, - >, - - onBubblingEventDefinedInlineOptionalValue: ? - BubblingEventHandler< - $ReadOnly<{| - ${EVENT_DEFINITION} - |}>, - >, - - onBubblingEventDefinedInlineOptionalBoth?: ? - BubblingEventHandler< - $ReadOnly<{| - ${EVENT_DEFINITION} - |}>, - >, - - onBubblingEventDefinedInlineWithPaperName?: ? - BubblingEventHandler< - $ReadOnly<{| - ${EVENT_DEFINITION} - |}>, - 'paperBubblingEventDefinedInlineWithPaperName' - >, -|}>; - -export default (codegenNativeComponent( - 'Module', -): HostComponent); -`; - -const EVENTS_DEFINED_AS_NULL_INLINE = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {BubblingEventHandler, DirectEventHandler} from 'CodegenTypese'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -type ModuleProps = $ReadOnly<{| - ...ViewProps, - - // No props - - // Events defined inline - onDirectEventDefinedInlineNull: DirectEventHandler, - onDirectEventDefinedInlineNullOptionalKey?: DirectEventHandler, - onDirectEventDefinedInlineNullOptionalValue: ?DirectEventHandler, - onDirectEventDefinedInlineNullOptionalBoth?: DirectEventHandler, - onDirectEventDefinedInlineNullWithPaperName?: ?DirectEventHandler< - null, - 'paperDirectEventDefinedInlineNullWithPaperName', - >, - - onBubblingEventDefinedInlineNull: BubblingEventHandler, - onBubblingEventDefinedInlineNullOptionalKey?: BubblingEventHandler, - onBubblingEventDefinedInlineNullOptionalValue: ?BubblingEventHandler, - onBubblingEventDefinedInlineNullOptionalBoth?: ?BubblingEventHandler, - onBubblingEventDefinedInlineNullWithPaperName?: ?BubblingEventHandler< - null, - 'paperBubblingEventDefinedInlineNullWithPaperName', - >, -|}>; - -export default (codegenNativeComponent( - 'Module', -): HostComponent); -`; - -const PROPS_AND_EVENTS_TYPES_EXPORTED = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -import type { - BubblingEventHandler, - DirectEventHandler, -} from 'CodegenTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -export type EventInFile = $ReadOnly<{| - ${EVENT_DEFINITION} -|}>; - -export type ModuleProps = $ReadOnly<{| - ...ViewProps, - - // No props - - // Events defined inline - onBubblingEventDefinedInline: BubblingEventHandler, - onBubblingEventDefinedInlineWithPaperName: BubblingEventHandler, - onDirectEventDefinedInline: DirectEventHandler, - onDirectEventDefinedInlineWithPaperName: DirectEventHandler, -|}>; - -export default (codegenNativeComponent( - 'Module', -): HostComponent); -`; - -const PROPS_AS_EXTERNAL_TYPES = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {HostComponent} from 'react-native'; - -export type String = string; -export type AnotherArray = $ReadOnlyArray; - -export type ModuleProps = $ReadOnly<{| - disable: String, - array: AnotherArray, -|}>; - -export default (codegenNativeComponent( - 'Module', -): HostComponent); -`; - -const COMMANDS_DEFINED_WITH_ALL_TYPES = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -const codegenNativeCommands = require('codegenNativeCommands'); -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {Int32, Double, Float} from 'CodegenTypes'; -import type {RootTag} from 'RCTExport'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - - -export type ModuleProps = $ReadOnly<{| - ...ViewProps, - // No props or events -|}>; - -type NativeType = HostComponent; - -interface NativeCommands { - +handleRootTag: (viewRef: React.ElementRef, rootTag: RootTag) => void; - +hotspotUpdate: (viewRef: React.ElementRef, x: Int32, y: Int32) => void; - +scrollTo: ( - viewRef: React.ElementRef, - x: Float, - y: Int32, - z: Double, - animated: boolean, - ) => void; -} - -export const Commands = codegenNativeCommands({ - supportedCommands: ['handleRootTag', 'hotspotUpdate', 'scrollTo'], -}); - -export default (codegenNativeComponent( - 'Module', -): NativeType); -`; - -const COMMANDS_WITH_EXTERNAL_TYPES = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -const codegenNativeCommands = require('codegenNativeCommands'); -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {Int32} from 'CodegenTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -export type Boolean = boolean; -export type Int = Int32; -export type Void = void; - -export type ModuleProps = $ReadOnly<{| - ...ViewProps, - // No props or events -|}>; - -type NativeType = HostComponent; - -export type ScrollTo = ( - viewRef: React.ElementRef, - y: Int, - animated: Boolean, -) => Void; - -interface NativeCommands { - +scrollTo: ScrollTo; -} - -export const Commands = codegenNativeCommands({ - supportedCommands: ['scrollTo'], -}); - -export default (codegenNativeComponent( - 'Module', -): NativeType); -`; - -const COMMANDS_EVENTS_TYPES_EXPORTED = ` -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -import type { - BubblingEventHandler, - DirectEventHandler, -} from 'CodegenTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -export type EventInFile = $ReadOnly<{| - ${EVENT_DEFINITION} -|}>; - -export type Boolean = boolean; -export type Int = Int32; -export type Void = void; - -export type ModuleProps = $ReadOnly<{| - ...ViewProps, - - // No props - - // Events defined inline - onBubblingEventDefinedInline: BubblingEventHandler, - onBubblingEventDefinedInlineWithPaperName: BubblingEventHandler, - onDirectEventDefinedInline: DirectEventHandler, - onDirectEventDefinedInlineWithPaperName: DirectEventHandler, -|}>; - -type NativeType = HostComponent; - -export type ScrollTo = (viewRef: React.ElementRef, y: Int, animated: Boolean) => Void; - -interface NativeCommands { - +scrollTo: ScrollTo; -} - -export const Commands = codegenNativeCommands({ - supportedCommands: ['scrollTo'] -}); - -export default (codegenNativeComponent( - 'Module', -): NativeType); -`; - -module.exports = { - ALL_PROP_TYPES_NO_EVENTS, - ARRAY_PROP_TYPES_NO_EVENTS, - OBJECT_PROP_TYPES_NO_EVENTS, - PROPS_ALIASED_LOCALLY, - ONE_OF_EACH_PROP_EVENT_DEFAULT_AND_OPTIONS, - ONE_OF_EACH_PROP_EVENT_DEFAULT_AND_OPTIONS_NO_CAST, - NO_PROPS_EVENTS_ONLY_DEPRECATED_VIEW_CONFIG_NAME_OPTION, - EVENTS_DEFINED_INLINE_WITH_ALL_TYPES, - EVENTS_DEFINED_AS_NULL_INLINE, - PROPS_AND_EVENTS_TYPES_EXPORTED, - COMMANDS_EVENTS_TYPES_EXPORTED, - COMMANDS_DEFINED_WITH_ALL_TYPES, - PROPS_AS_EXTERNAL_TYPES, - COMMANDS_WITH_EXTERNAL_TYPES, -}; diff --git a/packages/react-native-codegen/src/parsers/flow/components/__tests__/__snapshots__/component-parser-test.js.snap b/packages/react-native-codegen/src/parsers/flow/components/__tests__/__snapshots__/component-parser-test.js.snap deleted file mode 100644 index abfa4a1f7e36..000000000000 --- a/packages/react-native-codegen/src/parsers/flow/components/__tests__/__snapshots__/component-parser-test.js.snap +++ /dev/null @@ -1,9422 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`RN Codegen Flow Parser Fails with error message COMMANDS_DEFINED_INLINE 1`] = `"codegenNativeCommands doesn't support inline definitions. Specify a file local type alias"`; - -exports[`RN Codegen Flow Parser Fails with error message COMMANDS_DEFINED_MULTIPLE_TIMES 1`] = `"codegenNativeCommands may only be called once in a file"`; - -exports[`RN Codegen Flow Parser Fails with error message COMMANDS_DEFINED_WITH_MISMATCHED_METHOD_NAMES 1`] = `"codegenNativeCommands expected the same supportedCommands specified in the NativeCommands interface: hotspotUpdate, scrollTo"`; - -exports[`RN Codegen Flow Parser Fails with error message COMMANDS_DEFINED_WITH_NULLABLE_REF 1`] = `"The first argument of method hotspotUpdate must be of type React.ElementRef<>"`; - -exports[`RN Codegen Flow Parser Fails with error message COMMANDS_DEFINED_WITHOUT_METHOD_NAMES 1`] = `"codegenNativeCommands must be passed options including the supported commands"`; - -exports[`RN Codegen Flow Parser Fails with error message COMMANDS_DEFINED_WITHOUT_REF 1`] = `"The first argument of method hotspotUpdate must be of type React.ElementRef<>"`; - -exports[`RN Codegen Flow Parser Fails with error message NON_OPTIONAL_KEY_WITH_DEFAULT_VALUE 1`] = `"key required_key_with_default must be optional if used with WithDefault<> annotation"`; - -exports[`RN Codegen Flow Parser Fails with error message NULLABLE_WITH_DEFAULT 1`] = `"WithDefault<> is optional and does not need to be marked as optional. Please remove the ? annotation in front of it."`; - -exports[`RN Codegen Flow Parser Fails with error message PROP_ARRAY_ENUM_BOOLEAN 1`] = `"Unsupported union type for \\"someProp\\", received \\"BooleanLiteralTypeAnnotation\\""`; - -exports[`RN Codegen Flow Parser Fails with error message PROP_ARRAY_ENUM_INT 1`] = `"Arrays of int enums are not supported (see: \\"someProp\\")"`; - -exports[`RN Codegen Flow Parser Fails with error message PROP_ARRAY_MIXED_ENUM 1`] = `"Mixed types are not supported (see \\"someProp\\")"`; - -exports[`RN Codegen Flow Parser Fails with error message PROP_ENUM_BOOLEAN 1`] = `"Unsupported union type for \\"someProp\\", received \\"BooleanLiteralTypeAnnotation\\""`; - -exports[`RN Codegen Flow Parser Fails with error message PROP_MIXED_ENUM 1`] = `"Mixed types are not supported (see \\"someProp\\")."`; - -exports[`RN Codegen Flow Parser Fails with error message PROP_NUMBER_TYPE 1`] = `"Cannot use \\"NumberTypeAnnotation\\" type annotation for \\"someProp\\": must use a specific numeric type like Int32, Double, or Float"`; - -exports[`RN Codegen Flow Parser Fails with error message PROPS_CONFLICT_NAMES 1`] = `"A prop was already defined with the name isEnabled"`; - -exports[`RN Codegen Flow Parser Fails with error message PROPS_CONFLICT_WITH_SPREAD_PROPS 1`] = `"A prop was already defined with the name isEnabled"`; - -exports[`RN Codegen Flow Parser Fails with error message PROPS_SPREAD_CONFLICTS_WITH_PROPS 1`] = `"A prop was already defined with the name isEnabled"`; - -exports[`RN Codegen Flow Parser can generate fixture ALL_PROP_TYPES_NO_EVENTS 1`] = ` -"{ - 'modules': { - 'Module': { - 'type': 'Component', - 'components': { - 'Module': { - 'extendsProps': [ - { - 'type': 'ReactNativeBuiltInType', - 'knownTypeName': 'ReactNativeCoreViewProps' - } - ], - 'events': [], - 'props': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation', - 'default': false - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation', - 'default': true - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation', - 'default': true - } - }, - { - 'name': 'boolean_null_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation', - 'default': null - } - }, - { - 'name': 'boolean_null_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation', - 'default': null - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': '' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': '' - } - }, - { - 'name': 'string_null_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - }, - { - 'name': 'string_null_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - }, - { - 'name': 'stringish_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - }, - { - 'name': 'stringish_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': '' - } - }, - { - 'name': 'stringish_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': '' - } - }, - { - 'name': 'stringish_null_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - }, - { - 'name': 'stringish_null_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation', - 'default': 0 - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation', - 'default': 1.1 - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation', - 'default': 1.1 - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation', - 'default': 0 - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation', - 'default': 1.1 - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation', - 'default': 1.1 - } - }, - { - 'name': 'float_null_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation', - 'default': null - } - }, - { - 'name': 'float_null_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation', - 'default': null - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation', - 'default': 0 - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation', - 'default': 1 - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation', - 'default': 1 - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'default': 'small', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'default': 'small', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'int_enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32EnumTypeAnnotation', - 'default': 0, - 'options': [ - 0, - 1 - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - }, - { - 'name': 'image_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ImageSourcePrimitive' - } - }, - { - 'name': 'image_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ImageSourcePrimitive' - } - }, - { - 'name': 'image_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ImageSourcePrimitive' - } - }, - { - 'name': 'color_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - }, - { - 'name': 'color_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - }, - { - 'name': 'color_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - }, - { - 'name': 'color_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - }, - { - 'name': 'color_array_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - }, - { - 'name': 'color_array_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - }, - { - 'name': 'color_array_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - }, - { - 'name': 'color_array_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - }, - { - 'name': 'processed_color_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - }, - { - 'name': 'processed_color_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - }, - { - 'name': 'processed_color_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - }, - { - 'name': 'processed_color_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - }, - { - 'name': 'point_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'PointPrimitive' - } - }, - { - 'name': 'point_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'PointPrimitive' - } - }, - { - 'name': 'point_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'PointPrimitive' - } - }, - { - 'name': 'point_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'PointPrimitive' - } - }, - { - 'name': 'insets_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'EdgeInsetsPrimitive' - } - }, - { - 'name': 'insets_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'EdgeInsetsPrimitive' - } - }, - { - 'name': 'insets_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'EdgeInsetsPrimitive' - } - }, - { - 'name': 'insets_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'EdgeInsetsPrimitive' - } - } - ], - 'commands': [] - } - } - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture ARRAY_PROP_TYPES_NO_EVENTS 1`] = ` -"{ - 'modules': { - 'Module': { - 'type': 'Component', - 'components': { - 'Module': { - 'extendsProps': [ - { - 'type': 'ReactNativeBuiltInType', - 'knownTypeName': 'ReactNativeCoreViewProps' - } - ], - 'events': [], - 'props': [ - { - 'name': 'array_boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'BooleanTypeAnnotation' - } - } - }, - { - 'name': 'array_boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'BooleanTypeAnnotation' - } - } - }, - { - 'name': 'array_boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'BooleanTypeAnnotation' - } - } - }, - { - 'name': 'array_boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'BooleanTypeAnnotation' - } - } - }, - { - 'name': 'array_string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - }, - { - 'name': 'array_string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - }, - { - 'name': 'array_string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - }, - { - 'name': 'array_string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - }, - { - 'name': 'array_double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'DoubleTypeAnnotation' - } - } - }, - { - 'name': 'array_double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'DoubleTypeAnnotation' - } - } - }, - { - 'name': 'array_double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'DoubleTypeAnnotation' - } - } - }, - { - 'name': 'array_double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'DoubleTypeAnnotation' - } - } - }, - { - 'name': 'array_float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'FloatTypeAnnotation' - } - } - }, - { - 'name': 'array_float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'FloatTypeAnnotation' - } - } - }, - { - 'name': 'array_float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'FloatTypeAnnotation' - } - } - }, - { - 'name': 'array_float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'FloatTypeAnnotation' - } - } - }, - { - 'name': 'array_int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'Int32TypeAnnotation' - } - } - }, - { - 'name': 'array_int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'Int32TypeAnnotation' - } - } - }, - { - 'name': 'array_int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'Int32TypeAnnotation' - } - } - }, - { - 'name': 'array_int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'Int32TypeAnnotation' - } - } - }, - { - 'name': 'array_enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringEnumTypeAnnotation', - 'default': 'small', - 'options': [ - 'small', - 'large' - ] - } - } - }, - { - 'name': 'array_enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringEnumTypeAnnotation', - 'default': 'small', - 'options': [ - 'small', - 'large' - ] - } - } - }, - { - 'name': 'array_image_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ImageSourcePrimitive' - } - } - }, - { - 'name': 'array_image_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ImageSourcePrimitive' - } - } - }, - { - 'name': 'array_image_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ImageSourcePrimitive' - } - } - }, - { - 'name': 'array_image_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ImageSourcePrimitive' - } - } - }, - { - 'name': 'array_color_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - }, - { - 'name': 'array_color_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - }, - { - 'name': 'array_color_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - }, - { - 'name': 'array_color_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - }, - { - 'name': 'array_point_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'PointPrimitive' - } - } - }, - { - 'name': 'array_point_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'PointPrimitive' - } - } - }, - { - 'name': 'array_point_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'PointPrimitive' - } - } - }, - { - 'name': 'array_point_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'PointPrimitive' - } - } - }, - { - 'name': 'array_insets_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'EdgeInsetsPrimitive' - } - } - }, - { - 'name': 'array_insets_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'EdgeInsetsPrimitive' - } - } - }, - { - 'name': 'array_insets_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'EdgeInsetsPrimitive' - } - } - }, - { - 'name': 'array_insets_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'EdgeInsetsPrimitive' - } - } - }, - { - 'name': 'array_object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - }, - { - 'name': 'array_object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - }, - { - 'name': 'array_object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - }, - { - 'name': 'array_object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - }, - { - 'name': 'array_of_array_object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'array_object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - } - ] - } - } - }, - { - 'name': 'array_of_array_object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'array_object_optional_key', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - } - ] - } - } - }, - { - 'name': 'array_of_array_object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'array_object_optional_value', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - } - ] - } - } - }, - { - 'name': 'array_of_array_object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'array_object_optional_both', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - } - ] - } - } - }, - { - 'name': 'array_of_array_of_object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - } - }, - { - 'name': 'array_of_array_of_object_required_in_file', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - } - }, - { - 'name': 'array_of_array_of_object_required_with_spread', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - } - } - ], - 'commands': [] - } - } - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture COMMANDS_DEFINED_WITH_ALL_TYPES 1`] = ` -"{ - 'modules': { - 'Module': { - 'type': 'Component', - 'components': { - 'Module': { - 'extendsProps': [ - { - 'type': 'ReactNativeBuiltInType', - 'knownTypeName': 'ReactNativeCoreViewProps' - } - ], - 'events': [], - 'props': [], - 'commands': [ - { - 'name': 'handleRootTag', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'params': [ - { - 'name': 'rootTag', - 'typeAnnotation': { - 'type': 'ReservedTypeAnnotation', - 'name': 'RootTag' - } - } - ], - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - } - } - }, - { - 'name': 'hotspotUpdate', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'params': [ - { - 'name': 'x', - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'y', - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ], - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - } - } - }, - { - 'name': 'scrollTo', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'params': [ - { - 'name': 'x', - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'y', - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'z', - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'animated', - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ], - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - } - } - } - ] - } - } - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture COMMANDS_EVENTS_TYPES_EXPORTED 1`] = ` -"{ - 'modules': { - 'Module': { - 'type': 'Component', - 'components': { - 'Module': { - 'extendsProps': [ - { - 'type': 'ReactNativeBuiltInType', - 'knownTypeName': 'ReactNativeCoreViewProps' - } - ], - 'events': [ - { - 'name': 'onBubblingEventDefinedInline', - 'optional': false, - 'bubblingType': 'bubble', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - }, - { - 'name': 'onBubblingEventDefinedInlineWithPaperName', - 'optional': false, - 'bubblingType': 'bubble', - 'paperTopLevelNameDeprecated': 'paperBubblingEventDefinedInlineWithPaperName', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - }, - { - 'name': 'onDirectEventDefinedInline', - 'optional': false, - 'bubblingType': 'direct', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - }, - { - 'name': 'onDirectEventDefinedInlineWithPaperName', - 'optional': false, - 'bubblingType': 'direct', - 'paperTopLevelNameDeprecated': 'paperDirectEventDefinedInlineWithPaperName', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - } - ], - 'props': [], - 'commands': [ - { - 'name': 'scrollTo', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'params': [ - { - 'name': 'y', - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'animated', - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ], - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - } - } - } - ] - } - } - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture COMMANDS_WITH_EXTERNAL_TYPES 1`] = ` -"{ - 'modules': { - 'Module': { - 'type': 'Component', - 'components': { - 'Module': { - 'extendsProps': [ - { - 'type': 'ReactNativeBuiltInType', - 'knownTypeName': 'ReactNativeCoreViewProps' - } - ], - 'events': [], - 'props': [], - 'commands': [ - { - 'name': 'scrollTo', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'params': [ - { - 'name': 'y', - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'animated', - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ], - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - } - } - } - ] - } - } - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture EVENTS_DEFINED_AS_NULL_INLINE 1`] = ` -"{ - 'modules': { - 'Module': { - 'type': 'Component', - 'components': { - 'Module': { - 'extendsProps': [ - { - 'type': 'ReactNativeBuiltInType', - 'knownTypeName': 'ReactNativeCoreViewProps' - } - ], - 'events': [ - { - 'name': 'onDirectEventDefinedInlineNull', - 'optional': false, - 'bubblingType': 'direct', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [] - } - } - }, - { - 'name': 'onDirectEventDefinedInlineNullOptionalKey', - 'optional': true, - 'bubblingType': 'direct', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [] - } - } - }, - { - 'name': 'onDirectEventDefinedInlineNullOptionalValue', - 'optional': true, - 'bubblingType': 'direct', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [] - } - } - }, - { - 'name': 'onDirectEventDefinedInlineNullOptionalBoth', - 'optional': true, - 'bubblingType': 'direct', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [] - } - } - }, - { - 'name': 'onDirectEventDefinedInlineNullWithPaperName', - 'optional': true, - 'bubblingType': 'direct', - 'paperTopLevelNameDeprecated': 'paperDirectEventDefinedInlineNullWithPaperName', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [] - } - } - }, - { - 'name': 'onBubblingEventDefinedInlineNull', - 'optional': false, - 'bubblingType': 'bubble', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [] - } - } - }, - { - 'name': 'onBubblingEventDefinedInlineNullOptionalKey', - 'optional': true, - 'bubblingType': 'bubble', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [] - } - } - }, - { - 'name': 'onBubblingEventDefinedInlineNullOptionalValue', - 'optional': true, - 'bubblingType': 'bubble', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [] - } - } - }, - { - 'name': 'onBubblingEventDefinedInlineNullOptionalBoth', - 'optional': true, - 'bubblingType': 'bubble', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [] - } - } - }, - { - 'name': 'onBubblingEventDefinedInlineNullWithPaperName', - 'optional': true, - 'bubblingType': 'bubble', - 'paperTopLevelNameDeprecated': 'paperBubblingEventDefinedInlineNullWithPaperName', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [] - } - } - } - ], - 'props': [], - 'commands': [] - } - } - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture EVENTS_DEFINED_INLINE_WITH_ALL_TYPES 1`] = ` -"{ - 'modules': { - 'Module': { - 'type': 'Component', - 'components': { - 'Module': { - 'extendsProps': [ - { - 'type': 'ReactNativeBuiltInType', - 'knownTypeName': 'ReactNativeCoreViewProps' - } - ], - 'events': [ - { - 'name': 'onDirectEventDefinedInline', - 'optional': false, - 'bubblingType': 'direct', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - }, - { - 'name': 'onDirectEventDefinedInlineOptionalKey', - 'optional': true, - 'bubblingType': 'direct', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - }, - { - 'name': 'onDirectEventDefinedInlineOptionalValue', - 'optional': true, - 'bubblingType': 'direct', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - }, - { - 'name': 'onDirectEventDefinedInlineOptionalBoth', - 'optional': true, - 'bubblingType': 'direct', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - }, - { - 'name': 'onDirectEventDefinedInlineWithPaperName', - 'optional': true, - 'bubblingType': 'direct', - 'paperTopLevelNameDeprecated': 'paperDirectEventDefinedInlineWithPaperName', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - }, - { - 'name': 'onBubblingEventDefinedInline', - 'optional': false, - 'bubblingType': 'bubble', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - }, - { - 'name': 'onBubblingEventDefinedInlineOptionalKey', - 'optional': true, - 'bubblingType': 'bubble', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - }, - { - 'name': 'onBubblingEventDefinedInlineOptionalValue', - 'optional': true, - 'bubblingType': 'bubble', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - }, - { - 'name': 'onBubblingEventDefinedInlineOptionalBoth', - 'optional': true, - 'bubblingType': 'bubble', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - }, - { - 'name': 'onBubblingEventDefinedInlineWithPaperName', - 'optional': true, - 'bubblingType': 'bubble', - 'paperTopLevelNameDeprecated': 'paperBubblingEventDefinedInlineWithPaperName', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - } - ], - 'props': [], - 'commands': [] - } - } - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture NO_PROPS_EVENTS_ONLY_DEPRECATED_VIEW_CONFIG_NAME_OPTION 1`] = ` -"{ - 'modules': { - 'Module': { - 'type': 'Component', - 'components': { - 'Module': { - 'deprecatedViewConfigName': 'DeprecateModuleName', - 'extendsProps': [ - { - 'type': 'ReactNativeBuiltInType', - 'knownTypeName': 'ReactNativeCoreViewProps' - } - ], - 'events': [], - 'props': [], - 'commands': [] - } - } - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture OBJECT_PROP_TYPES_NO_EVENTS 1`] = ` -"{ - 'modules': { - 'Module': { - 'type': 'Component', - 'components': { - 'Module': { - 'extendsProps': [ - { - 'type': 'ReactNativeBuiltInType', - 'knownTypeName': 'ReactNativeCoreViewProps' - } - ], - 'events': [], - 'props': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation', - 'default': false - } - } - ] - } - }, - { - 'name': 'boolean_optional', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation', - 'default': false - } - } - ] - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - }, - { - 'name': 'string_optional', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': '' - } - } - ] - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation', - 'default': 0 - } - } - ] - } - }, - { - 'name': 'double_optional', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation', - 'default': 0 - } - } - ] - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation', - 'default': 0 - } - } - ] - } - }, - { - 'name': 'float_optional', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation', - 'default': 0 - } - } - ] - } - }, - { - 'name': 'int_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation', - 'default': 0 - } - } - ] - } - }, - { - 'name': 'int_optional', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation', - 'default': 0 - } - } - ] - } - }, - { - 'name': 'enum_optional', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringEnumTypeAnnotation', - 'default': 'small', - 'options': [ - 'small', - 'large' - ] - } - } - } - ] - } - }, - { - 'name': 'image_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ImageSourcePrimitive' - } - } - ] - } - }, - { - 'name': 'image_optional_key', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ImageSourcePrimitive' - } - } - ] - } - }, - { - 'name': 'image_optional_value', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ImageSourcePrimitive' - } - } - ] - } - }, - { - 'name': 'image_optional_both', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ImageSourcePrimitive' - } - } - ] - } - }, - { - 'name': 'color_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - ] - } - }, - { - 'name': 'color_optional_key', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - ] - } - }, - { - 'name': 'color_optional_value', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - ] - } - }, - { - 'name': 'color_optional_both', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - ] - } - }, - { - 'name': 'processed_color_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - ] - } - }, - { - 'name': 'processed_color_optional_key', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - ] - } - }, - { - 'name': 'processed_color_optional_value', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - ] - } - }, - { - 'name': 'processed_color_optional_both', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - ] - } - }, - { - 'name': 'point_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'PointPrimitive' - } - } - ] - } - }, - { - 'name': 'point_optional_key', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'PointPrimitive' - } - } - ] - } - }, - { - 'name': 'point_optional_value', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'PointPrimitive' - } - } - ] - } - }, - { - 'name': 'point_optional_both', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'PointPrimitive' - } - } - ] - } - }, - { - 'name': 'insets_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'EdgeInsetsPrimitive' - } - } - ] - } - }, - { - 'name': 'insets_optional_key', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'EdgeInsetsPrimitive' - } - } - ] - } - }, - { - 'name': 'insets_optional_value', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'EdgeInsetsPrimitive' - } - } - ] - } - }, - { - 'name': 'insets_optional_both', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'EdgeInsetsPrimitive' - } - } - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'nestedProp', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'nestedProp', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'nestedProp', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'nestedProp', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - ] - } - } - ], - 'commands': [] - } - } - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture ONE_OF_EACH_PROP_EVENT_DEFAULT_AND_OPTIONS 1`] = ` -"{ - 'modules': { - 'Module': { - 'type': 'Component', - 'components': { - 'Module': { - 'interfaceOnly': true, - 'paperComponentName': 'RCTModule', - 'extendsProps': [ - { - 'type': 'ReactNativeBuiltInType', - 'knownTypeName': 'ReactNativeCoreViewProps' - } - ], - 'events': [ - { - 'name': 'onDirectEventDefinedInlineNull', - 'optional': false, - 'bubblingType': 'direct', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [] - } - } - }, - { - 'name': 'onBubblingEventDefinedInlineNull', - 'optional': false, - 'bubblingType': 'bubble', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [] - } - } - } - ], - 'props': [ - { - 'name': 'boolean_default_true_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation', - 'default': true - } - } - ], - 'commands': [] - } - } - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture ONE_OF_EACH_PROP_EVENT_DEFAULT_AND_OPTIONS_NO_CAST 1`] = ` -"{ - 'modules': { - 'Module': { - 'type': 'Component', - 'components': { - 'Module': { - 'interfaceOnly': true, - 'excludedPlatforms': [ - 'android' - ], - 'paperComponentName': 'RCTModule', - 'extendsProps': [ - { - 'type': 'ReactNativeBuiltInType', - 'knownTypeName': 'ReactNativeCoreViewProps' - } - ], - 'events': [ - { - 'name': 'onDirectEventDefinedInlineNull', - 'optional': false, - 'bubblingType': 'direct', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [] - } - } - }, - { - 'name': 'onBubblingEventDefinedInlineNull', - 'optional': false, - 'bubblingType': 'bubble', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [] - } - } - } - ], - 'props': [ - { - 'name': 'boolean_default_true_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation', - 'default': true - } - } - ], - 'commands': [] - } - } - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture PROPS_ALIASED_LOCALLY 1`] = ` -"{ - 'modules': { - 'Module': { - 'type': 'Component', - 'components': { - 'Module': { - 'extendsProps': [ - { - 'type': 'ReactNativeBuiltInType', - 'knownTypeName': 'ReactNativeCoreViewProps' - } - ], - 'events': [], - 'props': [ - { - 'name': 'otherStringProp', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - }, - { - 'name': 'isEnabled', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation', - 'default': false - } - }, - { - 'name': 'label', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - }, - { - 'name': 'localType', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'otherStringProp', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - }, - { - 'name': 'isEnabled', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation', - 'default': false - } - }, - { - 'name': 'label', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - }, - { - 'name': 'localArr', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'otherStringProp', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - }, - { - 'name': 'isEnabled', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation', - 'default': false - } - }, - { - 'name': 'label', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - } - ], - 'commands': [] - } - } - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture PROPS_AND_EVENTS_TYPES_EXPORTED 1`] = ` -"{ - 'modules': { - 'Module': { - 'type': 'Component', - 'components': { - 'Module': { - 'extendsProps': [ - { - 'type': 'ReactNativeBuiltInType', - 'knownTypeName': 'ReactNativeCoreViewProps' - } - ], - 'events': [ - { - 'name': 'onBubblingEventDefinedInline', - 'optional': false, - 'bubblingType': 'bubble', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - }, - { - 'name': 'onBubblingEventDefinedInlineWithPaperName', - 'optional': false, - 'bubblingType': 'bubble', - 'paperTopLevelNameDeprecated': 'paperBubblingEventDefinedInlineWithPaperName', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - }, - { - 'name': 'onDirectEventDefinedInline', - 'optional': false, - 'bubblingType': 'direct', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - }, - { - 'name': 'onDirectEventDefinedInlineWithPaperName', - 'optional': false, - 'bubblingType': 'direct', - 'paperTopLevelNameDeprecated': 'paperDirectEventDefinedInlineWithPaperName', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - } - ], - 'props': [], - 'commands': [] - } - } - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture PROPS_AS_EXTERNAL_TYPES 1`] = ` -"{ - 'modules': { - 'Module': { - 'type': 'Component', - 'components': { - 'Module': { - 'extendsProps': [], - 'events': [], - 'props': [ - { - 'name': 'disable', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - }, - { - 'name': 'array', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - } - ], - 'commands': [] - } - } - } - } -}" -`; diff --git a/packages/react-native-codegen/src/parsers/flow/components/__tests__/component-parser-test.js b/packages/react-native-codegen/src/parsers/flow/components/__tests__/component-parser-test.js deleted file mode 100644 index 384b0af5b2c8..000000000000 --- a/packages/react-native-codegen/src/parsers/flow/components/__tests__/component-parser-test.js +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const FlowParser = require('../../index.js'); -const {parseFile} = require('../../../utils.js'); -const fixtures = require('../__test_fixtures__/fixtures.js'); -const failureFixtures = require('../__test_fixtures__/failures.js'); -jest.mock('fs', () => ({ - readFileSync: filename => { - // Jest in the OSS does not allow to capture variables in closures. - // Therefore, we have to bring the variables inside the closure. - // see: https://github.com/facebook/jest/issues/2567 - const readFileFixtures = require('../__test_fixtures__/fixtures.js'); - const readFileFailureFixtures = require('../__test_fixtures__/failures.js'); - return readFileFixtures[filename] || readFileFailureFixtures[filename]; - }, -})); - -describe('RN Codegen Flow Parser', () => { - Object.keys(fixtures) - .sort() - .forEach(fixtureName => { - it(`can generate fixture ${fixtureName}`, () => { - const schema = parseFile(fixtureName, FlowParser.buildSchema); - const serializedSchema = JSON.stringify(schema, null, 2).replace( - /"/g, - "'", - ); - expect(serializedSchema).toMatchSnapshot(); - }); - }); - - Object.keys(failureFixtures) - .sort() - .forEach(fixtureName => { - it(`Fails with error message ${fixtureName}`, () => { - expect(() => { - parseFile(fixtureName, FlowParser.buildSchema); - }).toThrowErrorMatchingSnapshot(); - }); - }); -}); diff --git a/packages/react-native-codegen/src/parsers/flow/components/commands.js b/packages/react-native-codegen/src/parsers/flow/components/commands.js deleted file mode 100644 index e829582ce311..000000000000 --- a/packages/react-native-codegen/src/parsers/flow/components/commands.js +++ /dev/null @@ -1,122 +0,0 @@ -/** - * 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 - */ - -'use strict'; - -import type { - NamedShape, - CommandTypeAnnotation, -} from '../../../CodegenSchema.js'; -import type {TypeDeclarationMap} from '../../utils'; - -const {getValueFromTypes} = require('../utils.js'); - -type EventTypeAST = Object; - -function buildCommandSchema(property: EventTypeAST, types: TypeDeclarationMap) { - const name = property.key.name; - const optional = property.optional; - const value = getValueFromTypes(property.value, types); - - const firstParam = value.params[0].typeAnnotation; - - if ( - !( - firstParam.id != null && - firstParam.id.type === 'QualifiedTypeIdentifier' && - firstParam.id.qualification.name === 'React' && - firstParam.id.id.name === 'ElementRef' - ) - ) { - throw new Error( - `The first argument of method ${name} must be of type React.ElementRef<>`, - ); - } - - const params = value.params.slice(1).map(param => { - const paramName = param.name.name; - const paramValue = getValueFromTypes(param.typeAnnotation, types); - const type = - paramValue.type === 'GenericTypeAnnotation' - ? paramValue.id.name - : paramValue.type; - let returnType; - - switch (type) { - case 'RootTag': - returnType = { - type: 'ReservedTypeAnnotation', - name: 'RootTag', - }; - break; - case 'BooleanTypeAnnotation': - returnType = { - type: 'BooleanTypeAnnotation', - }; - break; - case 'Int32': - returnType = { - type: 'Int32TypeAnnotation', - }; - break; - case 'Double': - returnType = { - type: 'DoubleTypeAnnotation', - }; - break; - case 'Float': - returnType = { - type: 'FloatTypeAnnotation', - }; - break; - case 'StringTypeAnnotation': - returnType = { - type: 'StringTypeAnnotation', - }; - break; - default: - (type: empty); - throw new Error( - `Unsupported param type for method "${name}", param "${paramName}". Found ${type}`, - ); - } - - return { - name: paramName, - typeAnnotation: returnType, - }; - }); - - return { - name, - optional, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - params, - returnTypeAnnotation: { - type: 'VoidTypeAnnotation', - }, - }, - }; -} - -function getCommands( - commandTypeAST: $ReadOnlyArray, - types: TypeDeclarationMap, -): $ReadOnlyArray> { - return commandTypeAST - .filter(property => property.type === 'ObjectTypeProperty') - .map(property => buildCommandSchema(property, types)) - .filter(Boolean); -} - -module.exports = { - getCommands, -}; diff --git a/packages/react-native-codegen/src/parsers/flow/components/componentsUtils.js b/packages/react-native-codegen/src/parsers/flow/components/componentsUtils.js deleted file mode 100644 index c448decc42d9..000000000000 --- a/packages/react-native-codegen/src/parsers/flow/components/componentsUtils.js +++ /dev/null @@ -1,496 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {ASTNode} from '../utils'; -import type {NamedShape} from '../../../CodegenSchema.js'; -const {getValueFromTypes} = require('../utils.js'); -import type {TypeDeclarationMap} from '../../utils'; - -function getProperties( - typeName: string, - types: TypeDeclarationMap, -): $FlowFixMe { - const typeAlias = types[typeName]; - try { - return typeAlias.right.typeParameters.params[0].properties; - } catch (e) { - throw new Error( - `Failed to find type definition for "${typeName}", please check that you have a valid codegen flow file`, - ); - } -} - -function getTypeAnnotationForArray<+T>( - name: string, - typeAnnotation: $FlowFixMe, - defaultValue: $FlowFixMe | null, - types: TypeDeclarationMap, - buildSchema: (property: PropAST, types: TypeDeclarationMap) => ?NamedShape, -): $FlowFixMe { - const extractedTypeAnnotation = getValueFromTypes(typeAnnotation, types); - if (extractedTypeAnnotation.type === 'NullableTypeAnnotation') { - throw new Error( - 'Nested optionals such as "$ReadOnlyArray" are not supported, please declare optionals at the top level of value definitions as in "?$ReadOnlyArray"', - ); - } - - if ( - extractedTypeAnnotation.type === 'GenericTypeAnnotation' && - extractedTypeAnnotation.id.name === 'WithDefault' - ) { - throw new Error( - 'Nested defaults such as "$ReadOnlyArray>" are not supported, please declare defaults at the top level of value definitions as in "WithDefault<$ReadOnlyArray, false>"', - ); - } - - if (extractedTypeAnnotation.type === 'GenericTypeAnnotation') { - // Resolve the type alias if it's not defined inline - const objectType = getValueFromTypes(extractedTypeAnnotation, types); - - if (objectType.id.name === '$ReadOnly') { - return { - type: 'ObjectTypeAnnotation', - properties: flattenProperties( - objectType.typeParameters.params[0].properties, - types, - ) - .map(prop => buildSchema(prop, types)) - .filter(Boolean), - }; - } - - if (objectType.id.name === '$ReadOnlyArray') { - // We need to go yet another level deeper to resolve - // types that may be defined in a type alias - const nestedObjectType = getValueFromTypes( - objectType.typeParameters.params[0], - types, - ); - - return { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'ObjectTypeAnnotation', - properties: flattenProperties( - nestedObjectType.typeParameters.params[0].properties, - types, - ) - .map(prop => buildSchema(prop, types)) - .filter(Boolean), - }, - }; - } - } - - const type = - extractedTypeAnnotation.type === 'GenericTypeAnnotation' - ? extractedTypeAnnotation.id.name - : extractedTypeAnnotation.type; - - switch (type) { - case 'ImageSource': - return { - type: 'ReservedPropTypeAnnotation', - name: 'ImageSourcePrimitive', - }; - case 'ImageRequest': - return { - type: 'ReservedPropTypeAnnotation', - name: 'ImageRequestPrimitive', - }; - case 'ColorValue': - case 'ProcessedColorValue': - return { - type: 'ReservedPropTypeAnnotation', - name: 'ColorPrimitive', - }; - case 'PointValue': - return { - type: 'ReservedPropTypeAnnotation', - name: 'PointPrimitive', - }; - case 'EdgeInsetsValue': - return { - type: 'ReservedPropTypeAnnotation', - name: 'EdgeInsetsPrimitive', - }; - case 'Stringish': - return { - type: 'StringTypeAnnotation', - }; - case 'Int32': - return { - type: 'Int32TypeAnnotation', - }; - case 'Double': - return { - type: 'DoubleTypeAnnotation', - }; - case 'Float': - return { - type: 'FloatTypeAnnotation', - }; - case 'BooleanTypeAnnotation': - return { - type: 'BooleanTypeAnnotation', - }; - case 'StringTypeAnnotation': - return { - type: 'StringTypeAnnotation', - }; - case 'UnionTypeAnnotation': - typeAnnotation.types.reduce((lastType, currType) => { - if (lastType && currType.type !== lastType.type) { - throw new Error(`Mixed types are not supported (see "${name}")`); - } - return currType; - }); - - if (defaultValue === null) { - throw new Error(`A default enum value is required for "${name}"`); - } - - const unionType = typeAnnotation.types[0].type; - if (unionType === 'StringLiteralTypeAnnotation') { - return { - type: 'StringEnumTypeAnnotation', - default: (defaultValue: string), - options: typeAnnotation.types.map(option => option.value), - }; - } else if (unionType === 'NumberLiteralTypeAnnotation') { - throw new Error( - `Arrays of int enums are not supported (see: "${name}")`, - ); - } else { - throw new Error( - `Unsupported union type for "${name}", received "${unionType}"`, - ); - } - default: - (type: empty); - throw new Error(`Unknown property type for "${name}": ${type}`); - } -} - -function flattenProperties( - typeDefinition: $ReadOnlyArray, - types: TypeDeclarationMap, -): $ReadOnlyArray { - return typeDefinition - .map(property => { - if (property.type === 'ObjectTypeProperty') { - return property; - } else if (property.type === 'ObjectTypeSpreadProperty') { - return flattenProperties( - getProperties(property.argument.id.name, types), - types, - ); - } - }) - .reduce((acc, item) => { - if (Array.isArray(item)) { - item.forEach(prop => { - verifyPropNotAlreadyDefined(acc, prop); - }); - return acc.concat(item); - } else { - verifyPropNotAlreadyDefined(acc, item); - acc.push(item); - return acc; - } - }, []) - .filter(Boolean); -} - -function verifyPropNotAlreadyDefined( - props: $ReadOnlyArray, - needleProp: PropAST, -) { - const propName = needleProp.key.name; - const foundProp = props.some(prop => prop.key.name === propName); - if (foundProp) { - throw new Error(`A prop was already defined with the name ${propName}`); - } -} - -function getTypeAnnotation<+T>( - name: string, - annotation: $FlowFixMe | ASTNode, - defaultValue: $FlowFixMe | null, - withNullDefault: boolean, - types: TypeDeclarationMap, - buildSchema: (property: PropAST, types: TypeDeclarationMap) => ?NamedShape, -): $FlowFixMe { - const typeAnnotation = getValueFromTypes(annotation, types); - - if ( - typeAnnotation.type === 'GenericTypeAnnotation' && - typeAnnotation.id.name === '$ReadOnlyArray' - ) { - return { - type: 'ArrayTypeAnnotation', - elementType: getTypeAnnotationForArray( - name, - typeAnnotation.typeParameters.params[0], - defaultValue, - types, - buildSchema, - ), - }; - } - - if ( - typeAnnotation.type === 'GenericTypeAnnotation' && - typeAnnotation.id.name === '$ReadOnly' - ) { - return { - type: 'ObjectTypeAnnotation', - properties: flattenProperties( - typeAnnotation.typeParameters.params[0].properties, - types, - ) - .map(prop => buildSchema(prop, types)) - .filter(Boolean), - }; - } - - const type = - typeAnnotation.type === 'GenericTypeAnnotation' - ? typeAnnotation.id.name - : typeAnnotation.type; - - switch (type) { - case 'ImageSource': - return { - type: 'ReservedPropTypeAnnotation', - name: 'ImageSourcePrimitive', - }; - case 'ImageRequest': - return { - type: 'ReservedPropTypeAnnotation', - name: 'ImageRequestPrimitive', - }; - case 'ColorValue': - case 'ProcessedColorValue': - return { - type: 'ReservedPropTypeAnnotation', - name: 'ColorPrimitive', - }; - case 'ColorArrayValue': - return { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'ReservedPropTypeAnnotation', - name: 'ColorPrimitive', - }, - }; - case 'PointValue': - return { - type: 'ReservedPropTypeAnnotation', - name: 'PointPrimitive', - }; - case 'EdgeInsetsValue': - return { - type: 'ReservedPropTypeAnnotation', - name: 'EdgeInsetsPrimitive', - }; - case 'Int32': - return { - type: 'Int32TypeAnnotation', - default: ((defaultValue ? defaultValue : 0): number), - }; - case 'Double': - return { - type: 'DoubleTypeAnnotation', - default: ((defaultValue ? defaultValue : 0): number), - }; - case 'Float': - return { - type: 'FloatTypeAnnotation', - default: withNullDefault - ? (defaultValue: number | null) - : ((defaultValue ? defaultValue : 0): number), - }; - case 'BooleanTypeAnnotation': - return { - type: 'BooleanTypeAnnotation', - default: withNullDefault - ? (defaultValue: boolean | null) - : ((defaultValue == null ? false : defaultValue): boolean), - }; - case 'StringTypeAnnotation': - if (typeof defaultValue !== 'undefined') { - return { - type: 'StringTypeAnnotation', - default: (defaultValue: string | null), - }; - } - throw new Error(`A default string (or null) is required for "${name}"`); - case 'Stringish': - if (typeof defaultValue !== 'undefined') { - return { - type: 'StringTypeAnnotation', - default: (defaultValue: string | null), - }; - } - throw new Error(`A default string (or null) is required for "${name}"`); - case 'UnionTypeAnnotation': - typeAnnotation.types.reduce((lastType, currType) => { - if (lastType && currType.type !== lastType.type) { - throw new Error(`Mixed types are not supported (see "${name}").`); - } - return currType; - }); - - if (defaultValue === null) { - throw new Error(`A default enum value is required for "${name}"`); - } - - const unionType = typeAnnotation.types[0].type; - if (unionType === 'StringLiteralTypeAnnotation') { - return { - type: 'StringEnumTypeAnnotation', - default: (defaultValue: string), - options: typeAnnotation.types.map(option => option.value), - }; - } else if (unionType === 'NumberLiteralTypeAnnotation') { - return { - type: 'Int32EnumTypeAnnotation', - default: (defaultValue: number), - options: typeAnnotation.types.map(option => option.value), - }; - } else { - throw new Error( - `Unsupported union type for "${name}", received "${unionType}"`, - ); - } - case 'ObjectTypeAnnotation': - throw new Error( - `Cannot use "${type}" type annotation for "${name}": object types must be declared using $ReadOnly<>`, - ); - case 'NumberTypeAnnotation': - throw new Error( - `Cannot use "${type}" type annotation for "${name}": must use a specific numeric type like Int32, Double, or Float`, - ); - default: - (type: empty); - throw new Error( - `Unknown property type for "${name}": "${type}" in the State`, - ); - } -} - -type SchemaInfo = { - name: string, - optional: boolean, - typeAnnotation: $FlowFixMe, - defaultValue: $FlowFixMe, - withNullDefault: boolean, -}; - -function getSchemaInfo( - property: PropAST, - types: TypeDeclarationMap, -): ?SchemaInfo { - const name = property.key.name; - - const value = getValueFromTypes(property.value, types); - let typeAnnotation = - value.type === 'NullableTypeAnnotation' ? value.typeAnnotation : value; - - const optional = - value.type === 'NullableTypeAnnotation' || - property.optional || - (value.type === 'GenericTypeAnnotation' && - typeAnnotation.id.name === 'WithDefault'); - - if ( - !property.optional && - value.type === 'GenericTypeAnnotation' && - typeAnnotation.id.name === 'WithDefault' - ) { - throw new Error( - `key ${name} must be optional if used with WithDefault<> annotation`, - ); - } - if ( - value.type === 'NullableTypeAnnotation' && - typeAnnotation.type === 'GenericTypeAnnotation' && - typeAnnotation.id.name === 'WithDefault' - ) { - throw new Error( - 'WithDefault<> is optional and does not need to be marked as optional. Please remove the ? annotation in front of it.', - ); - } - - let type = typeAnnotation.type; - if ( - type === 'GenericTypeAnnotation' && - (typeAnnotation.id.name === 'DirectEventHandler' || - typeAnnotation.id.name === 'BubblingEventHandler') - ) { - return null; - } - - if ( - name === 'style' && - type === 'GenericTypeAnnotation' && - typeAnnotation.id.name === 'ViewStyleProp' - ) { - return null; - } - - let defaultValue = null; - let withNullDefault = false; - if ( - type === 'GenericTypeAnnotation' && - typeAnnotation.id.name === 'WithDefault' - ) { - if (typeAnnotation.typeParameters.params.length === 1) { - throw new Error( - `WithDefault requires two parameters, did you forget to provide a default value for "${name}"?`, - ); - } - - defaultValue = typeAnnotation.typeParameters.params[1].value; - const defaultValueType = typeAnnotation.typeParameters.params[1].type; - - typeAnnotation = typeAnnotation.typeParameters.params[0]; - type = - typeAnnotation.type === 'GenericTypeAnnotation' - ? typeAnnotation.id.name - : typeAnnotation.type; - - if (defaultValueType === 'NullLiteralTypeAnnotation') { - defaultValue = null; - withNullDefault = true; - } - } - - return { - name, - optional, - typeAnnotation, - defaultValue, - withNullDefault, - }; -} - -// $FlowFixMe[unclear-type] there's no flowtype for ASTs -type PropAST = Object; - -module.exports = { - getProperties, - getSchemaInfo, - getTypeAnnotation, - flattenProperties, -}; diff --git a/packages/react-native-codegen/src/parsers/flow/components/events.js b/packages/react-native-codegen/src/parsers/flow/components/events.js deleted file mode 100644 index 8384edd789b8..000000000000 --- a/packages/react-native-codegen/src/parsers/flow/components/events.js +++ /dev/null @@ -1,262 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type { - EventTypeShape, - NamedShape, - EventTypeAnnotation, -} from '../../../CodegenSchema.js'; - -function getPropertyType( - /* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's - * LTI update could not be added via codemod */ - name, - optional: boolean, - typeAnnotation: $FlowFixMe, -): NamedShape { - const type = - typeAnnotation.type === 'GenericTypeAnnotation' - ? typeAnnotation.id.name - : typeAnnotation.type; - - switch (type) { - case 'BooleanTypeAnnotation': - return { - name, - optional, - typeAnnotation: { - type: 'BooleanTypeAnnotation', - }, - }; - case 'StringTypeAnnotation': - return { - name, - optional, - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }; - case 'Int32': - return { - name, - optional, - typeAnnotation: { - type: 'Int32TypeAnnotation', - }, - }; - case 'Double': - return { - name, - optional, - typeAnnotation: { - type: 'DoubleTypeAnnotation', - }, - }; - case 'Float': - return { - name, - optional, - typeAnnotation: { - type: 'FloatTypeAnnotation', - }, - }; - case '$ReadOnly': - return getPropertyType( - name, - optional, - typeAnnotation.typeParameters.params[0], - ); - case 'ObjectTypeAnnotation': - return { - name, - optional, - typeAnnotation: { - type: 'ObjectTypeAnnotation', - properties: typeAnnotation.properties.map(buildPropertiesForEvent), - }, - }; - case 'UnionTypeAnnotation': - return { - name, - optional, - typeAnnotation: { - type: 'StringEnumTypeAnnotation', - options: typeAnnotation.types.map(option => option.value), - }, - }; - default: - (type: empty); - throw new Error(`Unable to determine event type for "${name}": ${type}`); - } -} - -function findEventArgumentsAndType( - typeAnnotation: $FlowFixMe, - types: TypeMap, - bubblingType: void | 'direct' | 'bubble', - paperName: ?$FlowFixMe, -): { - argumentProps: $FlowFixMe, - bubblingType: ?('direct' | 'bubble'), - paperTopLevelNameDeprecated: ?$FlowFixMe, -} { - if (!typeAnnotation.id) { - throw new Error("typeAnnotation of event doesn't have a name"); - } - const name = typeAnnotation.id.name; - if (name === '$ReadOnly') { - return { - argumentProps: typeAnnotation.typeParameters.params[0].properties, - paperTopLevelNameDeprecated: paperName, - bubblingType, - }; - } else if (name === 'BubblingEventHandler' || name === 'DirectEventHandler') { - const eventType = name === 'BubblingEventHandler' ? 'bubble' : 'direct'; - const paperTopLevelNameDeprecated = - typeAnnotation.typeParameters.params.length > 1 - ? typeAnnotation.typeParameters.params[1].value - : null; - if ( - typeAnnotation.typeParameters.params[0].type === - 'NullLiteralTypeAnnotation' - ) { - return { - argumentProps: [], - bubblingType: eventType, - paperTopLevelNameDeprecated, - }; - } - return findEventArgumentsAndType( - typeAnnotation.typeParameters.params[0], - types, - eventType, - paperTopLevelNameDeprecated, - ); - } else if (types[name]) { - return findEventArgumentsAndType( - types[name].right, - types, - bubblingType, - paperName, - ); - } else { - return { - argumentProps: null, - bubblingType: null, - paperTopLevelNameDeprecated: null, - }; - } -} - -/* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's - * LTI update could not be added via codemod */ -function buildPropertiesForEvent(property): NamedShape { - const name = property.key.name; - const optional = - property.value.type === 'NullableTypeAnnotation' || property.optional; - let typeAnnotation = - property.value.type === 'NullableTypeAnnotation' - ? property.value.typeAnnotation - : property.value; - - return getPropertyType(name, optional, typeAnnotation); -} - -/* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's - * LTI update could not be added via codemod */ -function getEventArgument(argumentProps, name: $FlowFixMe) { - return { - type: 'ObjectTypeAnnotation', - properties: argumentProps.map(buildPropertiesForEvent), - }; -} - -function buildEventSchema( - types: TypeMap, - property: EventTypeAST, -): ?EventTypeShape { - const name = property.key.name; - const optional = - property.optional || property.value.type === 'NullableTypeAnnotation'; - - let typeAnnotation = - property.value.type === 'NullableTypeAnnotation' - ? property.value.typeAnnotation - : property.value; - - if ( - typeAnnotation.type !== 'GenericTypeAnnotation' || - (typeAnnotation.id.name !== 'BubblingEventHandler' && - typeAnnotation.id.name !== 'DirectEventHandler') - ) { - return null; - } - - const {argumentProps, bubblingType, paperTopLevelNameDeprecated} = - findEventArgumentsAndType(typeAnnotation, types); - - if (bubblingType && argumentProps) { - if (paperTopLevelNameDeprecated != null) { - return { - name, - optional, - bubblingType, - paperTopLevelNameDeprecated, - typeAnnotation: { - type: 'EventTypeAnnotation', - argument: getEventArgument(argumentProps, name), - }, - }; - } - - return { - name, - optional, - bubblingType, - typeAnnotation: { - type: 'EventTypeAnnotation', - argument: getEventArgument(argumentProps, name), - }, - }; - } - - if (argumentProps === null) { - throw new Error(`Unable to determine event arguments for "${name}"`); - } - - if (bubblingType === null) { - throw new Error(`Unable to determine event arguments for "${name}"`); - } -} - -// $FlowFixMe[unclear-type] there's no flowtype for ASTs -type EventTypeAST = Object; - -type TypeMap = { - // $FlowFixMe[unclear-type] there's no flowtype for ASTs - [string]: Object, - ... -}; - -function getEvents( - eventTypeAST: $ReadOnlyArray, - types: TypeMap, -): $ReadOnlyArray { - return eventTypeAST - .filter(property => property.type === 'ObjectTypeProperty') - .map(property => buildEventSchema(types, property)) - .filter(Boolean); -} - -module.exports = { - getEvents, -}; diff --git a/packages/react-native-codegen/src/parsers/flow/components/extends.js b/packages/react-native-codegen/src/parsers/flow/components/extends.js deleted file mode 100644 index 6f81f7b45408..000000000000 --- a/packages/react-native-codegen/src/parsers/flow/components/extends.js +++ /dev/null @@ -1,66 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {ExtendsPropsShape} from '../../../CodegenSchema.js'; -import type {TypeDeclarationMap} from '../../utils'; - -function extendsForProp(prop: PropsAST, types: TypeDeclarationMap) { - if (!prop.argument) { - console.log('null', prop); - } - const name = prop.argument.id.name; - - if (types[name] != null) { - // This type is locally defined in the file - return null; - } - - switch (name) { - case 'ViewProps': - return { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }; - default: { - throw new Error(`Unable to handle prop spread: ${name}`); - } - } -} - -function removeKnownExtends( - typeDefinition: $ReadOnlyArray, - types: TypeDeclarationMap, -): $ReadOnlyArray { - return typeDefinition.filter( - prop => - prop.type !== 'ObjectTypeSpreadProperty' || - extendsForProp(prop, types) === null, - ); -} - -// $FlowFixMe[unclear-type] there's no flowtype for ASTs -type PropsAST = Object; - -function getExtendsProps( - typeDefinition: $ReadOnlyArray, - types: TypeDeclarationMap, -): $ReadOnlyArray { - return typeDefinition - .filter(prop => prop.type === 'ObjectTypeSpreadProperty') - .map(prop => extendsForProp(prop, types)) - .filter(Boolean); -} - -module.exports = { - getExtendsProps, - removeKnownExtends, -}; diff --git a/packages/react-native-codegen/src/parsers/flow/components/index.js b/packages/react-native-codegen/src/parsers/flow/components/index.js deleted file mode 100644 index a0b1eda6cdaa..000000000000 --- a/packages/react-native-codegen/src/parsers/flow/components/index.js +++ /dev/null @@ -1,226 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; -import type {TypeDeclarationMap} from '../../utils'; -import type {CommandOptions} from './options'; -import type {ComponentSchemaBuilderConfig} from './schema.js'; - -const {getTypes} = require('../utils'); -const {getCommands} = require('./commands'); -const {getEvents} = require('./events'); -const {getExtendsProps, removeKnownExtends} = require('./extends'); -const {getCommandOptions, getOptions} = require('./options'); -const {getProps} = require('./props'); -const {getProperties} = require('./componentsUtils.js'); - -/* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's - * LTI update could not be added via codemod */ -function findComponentConfig(ast) { - const foundConfigs = []; - - const defaultExports = ast.body.filter( - node => node.type === 'ExportDefaultDeclaration', - ); - - defaultExports.forEach(statement => { - let declaration = statement.declaration; - - // codegenNativeComponent can be nested inside a cast - // expression so we need to go one level deeper - if (declaration.type === 'TypeCastExpression') { - declaration = declaration.expression; - } - - try { - if (declaration.callee.name === 'codegenNativeComponent') { - const typeArgumentParams = declaration.typeArguments.params; - const funcArgumentParams = declaration.arguments; - - const nativeComponentType: {[string]: string} = { - propsTypeName: typeArgumentParams[0].id.name, - componentName: funcArgumentParams[0].value, - }; - if (funcArgumentParams.length > 1) { - nativeComponentType.optionsExpression = funcArgumentParams[1]; - } - foundConfigs.push(nativeComponentType); - } - } catch (e) { - // ignore - } - }); - - if (foundConfigs.length === 0) { - throw new Error('Could not find component config for native component'); - } - if (foundConfigs.length > 1) { - throw new Error('Only one component is supported per file'); - } - - const foundConfig = foundConfigs[0]; - - const namedExports = ast.body.filter( - node => node.type === 'ExportNamedDeclaration', - ); - - const commandsTypeNames = namedExports - .map(statement => { - let callExpression; - let calleeName; - try { - callExpression = statement.declaration.declarations[0].init; - calleeName = callExpression.callee.name; - } catch (e) { - return; - } - - if (calleeName !== 'codegenNativeCommands') { - return; - } - - // const statement.declaration.declarations[0].init - if (callExpression.arguments.length !== 1) { - throw new Error( - 'codegenNativeCommands must be passed options including the supported commands', - ); - } - - const typeArgumentParam = callExpression.typeArguments.params[0]; - - if (typeArgumentParam.type !== 'GenericTypeAnnotation') { - throw new Error( - "codegenNativeCommands doesn't support inline definitions. Specify a file local type alias", - ); - } - - return { - commandTypeName: typeArgumentParam.id.name, - commandOptionsExpression: callExpression.arguments[0], - }; - }) - .filter(Boolean); - - if (commandsTypeNames.length > 1) { - throw new Error('codegenNativeCommands may only be called once in a file'); - } - - return { - ...foundConfig, - commandTypeName: - commandsTypeNames[0] == null - ? null - : commandsTypeNames[0].commandTypeName, - commandOptionsExpression: - commandsTypeNames[0] == null - ? null - : commandsTypeNames[0].commandOptionsExpression, - }; -} - -function getCommandProperties( - /* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's - * LTI update could not be added via codemod */ - commandTypeName, - types: TypeDeclarationMap, - commandOptions: ?CommandOptions, -) { - if (commandTypeName == null) { - return []; - } - - const typeAlias = types[commandTypeName]; - - if (typeAlias.type !== 'InterfaceDeclaration') { - throw new Error( - `The type argument for codegenNativeCommands must be an interface, received ${typeAlias.type}`, - ); - } - - let properties; - try { - properties = typeAlias.body.properties; - } catch (e) { - throw new Error( - `Failed to find type definition for "${commandTypeName}", please check that you have a valid codegen flow file`, - ); - } - - const flowPropertyNames = properties - .map(property => property && property.key && property.key.name) - .filter(Boolean); - - if (commandOptions == null || commandOptions.supportedCommands == null) { - throw new Error( - 'codegenNativeCommands must be given an options object with supportedCommands array', - ); - } - - if ( - commandOptions.supportedCommands.length !== flowPropertyNames.length || - !commandOptions.supportedCommands.every(supportedCommand => - flowPropertyNames.includes(supportedCommand), - ) - ) { - throw new Error( - `codegenNativeCommands expected the same supportedCommands specified in the ${commandTypeName} interface: ${flowPropertyNames.join( - ', ', - )}`, - ); - } - - return properties; -} - -// $FlowFixMe[signature-verification-failure] there's no flowtype for AST -/* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's - * LTI update could not be added via codemod */ -function buildComponentSchema(ast): ComponentSchemaBuilderConfig { - const { - componentName, - propsTypeName, - commandTypeName, - commandOptionsExpression, - optionsExpression, - } = findComponentConfig(ast); - - const types = getTypes(ast); - - const propProperties = getProperties(propsTypeName, types); - const commandOptions = getCommandOptions(commandOptionsExpression); - - const commandProperties = getCommandProperties( - commandTypeName, - types, - commandOptions, - ); - - const extendsProps = getExtendsProps(propProperties, types); - const options = getOptions(optionsExpression); - - const nonExtendsProps = removeKnownExtends(propProperties, types); - const props = getProps(nonExtendsProps, types); - const events = getEvents(propProperties, types); - const commands = getCommands(commandProperties, types); - - return { - filename: componentName, - componentName, - options, - extendsProps, - events, - props, - commands, - }; -} - -module.exports = { - buildComponentSchema, -}; diff --git a/packages/react-native-codegen/src/parsers/flow/components/options.js b/packages/react-native-codegen/src/parsers/flow/components/options.js deleted file mode 100644 index beb032eae320..000000000000 --- a/packages/react-native-codegen/src/parsers/flow/components/options.js +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {OptionsShape} from '../../../CodegenSchema.js'; - -// $FlowFixMe[unclear-type] there's no flowtype for ASTs -type OptionsAST = Object; - -export type CommandOptions = $ReadOnly<{ - supportedCommands: $ReadOnlyArray, -}>; - -function getCommandOptions( - commandOptionsExpression: OptionsAST, -): ?CommandOptions { - if (commandOptionsExpression == null) { - return null; - } - - let foundOptions; - try { - foundOptions = commandOptionsExpression.properties.reduce( - (options, prop) => { - options[prop.key.name] = ( - (prop && prop.value && prop.value.elements) || - [] - ).map(element => element && element.value); - return options; - }, - {}, - ); - } catch (e) { - throw new Error( - 'Failed to parse command options, please check that they are defined correctly', - ); - } - - return foundOptions; -} - -function getOptions(optionsExpression: OptionsAST): ?OptionsShape { - if (!optionsExpression) { - return null; - } - let foundOptions; - try { - foundOptions = optionsExpression.properties.reduce((options, prop) => { - if (prop.value.type === 'ArrayExpression') { - options[prop.key.name] = prop.value.elements.map( - element => element.value, - ); - } else { - options[prop.key.name] = prop.value.value; - } - return options; - }, {}); - } catch (e) { - throw new Error( - 'Failed to parse codegen options, please check that they are defined correctly', - ); - } - - if ( - foundOptions.paperComponentName && - foundOptions.paperComponentNameDeprecated - ) { - throw new Error( - 'Failed to parse codegen options, cannot use both paperComponentName and paperComponentNameDeprecated', - ); - } - - return foundOptions; -} - -module.exports = { - getCommandOptions, - getOptions, -}; diff --git a/packages/react-native-codegen/src/parsers/flow/components/props.js b/packages/react-native-codegen/src/parsers/flow/components/props.js deleted file mode 100644 index 05cdf06b0223..000000000000 --- a/packages/react-native-codegen/src/parsers/flow/components/props.js +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -const { - flattenProperties, - getSchemaInfo, - getTypeAnnotation, -} = require('./componentsUtils.js'); - -import type {NamedShape, PropTypeAnnotation} from '../../../CodegenSchema.js'; -import type {TypeDeclarationMap} from '../../utils'; - -// $FlowFixMe[unclear-type] there's no flowtype for ASTs -type PropAST = Object; - -function buildPropSchema( - property: PropAST, - types: TypeDeclarationMap, -): ?NamedShape { - const info = getSchemaInfo(property, types); - if (info == null) { - return null; - } - const {name, optional, typeAnnotation, defaultValue, withNullDefault} = info; - - return { - name, - optional, - typeAnnotation: getTypeAnnotation( - name, - typeAnnotation, - defaultValue, - withNullDefault, - types, - buildPropSchema, - ), - }; -} - -function getProps( - typeDefinition: $ReadOnlyArray, - types: TypeDeclarationMap, -): $ReadOnlyArray> { - return flattenProperties(typeDefinition, types) - .map(property => buildPropSchema(property, types)) - .filter(Boolean); -} - -module.exports = { - getProps, -}; diff --git a/packages/react-native-codegen/src/parsers/flow/components/schema.js b/packages/react-native-codegen/src/parsers/flow/components/schema.js deleted file mode 100644 index ab165031cd25..000000000000 --- a/packages/react-native-codegen/src/parsers/flow/components/schema.js +++ /dev/null @@ -1,62 +0,0 @@ -/** - * 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 - * @flow strict - */ - -'use strict'; - -import type { - EventTypeShape, - NamedShape, - CommandTypeAnnotation, - PropTypeAnnotation, - ExtendsPropsShape, - SchemaType, - OptionsShape, -} from '../../../CodegenSchema.js'; - -export type ComponentSchemaBuilderConfig = $ReadOnly<{ - filename: string, - componentName: string, - extendsProps: $ReadOnlyArray, - events: $ReadOnlyArray, - props: $ReadOnlyArray>, - commands: $ReadOnlyArray>, - options?: ?OptionsShape, -}>; - -function wrapComponentSchema({ - filename, - componentName, - extendsProps, - events, - props, - options, - commands, -}: ComponentSchemaBuilderConfig): SchemaType { - return { - modules: { - [filename]: { - type: 'Component', - components: { - [componentName]: { - ...(options || {}), - extendsProps, - events, - props, - commands, - }, - }, - }, - }, - }; -} - -module.exports = { - wrapComponentSchema, -}; diff --git a/packages/react-native-codegen/src/parsers/flow/index.js b/packages/react-native-codegen/src/parsers/flow/index.js deleted file mode 100644 index 2dfd5ff37ccd..000000000000 --- a/packages/react-native-codegen/src/parsers/flow/index.js +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {SchemaType} from '../../CodegenSchema.js'; - -// $FlowFixMe[untyped-import] there's no flowtype flow-parser -const flowParser = require('flow-parser'); -const fs = require('fs'); -const { - buildSchemaFromConfigType, - getConfigType, - isModuleRegistryCall, -} = require('../utils'); -const {buildComponentSchema} = require('./components'); -const {wrapComponentSchema} = require('./components/schema'); -const {buildModuleSchema} = require('./modules'); - -function Visitor(infoMap: {isComponent: boolean, isModule: boolean}) { - return { - CallExpression(node: $FlowFixMe) { - if ( - node.callee.type === 'Identifier' && - node.callee.name === 'codegenNativeComponent' - ) { - infoMap.isComponent = true; - } - - if (isModuleRegistryCall(node)) { - infoMap.isModule = true; - } - }, - InterfaceExtends(node: $FlowFixMe) { - if (node.id.name === 'TurboModule') { - infoMap.isModule = true; - } - }, - }; -} - -function buildSchema(contents: string, filename: ?string): SchemaType { - // Early return for non-Spec JavaScript files - if ( - !contents.includes('codegenNativeComponent') && - !contents.includes('TurboModule') - ) { - return {modules: {}}; - } - - const ast = flowParser.parse(contents, {enums: true}); - const configType = getConfigType(ast, Visitor); - - return buildSchemaFromConfigType( - configType, - filename, - ast, - wrapComponentSchema, - buildComponentSchema, - buildModuleSchema, - ); -} - -function parseModuleFixture(filename: string): SchemaType { - const contents = fs.readFileSync(filename, 'utf8'); - - return buildSchema(contents, 'path/NativeSampleTurboModule.js'); -} - -function parseString(contents: string, filename: ?string): SchemaType { - return buildSchema(contents, filename); -} - -module.exports = { - buildSchema, - parseModuleFixture, - parseString, -}; diff --git a/packages/react-native-codegen/src/parsers/flow/modules/__test_fixtures__/failures.js b/packages/react-native-codegen/src/parsers/flow/modules/__test_fixtures__/failures.js deleted file mode 100644 index 8024079b0fb6..000000000000 --- a/packages/react-native-codegen/src/parsers/flow/modules/__test_fixtures__/failures.js +++ /dev/null @@ -1,223 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -// @licenselint-loose-mode - -'use strict'; - -const NATIVE_MODULES_WITH_ARRAY_WITH_NO_TYPE_FOR_CONTENT = ` -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -export interface Spec extends TurboModule { - getString: (arg: string) => Array; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); - -`; - -const NATIVE_MODULES_WITH_ARRAY_WITH_NO_TYPE_FOR_CONTENT_AS_PARAM = ` -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -export interface Spec extends TurboModule { - getString: (arg : Array) => string; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); - -`; - -const NATIVE_MODULES_WITH_READ_ONLY_OBJECT_NO_TYPE_FOR_CONTENT = ` -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -export interface Spec extends TurboModule { - getString: (arg : $ReadOnly<>) => string; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); - -`; - -const NATIVE_MODULES_WITH_NOT_ONLY_METHODS = ` -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -export interface Spec extends TurboModule { - +getBool: (arg: boolean) => boolean; - +getNumber: (arg: number) => number; - +getString: (arg: string) => string; - sampleBool: boolean, - -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); - -`; - -const NATIVE_MODULES_WITH_UNNAMED_PARAMS = ` -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -export interface Spec extends TurboModule { - +getBool: (boolean) => boolean; - -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); - -`; - -const NATIVE_MODULES_WITH_PROMISE_WITHOUT_TYPE = ` -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -export interface Spec extends TurboModule { - +getBool: (arg: boolean) => Promise; - -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); - -`; - -const TWO_NATIVE_MODULES_EXPORTED_WITH_DEFAULT = ` -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule1'); -export default TurboModuleRegistry.getEnforcing('SampleTurboModule2'); - -`; - -const TWO_NATIVE_EXTENDING_TURBO_MODULE = ` -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -export interface Spec extends TurboModule { - +getSth: (a : ?number) => void -} - -export interface Spec2 extends TurboModule { - +getSth: (a : ?number) => void -} - - -`; - -module.exports = { - NATIVE_MODULES_WITH_READ_ONLY_OBJECT_NO_TYPE_FOR_CONTENT, - NATIVE_MODULES_WITH_UNNAMED_PARAMS, - NATIVE_MODULES_WITH_PROMISE_WITHOUT_TYPE, - NATIVE_MODULES_WITH_ARRAY_WITH_NO_TYPE_FOR_CONTENT_AS_PARAM, - NATIVE_MODULES_WITH_ARRAY_WITH_NO_TYPE_FOR_CONTENT, - TWO_NATIVE_MODULES_EXPORTED_WITH_DEFAULT, - NATIVE_MODULES_WITH_NOT_ONLY_METHODS, - TWO_NATIVE_EXTENDING_TURBO_MODULE, -}; diff --git a/packages/react-native-codegen/src/parsers/flow/modules/__test_fixtures__/fixtures.js b/packages/react-native-codegen/src/parsers/flow/modules/__test_fixtures__/fixtures.js deleted file mode 100644 index e8668947ce28..000000000000 --- a/packages/react-native-codegen/src/parsers/flow/modules/__test_fixtures__/fixtures.js +++ /dev/null @@ -1,678 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -// @licenselint-loose-mode - -'use strict'; - -const EMPTY_NATIVE_MODULE = ` -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -export interface Spec extends TurboModule { - // no methods -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); - -`; - -const NATIVE_MODULE_WITH_COMPLEX_OBJECTS = ` -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -export type String = string; - -export interface Spec extends TurboModule { - // Exported methods. - +getObject: (arg: {|const1: {|const1: boolean|}|}) => {| - const1: {|const1: boolean|}, - |}; - +getReadOnlyObject: (arg: $ReadOnly<{|const1: $ReadOnly<{|const1: boolean|}>|}>) => $ReadOnly<{| - const1: {|const1: boolean|}, - |}>; - +getObject2: (arg: { a: String }) => Object; - +getObjectInArray: (arg: {const1: {|const1: boolean|}}) => Array<{| - const1: {const1: boolean}, - |}>; -} -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); - -`; - -const NATIVE_MODULE_WITH_COMPLEX_OBJECTS_WITH_NULLABLE_KEY = ` -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -export interface Spec extends TurboModule { - +getConstants: () => {| - isTesting: boolean, - reactNativeVersion: {| - major: number, - minor: number, - patch?: number, - prerelease: ?number, - |}, - forceTouchAvailable: boolean, - osVersion: string, - systemName: string, - interfaceIdiom: string, - |}; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); - -`; - -const NATIVE_MODULE_WITH_BASIC_PARAM_TYPES = ` -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -export interface Spec extends TurboModule { - +passBool?: (arg: boolean) => void; - +passNumber: (arg: number) => void; - +passString: (arg: string) => void; - +passStringish: (arg: Stringish) => void; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); - -`; - -const NATIVE_MODULE_WITH_ALIASES = ` -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -type NumNum = number; -export type Num = (arg: NumNum) => void; -type Num2 = Num; -export type Void = void; -export type A = number; -export type B = number; -export type ObjectAlias = {| - x: number, - y: number, - label: string, - truthy: boolean, -|}; -export type ReadOnlyAlias = $ReadOnly; - -export interface Spec extends TurboModule { - // Exported methods. - +getNumber: Num2; - +getVoid: () => Void; - +getArray: (a: Array) => {| a: B |}; - +getStringFromAlias: (a: ObjectAlias) => string; - +getStringFromNullableAlias: (a: ?ObjectAlias) => string; - +getStringFromReadOnlyAlias: (a: ReadOnlyAlias) => string; - +getStringFromNullableReadOnlyAlias: (a: ?ReadOnlyAlias) => string; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); - -`; - -const NATIVE_MODULE_WITH_NESTED_ALIASES = ` -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -type Bar = {| - z: number -|}; - -type Foo = {| - bar1: Bar, - bar2: Bar, -|}; - -export interface Spec extends TurboModule { - // Exported methods. - foo1: (x: Foo) => Foo; - foo2: (x: Foo) => void; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); - -`; - -const NATIVE_MODULE_WITH_FLOAT_AND_INT32 = ` -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; -import type {Int32, Float} from 'react-native/Libraries/Types/CodegenTypes'; - -export interface Spec extends TurboModule { - +getInt: (arg: Int32) => Int32; - +getFloat: (arg: Float) => Float; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); -`; - -const NATIVE_MODULE_WITH_SIMPLE_OBJECT = ` -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -export interface Spec extends TurboModule { - +getObject: (o: Object) => Object, -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); - -`; - -const NATIVE_MODULE_WITH_UNSAFE_OBJECT = ` -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; -import type {UnsafeObject} from 'react-native/Libraries/Types/CodegenTypes'; - -export interface Spec extends TurboModule { - +getUnsafeObject: (o: UnsafeObject) => UnsafeObject, -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); - -`; - -const NATIVE_MODULE_WITH_ROOT_TAG = ` -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {RootTag, TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -export interface Spec extends TurboModule { - +getRootTag: (rootTag: RootTag) => RootTag, -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); - -`; - -const NATIVE_MODULE_WITH_NULLABLE_PARAM = ` -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -export interface Spec extends TurboModule { - // Exported methods. - +voidFunc: (arg: ?string) => void; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); - -`; - -const NATIVE_MODULE_WITH_BASIC_ARRAY = ` -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -export interface Spec extends TurboModule { - +getArray: (arg: Array) => Array; - +getArray: (arg: $ReadOnlyArray) => $ReadOnlyArray; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); - -`; - -const NATIVE_MODULE_WITH_OBJECT_WITH_OBJECT_DEFINED_IN_FILE_AS_PROPERTY = ` -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -type DisplayMetricsAndroid = {| - width: number, -|}; - -export interface Spec extends TurboModule { - +getConstants: () => {| - +Dimensions: { - windowPhysicalPixels: DisplayMetricsAndroid, - }, - |}; - +getConstants2: () => $ReadOnly<{| - +Dimensions: { - windowPhysicalPixels: DisplayMetricsAndroid, - }, - |}>; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); - -`; - -const NATIVE_MODULE_WITH_ARRAY_WITH_UNION_AND_TOUPLE = ` -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -export interface Spec extends TurboModule { - +getArray: (arg: Array<[string, string]>) => Array; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); - -`; - -const NATIVE_MODULE_WITH_ARRAY_WITH_ALIAS = ` -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -export type SomeString = string; - -export interface Spec extends TurboModule { - +getArray: (arg: Array) => Array; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); - -`; - -const NATIVE_MODULE_WITH_COMPLEX_ARRAY = ` -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -export interface Spec extends TurboModule { - +getArray: (arg: Array>>>>) => Array>>; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); - -`; - -const NATIVE_MODULE_WITH_PROMISE = ` -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -export type String = string; -export type SomeObj = {| a: string |}; - -export interface Spec extends TurboModule { - +getValueWithPromise: () => Promise; - +getValueWithPromiseDefinedSomewhereElse: () => Promise; - +getValueWithPromiseObjDefinedSomewhereElse: () => Promise; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); - -`; - -const NATIVE_MODULE_WITH_CALLBACK = ` -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -export interface Spec extends TurboModule { - // Exported methods. - +getValueWithCallback: ( - callback: (value: string, arr: Array>) => void, - ) => void; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); - -`; - -const ANDROID_ONLY_NATIVE_MODULE = ` -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -export interface Spec extends TurboModule { - // no methods -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModuleAndroid'); - -`; - -const IOS_ONLY_NATIVE_MODULE = ` -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -export enum Quality { - SD, - HD, -} - -export enum Resolution { - Low = 720, - High = 1080, -} - -export enum Floppy { - LowDensity = 0.72, - HighDensity = 1.44, -} - -export enum StringOptions { - One = 'one', - Two = 'two', - Three = 'three', -} - -export interface Spec extends TurboModule { - +getEnums: (quality: Quality, resolution?: Resolution, floppy: Floppy, stringOptions: StringOptions) => string; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModuleIOS'); - -`; - -const CXX_ONLY_NATIVE_MODULE = ` -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -export type ChooseInt = 1 | 2 | 3; -export type ChooseFloat = 1.44 | 2.88 | 5.76; -export type ChooseObject = {} | {low: string}; -export type ChooseString = 'One' | 'Two' | 'Three'; - -export enum Quality { - SD, - HD, -} - -export enum Resolution { - Low = 720, - High = 1080, -} - -export enum Floppy { - LowDensity = 0.72, - HighDensity = 1.44, -} - -export enum StringOptions { - One = 'one', - Two = 'two', - Three = 'three', -} - -export interface Spec extends TurboModule { - +getCallback: () => () => void; - +getMixed: (arg: mixed) => mixed; - +getEnums: (quality: Quality, resolution?: Resolution, floppy: Floppy, stringOptions: StringOptions) => string; - +getMap: (arg: {[a: string]: ?number}) => {[b: string]: ?number}; - +getAnotherMap: (arg: {[string]: string}) => {[string]: string}; - +getUnion: (chooseInt: ChooseInt, chooseFloat: ChooseFloat, chooseObject: ChooseObject, chooseString: ChooseString) => ChooseObject; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModuleCxx'); - -`; - -module.exports = { - NATIVE_MODULE_WITH_OBJECT_WITH_OBJECT_DEFINED_IN_FILE_AS_PROPERTY, - NATIVE_MODULE_WITH_ARRAY_WITH_UNION_AND_TOUPLE, - NATIVE_MODULE_WITH_FLOAT_AND_INT32, - NATIVE_MODULE_WITH_ALIASES, - NATIVE_MODULE_WITH_NESTED_ALIASES, - NATIVE_MODULE_WITH_PROMISE, - NATIVE_MODULE_WITH_COMPLEX_OBJECTS, - NATIVE_MODULE_WITH_COMPLEX_OBJECTS_WITH_NULLABLE_KEY, - NATIVE_MODULE_WITH_SIMPLE_OBJECT, - NATIVE_MODULE_WITH_UNSAFE_OBJECT, - NATIVE_MODULE_WITH_ROOT_TAG, - NATIVE_MODULE_WITH_NULLABLE_PARAM, - NATIVE_MODULE_WITH_BASIC_ARRAY, - NATIVE_MODULE_WITH_COMPLEX_ARRAY, - NATIVE_MODULE_WITH_ARRAY_WITH_ALIAS, - NATIVE_MODULE_WITH_BASIC_PARAM_TYPES, - NATIVE_MODULE_WITH_CALLBACK, - EMPTY_NATIVE_MODULE, - ANDROID_ONLY_NATIVE_MODULE, - IOS_ONLY_NATIVE_MODULE, - CXX_ONLY_NATIVE_MODULE, -}; diff --git a/packages/react-native-codegen/src/parsers/flow/modules/__tests__/__snapshots__/module-parser-snapshot-test.js.snap b/packages/react-native-codegen/src/parsers/flow/modules/__tests__/__snapshots__/module-parser-snapshot-test.js.snap deleted file mode 100644 index 8f308ace82dc..000000000000 --- a/packages/react-native-codegen/src/parsers/flow/modules/__tests__/__snapshots__/module-parser-snapshot-test.js.snap +++ /dev/null @@ -1,1666 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`RN Codegen Flow Parser Fails with error message NATIVE_MODULES_WITH_ARRAY_WITH_NO_TYPE_FOR_CONTENT 1`] = `"Module NativeSampleTurboModule: Generic 'Array' must have type parameters."`; - -exports[`RN Codegen Flow Parser Fails with error message NATIVE_MODULES_WITH_ARRAY_WITH_NO_TYPE_FOR_CONTENT_AS_PARAM 1`] = `"Module NativeSampleTurboModule: Generic 'Array' must have type parameters."`; - -exports[`RN Codegen Flow Parser Fails with error message NATIVE_MODULES_WITH_NOT_ONLY_METHODS 1`] = `"Module NativeSampleTurboModule: Flow interfaces extending TurboModule must only contain 'FunctionTypeAnnotation's. Property 'sampleBool' refers to a 'BooleanTypeAnnotation'."`; - -exports[`RN Codegen Flow Parser Fails with error message NATIVE_MODULES_WITH_PROMISE_WITHOUT_TYPE 1`] = `"Module NativeSampleTurboModule: Generic 'Promise' must have type parameters."`; - -exports[`RN Codegen Flow Parser Fails with error message NATIVE_MODULES_WITH_READ_ONLY_OBJECT_NO_TYPE_FOR_CONTENT 1`] = `"Module NativeSampleTurboModule: Generic '$ReadOnly' must have exactly one type parameter."`; - -exports[`RN Codegen Flow Parser Fails with error message NATIVE_MODULES_WITH_UNNAMED_PARAMS 1`] = `"Module NativeSampleTurboModule: All function parameters must be named."`; - -exports[`RN Codegen Flow Parser Fails with error message TWO_NATIVE_EXTENDING_TURBO_MODULE 1`] = `"Module NativeSampleTurboModule: Every NativeModule spec file must declare exactly one NativeModule Flow interface. This file declares 2: 'Spec', and 'Spec2'. Please remove the extraneous Flow interface declarations."`; - -exports[`RN Codegen Flow Parser Fails with error message TWO_NATIVE_MODULES_EXPORTED_WITH_DEFAULT 1`] = `"Module NativeSampleTurboModule: No Flow interfaces extending TurboModule were detected in this NativeModule spec."`; - -exports[`RN Codegen Flow Parser can generate fixture ANDROID_ONLY_NATIVE_MODULE 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [] - }, - 'moduleNames': [ - 'SampleTurboModuleAndroid' - ], - 'excludedPlatforms': [ - 'iOS' - ] - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture CXX_ONLY_NATIVE_MODULE 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getCallback', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - }, - 'params': [] - }, - 'params': [] - } - }, - { - 'name': 'getMixed', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'MixedTypeAnnotation' - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'MixedTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'getEnums', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'StringTypeAnnotation' - }, - 'params': [ - { - 'name': 'quality', - 'optional': false, - 'typeAnnotation': { - 'type': 'EnumDeclaration', - 'memberType': 'StringTypeAnnotation' - } - }, - { - 'name': 'resolution', - 'optional': true, - 'typeAnnotation': { - 'type': 'EnumDeclaration', - 'memberType': 'NumberTypeAnnotation' - } - }, - { - 'name': 'floppy', - 'optional': false, - 'typeAnnotation': { - 'type': 'EnumDeclaration', - 'memberType': 'NumberTypeAnnotation' - } - }, - { - 'name': 'stringOptions', - 'optional': false, - 'typeAnnotation': { - 'type': 'EnumDeclaration', - 'memberType': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'getMap', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'b', - 'optional': false, - 'typeAnnotation': { - 'type': 'GenericObjectTypeAnnotation' - } - } - ] - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'a', - 'optional': false, - 'typeAnnotation': { - 'type': 'GenericObjectTypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'getAnotherMap', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'key', - 'optional': false, - 'typeAnnotation': { - 'type': 'GenericObjectTypeAnnotation' - } - } - ] - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'key', - 'optional': false, - 'typeAnnotation': { - 'type': 'GenericObjectTypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'getUnion', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'UnionTypeAnnotation', - 'memberType': 'ObjectTypeAnnotation' - }, - 'params': [ - { - 'name': 'chooseInt', - 'optional': false, - 'typeAnnotation': { - 'type': 'UnionTypeAnnotation', - 'memberType': 'NumberTypeAnnotation' - } - }, - { - 'name': 'chooseFloat', - 'optional': false, - 'typeAnnotation': { - 'type': 'UnionTypeAnnotation', - 'memberType': 'NumberTypeAnnotation' - } - }, - { - 'name': 'chooseObject', - 'optional': false, - 'typeAnnotation': { - 'type': 'UnionTypeAnnotation', - 'memberType': 'ObjectTypeAnnotation' - } - }, - { - 'name': 'chooseString', - 'optional': false, - 'typeAnnotation': { - 'type': 'UnionTypeAnnotation', - 'memberType': 'StringTypeAnnotation' - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModuleCxx' - ], - 'excludedPlatforms': [ - 'iOS', - 'android' - ] - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture EMPTY_NATIVE_MODULE 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture IOS_ONLY_NATIVE_MODULE 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getEnums', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'StringTypeAnnotation' - }, - 'params': [ - { - 'name': 'quality', - 'optional': false, - 'typeAnnotation': { - 'type': 'EnumDeclaration', - 'memberType': 'StringTypeAnnotation' - } - }, - { - 'name': 'resolution', - 'optional': true, - 'typeAnnotation': { - 'type': 'EnumDeclaration', - 'memberType': 'NumberTypeAnnotation' - } - }, - { - 'name': 'floppy', - 'optional': false, - 'typeAnnotation': { - 'type': 'EnumDeclaration', - 'memberType': 'NumberTypeAnnotation' - } - }, - { - 'name': 'stringOptions', - 'optional': false, - 'typeAnnotation': { - 'type': 'EnumDeclaration', - 'memberType': 'StringTypeAnnotation' - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModuleIOS' - ], - 'excludedPlatforms': [ - 'android' - ] - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture NATIVE_MODULE_WITH_ALIASES 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': { - 'ObjectAlias': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'x', - 'optional': false, - 'typeAnnotation': { - 'type': 'NumberTypeAnnotation' - } - }, - { - 'name': 'y', - 'optional': false, - 'typeAnnotation': { - 'type': 'NumberTypeAnnotation' - } - }, - { - 'name': 'label', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'truthy', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - 'spec': { - 'properties': [ - { - 'name': 'getNumber', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'NumberTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'getVoid', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - }, - 'params': [] - } - }, - { - 'name': 'getArray', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'a', - 'optional': false, - 'typeAnnotation': { - 'type': 'NumberTypeAnnotation' - } - } - ] - }, - 'params': [ - { - 'name': 'a', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'NumberTypeAnnotation' - } - } - } - ] - } - }, - { - 'name': 'getStringFromAlias', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'StringTypeAnnotation' - }, - 'params': [ - { - 'name': 'a', - 'optional': false, - 'typeAnnotation': { - 'type': 'TypeAliasTypeAnnotation', - 'name': 'ObjectAlias' - } - } - ] - } - }, - { - 'name': 'getStringFromNullableAlias', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'StringTypeAnnotation' - }, - 'params': [ - { - 'name': 'a', - 'optional': false, - 'typeAnnotation': { - 'type': 'NullableTypeAnnotation', - 'typeAnnotation': { - 'type': 'TypeAliasTypeAnnotation', - 'name': 'ObjectAlias' - } - } - } - ] - } - }, - { - 'name': 'getStringFromReadOnlyAlias', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'StringTypeAnnotation' - }, - 'params': [ - { - 'name': 'a', - 'optional': false, - 'typeAnnotation': { - 'type': 'TypeAliasTypeAnnotation', - 'name': 'ObjectAlias' - } - } - ] - } - }, - { - 'name': 'getStringFromNullableReadOnlyAlias', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'StringTypeAnnotation' - }, - 'params': [ - { - 'name': 'a', - 'optional': false, - 'typeAnnotation': { - 'type': 'NullableTypeAnnotation', - 'typeAnnotation': { - 'type': 'TypeAliasTypeAnnotation', - 'name': 'ObjectAlias' - } - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture NATIVE_MODULE_WITH_ARRAY_WITH_ALIAS 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getArray', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture NATIVE_MODULE_WITH_ARRAY_WITH_UNION_AND_TOUPLE 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getArray', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ArrayTypeAnnotation' - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation' - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture NATIVE_MODULE_WITH_BASIC_ARRAY 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getArray', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - } - ] - } - }, - { - 'name': 'getArray', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture NATIVE_MODULE_WITH_BASIC_PARAM_TYPES 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'passBool', - 'optional': true, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'passNumber', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'NumberTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'passString', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'passStringish', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture NATIVE_MODULE_WITH_CALLBACK 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getValueWithCallback', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - }, - 'params': [ - { - 'name': 'callback', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - }, - 'params': [ - { - 'name': 'value', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'arr', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - } - } - ] - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture NATIVE_MODULE_WITH_COMPLEX_ARRAY 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getArray', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - } - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - } - } - } - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture NATIVE_MODULE_WITH_COMPLEX_OBJECTS 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getObject', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'const1', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'const1', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - } - ] - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'const1', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'const1', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - } - ] - } - } - ] - } - }, - { - 'name': 'getReadOnlyObject', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'const1', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'const1', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - } - ] - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'const1', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'const1', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - } - ] - } - } - ] - } - }, - { - 'name': 'getObject2', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'GenericObjectTypeAnnotation' - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'a', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'getObjectInArray', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'const1', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'const1', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - } - ] - } - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'const1', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'const1', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - } - ] - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture NATIVE_MODULE_WITH_COMPLEX_OBJECTS_WITH_NULLABLE_KEY 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getConstants', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'isTesting', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'reactNativeVersion', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'major', - 'optional': false, - 'typeAnnotation': { - 'type': 'NumberTypeAnnotation' - } - }, - { - 'name': 'minor', - 'optional': false, - 'typeAnnotation': { - 'type': 'NumberTypeAnnotation' - } - }, - { - 'name': 'patch', - 'optional': true, - 'typeAnnotation': { - 'type': 'NumberTypeAnnotation' - } - }, - { - 'name': 'prerelease', - 'optional': false, - 'typeAnnotation': { - 'type': 'NullableTypeAnnotation', - 'typeAnnotation': { - 'type': 'NumberTypeAnnotation' - } - } - } - ] - } - }, - { - 'name': 'forceTouchAvailable', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'osVersion', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'systemName', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'interfaceIdiom', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - }, - 'params': [] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture NATIVE_MODULE_WITH_FLOAT_AND_INT32 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getInt', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'Int32TypeAnnotation' - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'getFloat', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'FloatTypeAnnotation' - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture NATIVE_MODULE_WITH_NESTED_ALIASES 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': { - 'Bar': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'z', - 'optional': false, - 'typeAnnotation': { - 'type': 'NumberTypeAnnotation' - } - } - ] - }, - 'Foo': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'bar1', - 'optional': false, - 'typeAnnotation': { - 'type': 'TypeAliasTypeAnnotation', - 'name': 'Bar' - } - }, - { - 'name': 'bar2', - 'optional': false, - 'typeAnnotation': { - 'type': 'TypeAliasTypeAnnotation', - 'name': 'Bar' - } - } - ] - } - }, - 'spec': { - 'properties': [ - { - 'name': 'foo1', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'TypeAliasTypeAnnotation', - 'name': 'Foo' - }, - 'params': [ - { - 'name': 'x', - 'optional': false, - 'typeAnnotation': { - 'type': 'TypeAliasTypeAnnotation', - 'name': 'Foo' - } - } - ] - } - }, - { - 'name': 'foo2', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - }, - 'params': [ - { - 'name': 'x', - 'optional': false, - 'typeAnnotation': { - 'type': 'TypeAliasTypeAnnotation', - 'name': 'Foo' - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture NATIVE_MODULE_WITH_NULLABLE_PARAM 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'voidFunc', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'NullableTypeAnnotation', - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture NATIVE_MODULE_WITH_OBJECT_WITH_OBJECT_DEFINED_IN_FILE_AS_PROPERTY 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': { - 'DisplayMetricsAndroid': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'width', - 'optional': false, - 'typeAnnotation': { - 'type': 'NumberTypeAnnotation' - } - } - ] - } - }, - 'spec': { - 'properties': [ - { - 'name': 'getConstants', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'Dimensions', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'windowPhysicalPixels', - 'optional': false, - 'typeAnnotation': { - 'type': 'TypeAliasTypeAnnotation', - 'name': 'DisplayMetricsAndroid' - } - } - ] - } - } - ] - }, - 'params': [] - } - }, - { - 'name': 'getConstants2', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'Dimensions', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'windowPhysicalPixels', - 'optional': false, - 'typeAnnotation': { - 'type': 'TypeAliasTypeAnnotation', - 'name': 'DisplayMetricsAndroid' - } - } - ] - } - } - ] - }, - 'params': [] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture NATIVE_MODULE_WITH_PROMISE 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getValueWithPromise', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'PromiseTypeAnnotation' - }, - 'params': [] - } - }, - { - 'name': 'getValueWithPromiseDefinedSomewhereElse', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'PromiseTypeAnnotation' - }, - 'params': [] - } - }, - { - 'name': 'getValueWithPromiseObjDefinedSomewhereElse', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'PromiseTypeAnnotation' - }, - 'params': [] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture NATIVE_MODULE_WITH_ROOT_TAG 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getRootTag', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ReservedTypeAnnotation', - 'name': 'RootTag' - }, - 'params': [ - { - 'name': 'rootTag', - 'optional': false, - 'typeAnnotation': { - 'type': 'ReservedTypeAnnotation', - 'name': 'RootTag' - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture NATIVE_MODULE_WITH_SIMPLE_OBJECT 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getObject', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'GenericObjectTypeAnnotation' - }, - 'params': [ - { - 'name': 'o', - 'optional': false, - 'typeAnnotation': { - 'type': 'GenericObjectTypeAnnotation' - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen Flow Parser can generate fixture NATIVE_MODULE_WITH_UNSAFE_OBJECT 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getUnsafeObject', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'GenericObjectTypeAnnotation' - }, - 'params': [ - { - 'name': 'o', - 'optional': false, - 'typeAnnotation': { - 'type': 'GenericObjectTypeAnnotation' - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; diff --git a/packages/react-native-codegen/src/parsers/flow/modules/__tests__/module-parser-e2e-test.js b/packages/react-native-codegen/src/parsers/flow/modules/__tests__/module-parser-e2e-test.js deleted file mode 100644 index c1f959b7a884..000000000000 --- a/packages/react-native-codegen/src/parsers/flow/modules/__tests__/module-parser-e2e-test.js +++ /dev/null @@ -1,1239 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -import type { - NativeModuleReturnTypeAnnotation, - NativeModuleBaseTypeAnnotation, - NativeModuleSchema, - NativeModuleParamTypeAnnotation, -} from '../../../../CodegenSchema'; - -const {parseString} = require('../../index.js'); -const {unwrapNullable} = require('../../../parsers-commons'); -const { - UnsupportedGenericParserError, - UnsupportedTypeAnnotationParserError, - UnnamedFunctionParamParserError, - MissingTypeParameterGenericParserError, -} = require('../../../errors'); -const invariant = require('invariant'); - -type PrimitiveTypeAnnotationType = - | 'StringTypeAnnotation' - | 'NumberTypeAnnotation' - | 'Int32TypeAnnotation' - | 'DoubleTypeAnnotation' - | 'FloatTypeAnnotation' - | 'BooleanTypeAnnotation'; - -const PRIMITIVES: $ReadOnlyArray<[string, PrimitiveTypeAnnotationType]> = [ - ['string', 'StringTypeAnnotation'], - ['number', 'NumberTypeAnnotation'], - ['Int32', 'Int32TypeAnnotation'], - ['Double', 'DoubleTypeAnnotation'], - ['Float', 'FloatTypeAnnotation'], - ['boolean', 'BooleanTypeAnnotation'], -]; - -const RESERVED_FUNCTION_VALUE_TYPE_NAME: $ReadOnlyArray<'RootTag'> = [ - 'RootTag', -]; - -const MODULE_NAME = 'NativeFoo'; - -const TYPE_ALIAS_DECLARATIONS = ` -type Animal = { - name: string, -}; - -type AnimalPointer = Animal; -`; - -function expectAnimalTypeAliasToExist(module: NativeModuleSchema) { - const animalAlias = module.aliases.Animal; - - expect(animalAlias).not.toBe(null); - invariant(animalAlias != null, ''); - expect(animalAlias.type).toBe('ObjectTypeAnnotation'); - expect(animalAlias.properties.length).toBe(1); - expect(animalAlias.properties[0].name).toBe('name'); - expect(animalAlias.properties[0].optional).toBe(false); - - const [typeAnnotation, nullable] = unwrapNullable( - animalAlias.properties[0].typeAnnotation, - ); - - expect(typeAnnotation.type).toBe('StringTypeAnnotation'); - expect(nullable).toBe(false); -} - -describe('Flow Module Parser', () => { - describe('Parameter Parsing', () => { - it("should fail parsing when a method has an parameter of type 'any'", () => { - const parser = () => - parseModule(` - import type {TurboModule} from 'RCTExport'; - import * as TurboModuleRegistry from 'TurboModuleRegistry'; - export interface Spec extends TurboModule { - +useArg(arg: any): void; - } - export default TurboModuleRegistry.get('Foo'); - `); - - expect(parser).toThrow(UnsupportedTypeAnnotationParserError); - }); - - it('should fail parsing when a function param type is unamed', () => { - const parser = () => - parseModule(` - import type {TurboModule} from 'RCTExport'; - import * as TurboModuleRegistry from 'TurboModuleRegistry'; - export interface Spec extends TurboModule { - +useArg(boolean): void; - } - export default TurboModuleRegistry.get('Foo'); - `); - - expect(parser).toThrow(UnnamedFunctionParamParserError); - }); - - [ - {nullable: false, optional: false}, - {nullable: false, optional: true}, - {nullable: true, optional: false}, - {nullable: true, optional: true}, - ].forEach(({nullable, optional}) => { - const PARAM_TYPE_DESCRIPTION = - nullable && optional - ? 'a nullable and optional' - : nullable - ? 'a nullable' - : optional - ? 'an optional' - : 'a required'; - - function annotateArg(paramName: string, paramType: string) { - if (nullable && optional) { - return `${paramName}?: ?${paramType}`; - } - if (nullable) { - return `${paramName}: ?${paramType}`; - } - if (optional) { - return `${paramName}?: ${paramType}`; - } - return `${paramName}: ${paramType}`; - } - - function parseParamType( - paramName: string, - paramType: string, - ): [NativeModuleParamTypeAnnotation, NativeModuleSchema] { - const module = parseModule(` - import type {TurboModule} from 'RCTExport'; - import * as TurboModuleRegistry from 'TurboModuleRegistry'; - - ${TYPE_ALIAS_DECLARATIONS} - - export interface Spec extends TurboModule { - +useArg(${annotateArg(paramName, paramType)}): void; - } - export default TurboModuleRegistry.get('Foo'); - `); - - expect(module.spec.properties[0]).not.toBe(null); - const param = unwrapNullable( - module.spec.properties[0].typeAnnotation, - )[0].params[0]; - expect(param).not.toBe(null); - expect(param.name).toBe(paramName); - expect(param.optional).toBe(optional); - const [paramTypeAnnotation, isParamTypeAnnotationNullable] = - unwrapNullable(param.typeAnnotation); - expect(isParamTypeAnnotationNullable).toBe(nullable); - - return [paramTypeAnnotation, module]; - } - - describe( - (nullable && optional - ? 'Nullable and Optional' - : nullable - ? 'Nullable' - : optional - ? 'Optional' - : 'Required') + ' Parameter', - () => { - it(`should not parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of type 'Function'`, () => { - expect(() => parseParamType('arg', 'Function')).toThrow( - UnsupportedGenericParserError, - ); - }); - - describe('Primitive types', () => { - PRIMITIVES.forEach(([FLOW_TYPE, PARSED_TYPE_NAME]) => { - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} primitive parameter of type '${FLOW_TYPE}'`, () => { - const [paramTypeAnnotation] = parseParamType('arg', FLOW_TYPE); - expect(paramTypeAnnotation.type).toBe(PARSED_TYPE_NAME); - }); - }); - }); - - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of type 'Object'`, () => { - const [paramTypeAnnotation] = parseParamType('arg', 'Object'); - expect(paramTypeAnnotation.type).toBe( - 'GenericObjectTypeAnnotation', - ); - }); - - describe('Reserved Types', () => { - RESERVED_FUNCTION_VALUE_TYPE_NAME.forEach(FLOW_TYPE => { - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of reserved type '${FLOW_TYPE}'`, () => { - const [paramTypeAnnotation] = parseParamType('arg', FLOW_TYPE); - - expect(paramTypeAnnotation.type).toBe('ReservedTypeAnnotation'); - invariant( - paramTypeAnnotation.type === 'ReservedTypeAnnotation', - 'Param must be a Reserved type', - ); - - expect(paramTypeAnnotation.name).toBe(FLOW_TYPE); - }); - }); - }); - - describe('Array Types', () => { - it(`should not parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of type 'Array'`, () => { - expect(() => parseParamType('arg', 'Array')).toThrow( - MissingTypeParameterGenericParserError, - ); - }); - - function parseParamArrayElementType( - paramName: string, - paramType: string, - ): [NativeModuleBaseTypeAnnotation, NativeModuleSchema] { - const [paramTypeAnnotation, module] = parseParamType( - paramName, - `Array<${paramType}>`, - ); - - expect(paramTypeAnnotation.type).toBe('ArrayTypeAnnotation'); - invariant(paramTypeAnnotation.type === 'ArrayTypeAnnotation', ''); - - expect(paramTypeAnnotation.elementType).not.toBe(null); - invariant(paramTypeAnnotation.elementType != null, ''); - const [elementType, isElementTypeNullable] = - unwrapNullable( - paramTypeAnnotation.elementType, - ); - expect(isElementTypeNullable).toBe(false); - return [elementType, module]; - } - - // TODO: Do we support nullable element types? - - describe('Primitive Element Types', () => { - PRIMITIVES.forEach(([FLOW_TYPE, PARSED_TYPE_NAME]) => { - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of type 'Array<${FLOW_TYPE}>'`, () => { - const [elementType] = parseParamArrayElementType( - 'arg', - FLOW_TYPE, - ); - expect(elementType.type).toBe(PARSED_TYPE_NAME); - }); - }); - }); - - describe('Reserved Element Types', () => { - RESERVED_FUNCTION_VALUE_TYPE_NAME.forEach(FLOW_TYPE => { - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of type 'Array<${FLOW_TYPE}>'`, () => { - const [elementType] = parseParamArrayElementType( - 'arg', - FLOW_TYPE, - ); - expect(elementType.type).toBe('ReservedTypeAnnotation'); - invariant(elementType.type === 'ReservedTypeAnnotation', ''); - - expect(elementType.name).toBe(FLOW_TYPE); - }); - }); - }); - - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of type 'Array'`, () => { - const [elementType] = parseParamArrayElementType('arg', 'Object'); - expect(elementType.type).toBe('GenericObjectTypeAnnotation'); - }); - - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of some array of an alias`, () => { - const [elementType, module] = parseParamArrayElementType( - 'arg', - 'Animal', - ); - expect(elementType.type).toBe('TypeAliasTypeAnnotation'); - invariant(elementType.type === 'TypeAliasTypeAnnotation', ''); - - expect(elementType.name).toBe('Animal'); - expectAnimalTypeAliasToExist(module); - }); - - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of type 'Array<{foo: ?string}>'`, () => { - const [elementType] = parseParamArrayElementType( - 'arg', - '{foo: ?string}', - ); - expect(elementType).not.toBe(null); - - expect(elementType.type).toBe('ObjectTypeAnnotation'); - invariant(elementType.type === 'ObjectTypeAnnotation', ''); - - const {properties} = elementType; - invariant(properties != null, ''); - - expect(properties).not.toBe(null); - expect(properties[0]).not.toBe(null); - expect(properties[0].name).toBe('foo'); - expect(properties[0].typeAnnotation).not.toBe(null); - - const [typeAnnotation, isPropertyNullable] = unwrapNullable( - properties[0].typeAnnotation, - ); - - expect(typeAnnotation.type).toBe('StringTypeAnnotation'); - expect(isPropertyNullable).toBe(true); - expect(properties[0].optional).toBe(false); - }); - }); - - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of some type alias`, () => { - const [paramTypeAnnotation, module] = parseParamType( - 'arg', - 'Animal', - ); - expect(paramTypeAnnotation.type).toBe('TypeAliasTypeAnnotation'); - invariant( - paramTypeAnnotation.type === 'TypeAliasTypeAnnotation', - '', - ); - - expect(paramTypeAnnotation.name).toBe('Animal'); - expectAnimalTypeAliasToExist(module); - }); - - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of some type alias that points to another type alias`, () => { - const [paramTypeAnnotation, module] = parseParamType( - 'arg', - 'AnimalPointer', - ); - expect(paramTypeAnnotation.type).toBe('TypeAliasTypeAnnotation'); - invariant( - paramTypeAnnotation.type === 'TypeAliasTypeAnnotation', - '', - ); - - expect(paramTypeAnnotation.name).toBe('Animal'); - expectAnimalTypeAliasToExist(module); - }); - - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of some type alias that points to another nullable type alias`, () => { - const module = parseModule(` - import type {TurboModule} from 'RCTExport'; - import * as TurboModuleRegistry from 'TurboModuleRegistry'; - - type Animal = ?{ - name: string, - }; - - type AnimalPointer = Animal; - - export interface Spec extends TurboModule { - +useArg(${annotateArg('arg', 'AnimalPointer')}): void; - } - export default TurboModuleRegistry.get('Foo'); - `); - - expect(module.spec.properties[0]).not.toBe(null); - const param = unwrapNullable( - module.spec.properties[0].typeAnnotation, - )[0].params[0]; - expect(param.name).toBe('arg'); - expect(param.optional).toBe(optional); - - // The TypeAliasAnnotation is called Animal, and is nullable - const [paramTypeAnnotation, isParamTypeAnnotationNullable] = - unwrapNullable(param.typeAnnotation); - expect(paramTypeAnnotation.type).toBe('TypeAliasTypeAnnotation'); - invariant( - paramTypeAnnotation.type === 'TypeAliasTypeAnnotation', - '', - ); - expect(paramTypeAnnotation.name).toBe('Animal'); - expect(isParamTypeAnnotationNullable).toBe(true); - - // The Animal type alias RHS is valid, and non-null - expectAnimalTypeAliasToExist(module); - }); - - [ - {nullable: false, optional: false}, - {nullable: false, optional: true}, - {nullable: true, optional: false}, - {nullable: true, optional: true}, - ].forEach(({nullable: isPropNullable, optional: isPropOptional}) => { - const PROP_TYPE_DESCRIPTION = - isPropNullable && isPropOptional - ? 'a nullable and optional' - : isPropNullable - ? 'a nullable' - : isPropOptional - ? 'an optional' - : 'a required'; - - function annotateProp(propName: string, propType: string) { - if (isPropNullable && isPropOptional) { - return `${propName}?: ?${propType}`; - } - if (isPropNullable) { - return `${propName}: ?${propType}`; - } - if (isPropOptional) { - return `${propName}?: ${propType}`; - } - return `${propName}: ${propType}`; - } - - function parseParamTypeObjectLiteralProp( - propName: string, - propType: string, - ): [ - $ReadOnly<{ - name: string, - optional: boolean, - typeAnnotation: NativeModuleBaseTypeAnnotation, - }>, - NativeModuleSchema, - ] { - const [paramTypeAnnotation, module] = parseParamType( - 'arg', - `{${annotateProp(propName, propType)}}`, - ); - - expect(paramTypeAnnotation.type).toBe('ObjectTypeAnnotation'); - invariant( - paramTypeAnnotation.type === 'ObjectTypeAnnotation', - '', - ); - - const {properties} = paramTypeAnnotation; - - expect(properties).not.toBe(null); - invariant(properties != null, ''); - - expect(properties.length).toBe(1); - expect(properties[0].name).toBe(propName); - expect(properties[0].optional).toBe(isPropOptional); - - const [propertyTypeAnnotation, isPropertyTypeAnnotationNullable] = - unwrapNullable(properties[0].typeAnnotation); - - expect(propertyTypeAnnotation).not.toBe(null); - expect(isPropertyTypeAnnotationNullable).toBe(isPropNullable); - - return [ - { - ...properties[0], - typeAnnotation: propertyTypeAnnotation, - }, - module, - ]; - } - - describe( - (isPropNullable && isPropOptional - ? 'Nullable and Optional' - : isPropNullable - ? 'Nullable' - : isPropOptional - ? 'Optional' - : 'Required') + ' Property', - () => { - describe('Props with Primitive Types', () => { - PRIMITIVES.forEach(([FLOW_TYPE, PARSED_TYPE_NAME]) => { - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of primitive type '${FLOW_TYPE}'`, () => { - const [prop] = parseParamTypeObjectLiteralProp( - 'prop', - FLOW_TYPE, - ); - expect(prop.typeAnnotation.type).toBe(PARSED_TYPE_NAME); - }); - }); - }); - - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Object'`, () => { - const [prop] = parseParamTypeObjectLiteralProp( - 'prop', - 'Object', - ); - expect(prop.typeAnnotation.type).toBe( - 'GenericObjectTypeAnnotation', - ); - }); - - describe('Props with Reserved Types', () => { - RESERVED_FUNCTION_VALUE_TYPE_NAME.forEach(FLOW_TYPE => { - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of reserved type '${FLOW_TYPE}'`, () => { - const [prop] = parseParamTypeObjectLiteralProp( - 'prop', - FLOW_TYPE, - ); - expect(prop.typeAnnotation.type).toBe( - 'ReservedTypeAnnotation', - ); - invariant( - prop.typeAnnotation.type === 'ReservedTypeAnnotation', - '', - ); - - expect(prop.typeAnnotation.name).toBe(FLOW_TYPE); - }); - }); - }); - - describe('Props with Array Types', () => { - it(`should not parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Array`, () => { - expect(() => - parseParamTypeObjectLiteralProp('prop', 'Array'), - ).toThrow(MissingTypeParameterGenericParserError); - }); - - function parseArrayElementType( - propName: string, - arrayElementType: string, - ): [NativeModuleBaseTypeAnnotation, NativeModuleSchema] { - const [property, module] = parseParamTypeObjectLiteralProp( - 'propName', - `Array<${arrayElementType}>`, - ); - expect(property.typeAnnotation.type).toBe( - 'ArrayTypeAnnotation', - ); - invariant( - property.typeAnnotation.type === 'ArrayTypeAnnotation', - '', - ); - - const {elementType: nullableElementType} = - property.typeAnnotation; - expect(nullableElementType).not.toBe(null); - invariant(nullableElementType != null, ''); - - const [elementType, isElementTypeNullable] = - unwrapNullable( - nullableElementType, - ); - - expect(isElementTypeNullable).toBe(false); - - return [elementType, module]; - } - - PRIMITIVES.forEach(([FLOW_TYPE, PARSED_TYPE_NAME]) => { - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Array<${FLOW_TYPE}>'`, () => { - const [elementType] = parseArrayElementType( - 'prop', - FLOW_TYPE, - ); - - expect(elementType.type).toBe(PARSED_TYPE_NAME); - }); - }); - - RESERVED_FUNCTION_VALUE_TYPE_NAME.forEach(FLOW_TYPE => { - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Array<${FLOW_TYPE}>'`, () => { - const [elementType] = parseArrayElementType( - 'prop', - FLOW_TYPE, - ); - - expect(elementType.type).toBe('ReservedTypeAnnotation'); - invariant( - elementType.type === 'ReservedTypeAnnotation', - '', - ); - expect(elementType.name).toBe(FLOW_TYPE); - }); - }); - - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Array'`, () => { - const [elementType] = parseArrayElementType( - 'prop', - 'Object', - ); - expect(elementType.type).toBe( - 'GenericObjectTypeAnnotation', - ); - }); - - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type of some array of an alias`, () => { - const [elementType, module] = parseArrayElementType( - 'prop', - 'Animal', - ); - - expect(elementType.type).toBe('TypeAliasTypeAnnotation'); - invariant( - elementType.type === 'TypeAliasTypeAnnotation', - '', - ); - - expect(elementType.name).toBe('Animal'); - expectAnimalTypeAliasToExist(module); - }); - - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of 'Array<{foo: ?string}>'`, () => { - const [elementType] = parseArrayElementType( - 'prop', - '{foo: ?string}', - ); - - expect(elementType.type).toBe('ObjectTypeAnnotation'); - invariant(elementType.type === 'ObjectTypeAnnotation', ''); - - const {properties} = elementType; - expect(properties).not.toBe(null); - invariant(properties != null, ''); - - expect(properties[0]).not.toBe(null); - expect(properties[0].name).toBe('foo'); - expect(properties[0].typeAnnotation).not.toBe(null); - - const [ - propertyTypeAnnotation, - isPropertyTypeAnnotationNullable, - ] = unwrapNullable(properties[0].typeAnnotation); - - expect(propertyTypeAnnotation.type).toBe( - 'StringTypeAnnotation', - ); - expect(isPropertyTypeAnnotationNullable).toBe(true); - expect(properties[0].optional).toBe(false); - }); - }); - - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type '{foo: ?string}'`, () => { - const [property] = parseParamTypeObjectLiteralProp( - 'prop', - '{foo: ?string}', - ); - - expect(property.typeAnnotation.type).toBe( - 'ObjectTypeAnnotation', - ); - invariant( - property.typeAnnotation.type === 'ObjectTypeAnnotation', - '', - ); - - const {properties} = property.typeAnnotation; - expect(properties).not.toBe(null); - invariant(properties != null, ''); - - expect(properties[0]).not.toBe(null); - expect(properties[0].name).toBe('foo'); - - const [ - propertyTypeAnnotation, - isPropertyTypeAnnotationNullable, - ] = unwrapNullable(properties[0].typeAnnotation); - - expect(propertyTypeAnnotation.type).toBe( - 'StringTypeAnnotation', - ); - expect(isPropertyTypeAnnotationNullable).toBe(true); - expect(properties[0].optional).toBe(false); - }); - - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of some type alias`, () => { - const [property, module] = parseParamTypeObjectLiteralProp( - 'prop', - 'Animal', - ); - - expect(property.typeAnnotation.type).toBe( - 'TypeAliasTypeAnnotation', - ); - invariant( - property.typeAnnotation.type === 'TypeAliasTypeAnnotation', - '', - ); - - expect(property.typeAnnotation.name).toBe('Animal'); - expectAnimalTypeAliasToExist(module); - }); - }, - ); - }); - }, - ); - }); - }); - - describe('Return Parsing', () => { - it('should parse methods that have a return type of void', () => { - const module = parseModule(` - import type {TurboModule} from 'RCTExport'; - import * as TurboModuleRegistry from 'TurboModuleRegistry'; - export interface Spec extends TurboModule { - +useArg(): void; - } - export default TurboModuleRegistry.get('Foo'); - `); - - expect(module.spec.properties[0]).not.toBe(null); - - const [functionTypeAnnotation, isFunctionTypeAnnotationNullable] = - unwrapNullable(module.spec.properties[0].typeAnnotation); - expect(isFunctionTypeAnnotationNullable).toBe(false); - - const [returnTypeAnnotation, isReturnTypeAnnotationNullable] = - unwrapNullable(functionTypeAnnotation.returnTypeAnnotation); - expect(returnTypeAnnotation.type).toBe('VoidTypeAnnotation'); - expect(isReturnTypeAnnotationNullable).toBe(false); - }); - - [true, false].forEach(IS_RETURN_TYPE_NULLABLE => { - const RETURN_TYPE_DESCRIPTION = IS_RETURN_TYPE_NULLABLE - ? 'a nullable' - : 'a non-nullable'; - const annotateRet = (retType: string) => - IS_RETURN_TYPE_NULLABLE ? `?${retType}` : retType; - - function parseReturnType( - flowType: string, - ): [NativeModuleReturnTypeAnnotation, NativeModuleSchema] { - const module = parseModule(` - import type {TurboModule} from 'RCTExport'; - import * as TurboModuleRegistry from 'TurboModuleRegistry'; - - ${TYPE_ALIAS_DECLARATIONS} - - export interface Spec extends TurboModule { - +useArg(): ${annotateRet(flowType)}; - } - export default TurboModuleRegistry.get('Foo'); - `); - - expect(module.spec.properties[0]).not.toBe(null); - const [functionTypeAnnotation, isFunctionTypeAnnotationNullable] = - unwrapNullable(module.spec.properties[0].typeAnnotation); - expect(isFunctionTypeAnnotationNullable).toBe(false); - - const [returnTypeAnnotation, isReturnTypeAnnotationNullable] = - unwrapNullable(functionTypeAnnotation.returnTypeAnnotation); - expect(isReturnTypeAnnotationNullable).toBe(IS_RETURN_TYPE_NULLABLE); - - return [returnTypeAnnotation, module]; - } - - describe( - IS_RETURN_TYPE_NULLABLE ? 'Nullable Returns' : 'Non-Nullable Returns', - () => { - ['Promise', 'Promise<{}>', 'Promise<*>'].forEach( - promiseFlowType => { - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return of type '${promiseFlowType}'`, () => { - const [returnTypeAnnotation] = parseReturnType(promiseFlowType); - expect(returnTypeAnnotation.type).toBe('PromiseTypeAnnotation'); - }); - }, - ); - - describe('Primitive Types', () => { - PRIMITIVES.forEach(([FLOW_TYPE, PARSED_TYPE_NAME]) => { - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} primitive return of type '${FLOW_TYPE}'`, () => { - const [returnTypeAnnotation] = parseReturnType(FLOW_TYPE); - expect(returnTypeAnnotation.type).toBe(PARSED_TYPE_NAME); - }); - }); - }); - - describe('Reserved Types', () => { - RESERVED_FUNCTION_VALUE_TYPE_NAME.forEach(FLOW_TYPE => { - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} reserved return of type '${FLOW_TYPE}'`, () => { - const [returnTypeAnnotation] = parseReturnType(FLOW_TYPE); - expect(returnTypeAnnotation.type).toBe( - 'ReservedTypeAnnotation', - ); - invariant( - returnTypeAnnotation.type === 'ReservedTypeAnnotation', - '', - ); - expect(returnTypeAnnotation.name).toBe(FLOW_TYPE); - }); - }); - }); - - describe('Array Types', () => { - it(`should not parse methods that have ${RETURN_TYPE_DESCRIPTION} return of type 'Array'`, () => { - expect(() => parseReturnType('Array')).toThrow( - MissingTypeParameterGenericParserError, - ); - }); - - function parseArrayElementReturnType( - flowType: string, - ): [NativeModuleBaseTypeAnnotation, NativeModuleSchema] { - const [returnTypeAnnotation, module] = parseReturnType( - 'Array' + (flowType != null ? `<${flowType}>` : ''), - ); - expect(returnTypeAnnotation.type).toBe('ArrayTypeAnnotation'); - invariant( - returnTypeAnnotation.type === 'ArrayTypeAnnotation', - '', - ); - - const arrayTypeAnnotation = returnTypeAnnotation; - - const {elementType} = arrayTypeAnnotation; - expect(elementType).not.toBe(null); - invariant(elementType != null, ''); - - const [elementTypeAnnotation, isElementTypeAnnotation] = - unwrapNullable(elementType); - expect(isElementTypeAnnotation).toBe(false); - - return [elementTypeAnnotation, module]; - } - - // TODO: Do we support nullable element types? - - describe('Primitive Element Types', () => { - PRIMITIVES.forEach(([FLOW_TYPE, PARSED_TYPE_NAME]) => { - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return of type 'Array<${FLOW_TYPE}>'`, () => { - const [elementType] = parseArrayElementReturnType(FLOW_TYPE); - expect(elementType.type).toBe(PARSED_TYPE_NAME); - }); - }); - }); - - describe('Reserved Element Types', () => { - RESERVED_FUNCTION_VALUE_TYPE_NAME.forEach(FLOW_TYPE => { - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return of type 'Array<${FLOW_TYPE}>'`, () => { - const [elementType] = parseArrayElementReturnType(FLOW_TYPE); - expect(elementType.type).toBe('ReservedTypeAnnotation'); - invariant(elementType.type === 'ReservedTypeAnnotation', ''); - - expect(elementType.name).toBe(FLOW_TYPE); - }); - }); - }); - - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return of type 'Array'`, () => { - const [elementType] = parseArrayElementReturnType('Object'); - expect(elementType.type).toBe('GenericObjectTypeAnnotation'); - }); - - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of some array of an alias`, () => { - const [elementType, module] = - parseArrayElementReturnType('Animal'); - expect(elementType.type).toBe('TypeAliasTypeAnnotation'); - invariant(elementType.type === 'TypeAliasTypeAnnotation', ''); - expect(elementType.name).toBe('Animal'); - expectAnimalTypeAliasToExist(module); - }); - - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return of type 'Array<{foo: ?string}>'`, () => { - const [elementType] = - parseArrayElementReturnType('{foo: ?string}'); - expect(elementType.type).toBe('ObjectTypeAnnotation'); - invariant(elementType.type === 'ObjectTypeAnnotation', ''); - - const {properties} = elementType; - expect(properties).not.toBe(null); - invariant(properties != null, ''); - - expect(properties[0]).not.toBe(null); - expect(properties[0].name).toBe('foo'); - expect(properties[0].typeAnnotation).not.toBe(null); - - const [propertyTypeAnnotation, isPropertyTypeAnnotationNullable] = - unwrapNullable(properties[0].typeAnnotation); - - expect(propertyTypeAnnotation.type).toBe('StringTypeAnnotation'); - expect(isPropertyTypeAnnotationNullable).toBe(true); - expect(properties[0].optional).toBe(false); - }); - }); - - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of some type alias`, () => { - const [returnTypeAnnotation, module] = parseReturnType('Animal'); - expect(returnTypeAnnotation.type).toBe('TypeAliasTypeAnnotation'); - invariant( - returnTypeAnnotation.type === 'TypeAliasTypeAnnotation', - '', - ); - expect(returnTypeAnnotation.name).toBe('Animal'); - expectAnimalTypeAliasToExist(module); - }); - - it(`should not parse methods that have ${RETURN_TYPE_DESCRIPTION} return of type 'Function'`, () => { - expect(() => parseReturnType('Function')).toThrow( - UnsupportedGenericParserError, - ); - }); - - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return of type 'Object'`, () => { - const [returnTypeAnnotation] = parseReturnType('Object'); - expect(returnTypeAnnotation.type).toBe( - 'GenericObjectTypeAnnotation', - ); - }); - - describe('Object Literals Types', () => { - // TODO: Inexact vs exact object literals? - - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an empty object literal`, () => { - const [returnTypeAnnotation] = parseReturnType('{}'); - expect(returnTypeAnnotation.type).toBe('ObjectTypeAnnotation'); - invariant( - returnTypeAnnotation.type === 'ObjectTypeAnnotation', - '', - ); - - // Validate properties of object literal - expect(returnTypeAnnotation.properties).not.toBe(null); - expect(returnTypeAnnotation.properties?.length).toBe(0); - }); - - [ - {nullable: false, optional: false}, - {nullable: false, optional: true}, - {nullable: true, optional: false}, - {nullable: true, optional: true}, - ].forEach(({nullable, optional}) => { - const PROP_TYPE_DESCRIPTION = - nullable && optional - ? 'a nullable and optional' - : nullable - ? 'a nullable' - : optional - ? 'an optional' - : 'a required'; - - function annotateProp(propName: string, propType: string) { - if (nullable && optional) { - return `${propName}?: ?${propType}`; - } - if (nullable) { - return `${propName}: ?${propType}`; - } - if (optional) { - return `${propName}?: ${propType}`; - } - return `${propName}: ${propType}`; - } - - function parseObjectLiteralReturnTypeProp( - propName: string, - propType: string, - ): [ - $ReadOnly<{ - name: string, - optional: boolean, - typeAnnotation: NativeModuleBaseTypeAnnotation, - }>, - NativeModuleSchema, - ] { - const [returnTypeAnnotation, module] = parseReturnType( - `{${annotateProp(propName, propType)}}`, - ); - expect(returnTypeAnnotation.type).toBe('ObjectTypeAnnotation'); - invariant( - returnTypeAnnotation.type === 'ObjectTypeAnnotation', - '', - ); - - const properties = returnTypeAnnotation.properties; - expect(properties).not.toBe(null); - invariant(properties != null, ''); - - expect(properties.length).toBe(1); - - // Validate property - const property = properties[0]; - expect(property.name).toBe(propName); - expect(property.optional).toBe(optional); - - const [ - propertyTypeAnnotation, - isPropertyTypeAnnotationNullable, - ] = unwrapNullable(property.typeAnnotation); - - expect(propertyTypeAnnotation).not.toBe(null); - expect(isPropertyTypeAnnotationNullable).toBe(nullable); - return [ - { - ...property, - typeAnnotation: propertyTypeAnnotation, - }, - module, - ]; - } - - describe( - (nullable && optional - ? 'Nullable and Optional' - : nullable - ? 'Nullable' - : optional - ? 'Optional' - : 'Required') + ' Property', - () => { - /** - * TODO: Fill out props in promise - */ - - describe('Props with Primitive Types', () => { - PRIMITIVES.forEach(([FLOW_TYPE, PARSED_TYPE_NAME]) => { - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of primitive type '${FLOW_TYPE}'`, () => { - const [property] = parseObjectLiteralReturnTypeProp( - 'prop', - FLOW_TYPE, - ); - expect(property.typeAnnotation.type).toBe( - PARSED_TYPE_NAME, - ); - }); - }); - }); - - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Object'`, () => { - const [property] = parseObjectLiteralReturnTypeProp( - 'prop', - 'Object', - ); - - expect(property.typeAnnotation.type).toBe( - 'GenericObjectTypeAnnotation', - ); - }); - - describe('Props with Reserved Types', () => { - RESERVED_FUNCTION_VALUE_TYPE_NAME.forEach(FLOW_TYPE => { - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of reserved type '${FLOW_TYPE}'`, () => { - const [property] = parseObjectLiteralReturnTypeProp( - 'prop', - FLOW_TYPE, - ); - - expect(property.typeAnnotation.type).toBe( - 'ReservedTypeAnnotation', - ); - invariant( - property.typeAnnotation.type === - 'ReservedTypeAnnotation', - '', - ); - - expect(property.typeAnnotation.name).toBe(FLOW_TYPE); - }); - }); - }); - - describe('Props with Array Types', () => { - it(`should not parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Array`, () => { - expect(() => - parseObjectLiteralReturnTypeProp('prop', 'Array'), - ).toThrow(MissingTypeParameterGenericParserError); - }); - - function parseArrayElementType( - propName: string, - arrayElementType: string, - ): [NativeModuleBaseTypeAnnotation, NativeModuleSchema] { - const [property, module] = - parseObjectLiteralReturnTypeProp( - propName, - `Array<${arrayElementType}>`, - ); - expect(property.name).toBe(propName); - expect(property.typeAnnotation.type).toBe( - 'ArrayTypeAnnotation', - ); - invariant( - property.typeAnnotation.type === 'ArrayTypeAnnotation', - '', - ); - - const {elementType: nullableElementType} = - property.typeAnnotation; - expect(nullableElementType).not.toBe(null); - invariant(nullableElementType != null, ''); - - const [elementType, isElementTypeNullable] = - unwrapNullable( - nullableElementType, - ); - expect(isElementTypeNullable).toBe(false); - - return [elementType, module]; - } - - PRIMITIVES.forEach(([FLOW_TYPE, PARSED_TYPE_NAME]) => { - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Array<${FLOW_TYPE}>'`, () => { - const [elementType] = parseArrayElementType( - 'prop', - FLOW_TYPE, - ); - expect(elementType.type).toBe(PARSED_TYPE_NAME); - }); - }); - - RESERVED_FUNCTION_VALUE_TYPE_NAME.forEach(FLOW_TYPE => { - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Array<${FLOW_TYPE}>'`, () => { - const [elementType] = parseArrayElementType( - 'prop', - FLOW_TYPE, - ); - expect(elementType.type).toBe('ReservedTypeAnnotation'); - invariant( - elementType.type === 'ReservedTypeAnnotation', - '', - ); - - expect(elementType.name).toBe(FLOW_TYPE); - }); - }); - - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Array'`, () => { - const [elementType] = parseArrayElementType( - 'prop', - 'Object', - ); - expect(elementType).not.toBe(null); - expect(elementType.type).toBe( - 'GenericObjectTypeAnnotation', - ); - }); - - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type of some array of an aliase`, () => { - const [elementType, module] = parseArrayElementType( - 'prop', - 'Animal', - ); - expect(elementType.type).toBe('TypeAliasTypeAnnotation'); - invariant( - elementType.type === 'TypeAliasTypeAnnotation', - '', - ); - expect(elementType.name).toBe('Animal'); - expectAnimalTypeAliasToExist(module); - }); - - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Array<{foo: ?string}>'`, () => { - const [elementType] = parseArrayElementType( - 'prop', - '{foo: ?string}', - ); - expect(elementType.type).toBe('ObjectTypeAnnotation'); - invariant( - elementType.type === 'ObjectTypeAnnotation', - '', - ); - - const {properties} = elementType; - invariant(properties != null, ''); - expect(properties).not.toBe(null); - expect(properties[0]).not.toBe(null); - expect(properties[0].name).toBe('foo'); - expect(properties[0].optional).toBe(false); - - const [ - propertyTypeAnnotation, - isPropertyTypeAnnotationNullable, - ] = unwrapNullable(properties[0].typeAnnotation); - - expect(propertyTypeAnnotation.type).toBe( - 'StringTypeAnnotation', - ); - expect(isPropertyTypeAnnotationNullable).toBe(true); - }); - }); - - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of '{foo: ?string}'`, () => { - const [property] = parseObjectLiteralReturnTypeProp( - 'prop', - '{foo: ?string}', - ); - - expect(property.typeAnnotation.type).toBe( - 'ObjectTypeAnnotation', - ); - invariant( - property.typeAnnotation.type === 'ObjectTypeAnnotation', - '', - ); - - const {properties} = property.typeAnnotation; - - expect(properties).not.toBe(null); - invariant(properties != null, ''); - - expect(properties[0]).not.toBe(null); - expect(properties[0].name).toBe('foo'); - expect(properties[0].optional).toBe(false); - - const [ - propertyTypeAnnotation, - isPropertyTypeAnnotationNullable, - ] = unwrapNullable(properties[0].typeAnnotation); - - expect(propertyTypeAnnotation.type).toBe( - 'StringTypeAnnotation', - ); - expect(isPropertyTypeAnnotationNullable).toBe(true); - }); - - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of some type alias`, () => { - const [property, module] = parseObjectLiteralReturnTypeProp( - 'prop', - 'Animal', - ); - - expect(property.typeAnnotation.type).toBe( - 'TypeAliasTypeAnnotation', - ); - invariant( - property.typeAnnotation.type === - 'TypeAliasTypeAnnotation', - '', - ); - - expect(property.typeAnnotation.name).toBe('Animal'); - expectAnimalTypeAliasToExist(module); - }); - }, - ); - }); - }); - }, - ); - }); - }); -}); - -function parseModule(source: string) { - const schema = parseString(source, `${MODULE_NAME}.js`); - const module = schema.modules.NativeFoo; - invariant( - module.type === 'NativeModule', - "'nativeModules' in Spec NativeFoo shouldn't be null", - ); - return module; -} diff --git a/packages/react-native-codegen/src/parsers/flow/modules/__tests__/module-parser-snapshot-test.js b/packages/react-native-codegen/src/parsers/flow/modules/__tests__/module-parser-snapshot-test.js deleted file mode 100644 index f260240b7fda..000000000000 --- a/packages/react-native-codegen/src/parsers/flow/modules/__tests__/module-parser-snapshot-test.js +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const FlowParser = require('../../index.js'); - -const fixtures = require('../__test_fixtures__/fixtures.js'); -const failureFixtures = require('../__test_fixtures__/failures.js'); - -jest.mock('fs', () => ({ - readFileSync: filename => { - // Jest in the OSS does not allow to capture variables in closures. - // Therefore, we have to bring the variables inside the closure. - // see: https://github.com/facebook/jest/issues/2567 - const readFileFixtures = require('../__test_fixtures__/fixtures.js'); - const readFileFailureFixtures = require('../__test_fixtures__/failures.js'); - return readFileFixtures[filename] || readFileFailureFixtures[filename]; - }, -})); - -describe('RN Codegen Flow Parser', () => { - Object.keys(fixtures) - .sort() - .forEach(fixtureName => { - it(`can generate fixture ${fixtureName}`, () => { - const schema = FlowParser.parseModuleFixture(fixtureName); - const serializedSchema = JSON.stringify(schema, null, 2).replace( - /"/g, - "'", - ); - - expect(serializedSchema).toMatchSnapshot(); - }); - }); - - Object.keys(failureFixtures) - .sort() - .forEach(fixtureName => { - it(`Fails with error message ${fixtureName}`, () => { - expect(() => { - FlowParser.parseModuleFixture(fixtureName); - }).toThrowErrorMatchingSnapshot(); - }); - }); -}); diff --git a/packages/react-native-codegen/src/parsers/flow/modules/index.js b/packages/react-native-codegen/src/parsers/flow/modules/index.js deleted file mode 100644 index cd6e2f3e4401..000000000000 --- a/packages/react-native-codegen/src/parsers/flow/modules/index.js +++ /dev/null @@ -1,691 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type { - NamedShape, - NativeModuleAliasMap, - NativeModuleArrayTypeAnnotation, - NativeModuleBaseTypeAnnotation, - NativeModuleFunctionTypeAnnotation, - NativeModuleParamTypeAnnotation, - NativeModulePropertyShape, - NativeModuleSchema, - Nullable, -} from '../../../CodegenSchema.js'; - -import type {ParserErrorCapturer, TypeDeclarationMap} from '../../utils'; -import type {NativeModuleTypeAnnotation} from '../../../CodegenSchema.js'; -const {nullGuard} = require('../../parsers-utils'); - -const {throwIfMoreThanOneModuleRegistryCalls} = require('../../error-utils'); -const {visit, isModuleRegistryCall} = require('../../utils'); -const {resolveTypeAnnotation, getTypes} = require('../utils.js'); -const { - unwrapNullable, - wrapNullable, - assertGenericTypeAnnotationHasExactlyOneTypeParameter, - emitMixedTypeAnnotation, - emitUnionTypeAnnotation, - translateDefault, -} = require('../../parsers-commons'); -const { - emitBoolean, - emitDouble, - emitFloat, - emitFunction, - emitNumber, - emitInt32, - emitObject, - emitPromise, - emitRootTag, - emitVoid, - emitString, - emitStringish, - typeAliasResolution, -} = require('../../parsers-primitives'); - -const { - UnnamedFunctionParamParserError, - UnsupportedArrayElementTypeAnnotationParserError, - UnsupportedTypeAnnotationParserError, - UnsupportedObjectPropertyTypeAnnotationParserError, - IncorrectModuleRegistryCallArgumentTypeParserError, -} = require('../../errors.js'); - -const {verifyPlatforms} = require('../../utils'); - -const { - throwIfUnsupportedFunctionReturnTypeAnnotationParserError, - throwIfModuleInterfaceNotFound, - throwIfModuleInterfaceIsMisnamed, - throwIfPropertyValueTypeIsUnsupported, - throwIfUnusedModuleInterfaceParserError, - throwIfWrongNumberOfCallExpressionArgs, - throwIfIncorrectModuleRegistryCallTypeParameterParserError, - throwIfUntypedModule, - throwIfModuleTypeIsUnsupported, - throwIfMoreThanOneModuleInterfaceParserError, - throwIfUnsupportedFunctionParamTypeAnnotationParserError, -} = require('../../error-utils'); - -const {FlowParser} = require('../parser.js'); -const {getKeyName} = require('../../parsers-commons'); - -const language = 'Flow'; -const parser = new FlowParser(); - -function translateArrayTypeAnnotation( - hasteModuleName: string, - types: TypeDeclarationMap, - aliasMap: {...NativeModuleAliasMap}, - cxxOnly: boolean, - flowArrayType: 'Array' | '$ReadOnlyArray', - flowElementType: $FlowFixMe, - nullable: boolean, -): Nullable { - try { - /** - * TODO(T72031674): Migrate all our NativeModule specs to not use - * invalid Array ElementTypes. Then, make the elementType a required - * parameter. - */ - const [elementType, isElementTypeNullable] = unwrapNullable( - translateTypeAnnotation( - hasteModuleName, - flowElementType, - types, - aliasMap, - /** - * TODO(T72031674): Ensure that all ParsingErrors that are thrown - * while parsing the array element don't get captured and collected. - * Why? If we detect any parsing error while parsing the element, - * we should default it to null down the line, here. This is - * the correct behaviour until we migrate all our NativeModule specs - * to be parseable. - */ - nullGuard, - cxxOnly, - ), - ); - - if (elementType.type === 'VoidTypeAnnotation') { - throw new UnsupportedArrayElementTypeAnnotationParserError( - hasteModuleName, - flowElementType, - flowArrayType, - 'void', - language, - ); - } - - if (elementType.type === 'PromiseTypeAnnotation') { - throw new UnsupportedArrayElementTypeAnnotationParserError( - hasteModuleName, - flowElementType, - flowArrayType, - 'Promise', - language, - ); - } - - if (elementType.type === 'FunctionTypeAnnotation') { - throw new UnsupportedArrayElementTypeAnnotationParserError( - hasteModuleName, - flowElementType, - flowArrayType, - 'FunctionTypeAnnotation', - language, - ); - } - - const finalTypeAnnotation: NativeModuleArrayTypeAnnotation< - Nullable, - > = { - type: 'ArrayTypeAnnotation', - elementType: wrapNullable(isElementTypeNullable, elementType), - }; - - return wrapNullable(nullable, finalTypeAnnotation); - } catch (ex) { - return wrapNullable(nullable, { - type: 'ArrayTypeAnnotation', - }); - } -} - -function translateTypeAnnotation( - hasteModuleName: string, - /** - * TODO(T71778680): Flow-type this node. - */ - flowTypeAnnotation: $FlowFixMe, - types: TypeDeclarationMap, - aliasMap: {...NativeModuleAliasMap}, - tryParse: ParserErrorCapturer, - cxxOnly: boolean, -): Nullable { - const {nullable, typeAnnotation, typeAliasResolutionStatus} = - resolveTypeAnnotation(flowTypeAnnotation, types); - - switch (typeAnnotation.type) { - case 'GenericTypeAnnotation': { - switch (typeAnnotation.id.name) { - case 'RootTag': { - return emitRootTag(nullable); - } - case 'Promise': { - return emitPromise( - hasteModuleName, - typeAnnotation, - language, - nullable, - ); - } - case 'Array': - case '$ReadOnlyArray': { - assertGenericTypeAnnotationHasExactlyOneTypeParameter( - hasteModuleName, - typeAnnotation, - language, - ); - - return translateArrayTypeAnnotation( - hasteModuleName, - types, - aliasMap, - cxxOnly, - typeAnnotation.type, - typeAnnotation.typeParameters.params[0], - nullable, - ); - } - case '$ReadOnly': { - assertGenericTypeAnnotationHasExactlyOneTypeParameter( - hasteModuleName, - typeAnnotation, - language, - ); - - const [paramType, isParamNullable] = unwrapNullable( - translateTypeAnnotation( - hasteModuleName, - typeAnnotation.typeParameters.params[0], - types, - aliasMap, - tryParse, - cxxOnly, - ), - ); - - return wrapNullable(nullable || isParamNullable, paramType); - } - case 'Stringish': { - return emitStringish(nullable); - } - case 'Int32': { - return emitInt32(nullable); - } - case 'Double': { - return emitDouble(nullable); - } - case 'Float': { - return emitFloat(nullable); - } - case 'UnsafeObject': - case 'Object': { - return emitObject(nullable); - } - default: { - return translateDefault( - hasteModuleName, - typeAnnotation, - types, - nullable, - parser, - ); - } - } - } - case 'ObjectTypeAnnotation': { - const objectTypeAnnotation = { - type: 'ObjectTypeAnnotation', - // $FlowFixMe[missing-type-arg] - properties: ([ - ...typeAnnotation.properties, - ...typeAnnotation.indexers, - ]: Array<$FlowFixMe>) - .map>>( - property => { - return tryParse(() => { - if ( - property.type !== 'ObjectTypeProperty' && - property.type !== 'ObjectTypeIndexer' - ) { - throw new UnsupportedObjectPropertyTypeAnnotationParserError( - hasteModuleName, - property, - property.type, - language, - ); - } - - const {optional = false} = property; - const name = getKeyName(property, hasteModuleName, language); - if (property.type === 'ObjectTypeIndexer') { - return { - name, - optional, - typeAnnotation: emitObject(nullable), - }; - } - const [propertyTypeAnnotation, isPropertyNullable] = - unwrapNullable( - translateTypeAnnotation( - hasteModuleName, - property.value, - types, - aliasMap, - tryParse, - cxxOnly, - ), - ); - - if ( - propertyTypeAnnotation.type === 'FunctionTypeAnnotation' || - propertyTypeAnnotation.type === 'PromiseTypeAnnotation' || - propertyTypeAnnotation.type === 'VoidTypeAnnotation' - ) { - throwIfPropertyValueTypeIsUnsupported( - hasteModuleName, - property.value, - property.key, - propertyTypeAnnotation.type, - language, - ); - } else { - return { - name, - optional, - typeAnnotation: wrapNullable( - isPropertyNullable, - propertyTypeAnnotation, - ), - }; - } - }); - }, - ) - .filter(Boolean), - }; - - return typeAliasResolution( - typeAliasResolutionStatus, - objectTypeAnnotation, - aliasMap, - nullable, - ); - } - case 'BooleanTypeAnnotation': { - return emitBoolean(nullable); - } - case 'NumberTypeAnnotation': { - return emitNumber(nullable); - } - case 'VoidTypeAnnotation': { - return emitVoid(nullable); - } - case 'StringTypeAnnotation': { - return emitString(nullable); - } - case 'FunctionTypeAnnotation': { - const translateFunctionTypeAnnotationValue: NativeModuleFunctionTypeAnnotation = - translateFunctionTypeAnnotation( - hasteModuleName, - typeAnnotation, - types, - aliasMap, - tryParse, - cxxOnly, - ); - return emitFunction(nullable, translateFunctionTypeAnnotationValue); - } - case 'UnionTypeAnnotation': { - if (cxxOnly) { - return emitUnionTypeAnnotation( - nullable, - hasteModuleName, - typeAnnotation, - language, - ); - } - // Fallthrough - } - case 'MixedTypeAnnotation': { - if (cxxOnly) { - return emitMixedTypeAnnotation(nullable); - } - // Fallthrough - } - default: { - throw new UnsupportedTypeAnnotationParserError( - hasteModuleName, - typeAnnotation, - language, - ); - } - } -} - -function translateFunctionTypeAnnotation( - hasteModuleName: string, - // TODO(T71778680): This is a FunctionTypeAnnotation. Type this. - flowFunctionTypeAnnotation: $FlowFixMe, - types: TypeDeclarationMap, - aliasMap: {...NativeModuleAliasMap}, - tryParse: ParserErrorCapturer, - cxxOnly: boolean, -): NativeModuleFunctionTypeAnnotation { - type Param = NamedShape>; - const params: Array = []; - - for (const flowParam of (flowFunctionTypeAnnotation.params: $ReadOnlyArray<$FlowFixMe>)) { - const parsedParam = tryParse(() => { - if (flowParam.name == null) { - throw new UnnamedFunctionParamParserError( - flowParam, - hasteModuleName, - language, - ); - } - - const paramName = flowParam.name.name; - const [paramTypeAnnotation, isParamTypeAnnotationNullable] = - unwrapNullable( - translateTypeAnnotation( - hasteModuleName, - flowParam.typeAnnotation, - types, - aliasMap, - tryParse, - cxxOnly, - ), - ); - - if ( - paramTypeAnnotation.type === 'VoidTypeAnnotation' || - paramTypeAnnotation.type === 'PromiseTypeAnnotation' - ) { - return throwIfUnsupportedFunctionParamTypeAnnotationParserError( - hasteModuleName, - flowParam.typeAnnotation, - paramName, - paramTypeAnnotation.type, - ); - } - - return { - name: flowParam.name.name, - optional: flowParam.optional, - typeAnnotation: wrapNullable( - isParamTypeAnnotationNullable, - paramTypeAnnotation, - ), - }; - }); - - if (parsedParam != null) { - params.push(parsedParam); - } - } - - const [returnTypeAnnotation, isReturnTypeAnnotationNullable] = unwrapNullable( - translateTypeAnnotation( - hasteModuleName, - flowFunctionTypeAnnotation.returnType, - types, - aliasMap, - tryParse, - cxxOnly, - ), - ); - - throwIfUnsupportedFunctionReturnTypeAnnotationParserError( - hasteModuleName, - flowFunctionTypeAnnotation, - 'FunctionTypeAnnotation', - language, - cxxOnly, - returnTypeAnnotation.type, - ); - - return { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: wrapNullable( - isReturnTypeAnnotationNullable, - returnTypeAnnotation, - ), - params, - }; -} - -function buildPropertySchema( - hasteModuleName: string, - // TODO(T71778680): This is an ObjectTypeProperty containing either: - // - a FunctionTypeAnnotation or GenericTypeAnnotation - // - a NullableTypeAnnoation containing a FunctionTypeAnnotation or GenericTypeAnnotation - // Flow type this node - property: $FlowFixMe, - types: TypeDeclarationMap, - aliasMap: {...NativeModuleAliasMap}, - tryParse: ParserErrorCapturer, - cxxOnly: boolean, -): NativeModulePropertyShape { - let nullable = false; - let {key, value} = property; - - const methodName: string = key.name; - - ({nullable, typeAnnotation: value} = resolveTypeAnnotation(value, types)); - - throwIfModuleTypeIsUnsupported( - hasteModuleName, - property.value, - property.key.name, - value.type, - language, - ); - - return { - name: methodName, - optional: property.optional, - typeAnnotation: wrapNullable( - nullable, - translateFunctionTypeAnnotation( - hasteModuleName, - value, - types, - aliasMap, - tryParse, - cxxOnly, - ), - ), - }; -} - -function isModuleInterface(node: $FlowFixMe) { - return ( - node.type === 'InterfaceDeclaration' && - node.extends.length === 1 && - node.extends[0].type === 'InterfaceExtends' && - node.extends[0].id.name === 'TurboModule' - ); -} - -function buildModuleSchema( - hasteModuleName: string, - /** - * TODO(T71778680): Flow-type this node. - */ - ast: $FlowFixMe, - tryParse: ParserErrorCapturer, -): NativeModuleSchema { - const types = getTypes(ast); - const moduleSpecs = (Object.values(types): $ReadOnlyArray<$FlowFixMe>).filter( - isModuleInterface, - ); - - throwIfModuleInterfaceNotFound( - moduleSpecs.length, - hasteModuleName, - ast, - language, - ); - - throwIfMoreThanOneModuleInterfaceParserError( - hasteModuleName, - moduleSpecs, - language, - ); - - const [moduleSpec] = moduleSpecs; - - throwIfModuleInterfaceIsMisnamed(hasteModuleName, moduleSpec.id, language); - - // Parse Module Names - const moduleName = tryParse((): string => { - const callExpressions = []; - visit(ast, { - CallExpression(node) { - if (isModuleRegistryCall(node)) { - callExpressions.push(node); - } - }, - }); - - throwIfUnusedModuleInterfaceParserError( - hasteModuleName, - moduleSpec, - callExpressions, - language, - ); - - throwIfMoreThanOneModuleRegistryCalls( - hasteModuleName, - callExpressions, - callExpressions.length, - language, - ); - - const [callExpression] = callExpressions; - const {typeArguments} = callExpression; - const methodName = callExpression.callee.property.name; - - throwIfWrongNumberOfCallExpressionArgs( - hasteModuleName, - callExpression, - methodName, - callExpression.arguments.length, - language, - ); - - if (callExpression.arguments[0].type !== 'Literal') { - const {type} = callExpression.arguments[0]; - throw new IncorrectModuleRegistryCallArgumentTypeParserError( - hasteModuleName, - callExpression.arguments[0], - methodName, - type, - language, - ); - } - - const $moduleName = callExpression.arguments[0].value; - - throwIfUntypedModule( - typeArguments, - hasteModuleName, - callExpression, - methodName, - $moduleName, - language, - ); - - throwIfIncorrectModuleRegistryCallTypeParameterParserError( - hasteModuleName, - typeArguments, - methodName, - $moduleName, - language, - ); - - return $moduleName; - }); - - const moduleNames = moduleName == null ? [] : [moduleName]; - - // Some module names use platform suffix to indicate platform-exclusive modules. - // Eventually this should be made explicit in the Flow type itself. - // Also check the hasteModuleName for platform suffix. - // Note: this shape is consistent with ComponentSchema. - const {cxxOnly, excludedPlatforms} = verifyPlatforms( - hasteModuleName, - moduleNames, - ); - - // $FlowFixMe[missing-type-arg] - return (moduleSpec.body.properties: $ReadOnlyArray<$FlowFixMe>) - .filter(property => property.type === 'ObjectTypeProperty') - .map(property => { - const aliasMap: {...NativeModuleAliasMap} = {}; - - return tryParse(() => ({ - aliasMap: aliasMap, - propertyShape: buildPropertySchema( - hasteModuleName, - property, - types, - aliasMap, - tryParse, - cxxOnly, - ), - })); - }) - .filter(Boolean) - .reduce( - (moduleSchema: NativeModuleSchema, {aliasMap, propertyShape}) => { - return { - type: 'NativeModule', - aliases: {...moduleSchema.aliases, ...aliasMap}, - spec: { - properties: [...moduleSchema.spec.properties, propertyShape], - }, - moduleNames: moduleSchema.moduleNames, - excludedPlatforms: moduleSchema.excludedPlatforms, - }; - }, - { - type: 'NativeModule', - aliases: {}, - spec: {properties: []}, - moduleNames: moduleNames, - excludedPlatforms: - excludedPlatforms.length !== 0 ? [...excludedPlatforms] : undefined, - }, - ); -} - -module.exports = { - buildModuleSchema, -}; diff --git a/packages/react-native-codegen/src/parsers/flow/parser.js b/packages/react-native-codegen/src/parsers/flow/parser.js deleted file mode 100644 index 5315411ecf49..000000000000 --- a/packages/react-native-codegen/src/parsers/flow/parser.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type {ParserType} from '../errors'; -import type {Parser} from '../parser'; - -class FlowParser implements Parser { - getMaybeEnumMemberType(maybeEnumDeclaration: $FlowFixMe): string { - return maybeEnumDeclaration.body.type - .replace('EnumNumberBody', 'NumberTypeAnnotation') - .replace('EnumStringBody', 'StringTypeAnnotation'); - } - - isEnumDeclaration(maybeEnumDeclaration: $FlowFixMe): boolean { - return maybeEnumDeclaration.type === 'EnumDeclaration'; - } - - language(): ParserType { - return 'Flow'; - } - - nameForGenericTypeAnnotation(typeAnnotation: $FlowFixMe): string { - return typeAnnotation.id.name; - } -} - -module.exports = { - FlowParser, -}; diff --git a/packages/react-native-codegen/src/parsers/flow/utils.js b/packages/react-native-codegen/src/parsers/flow/utils.js deleted file mode 100644 index 86c663db5bd2..000000000000 --- a/packages/react-native-codegen/src/parsers/flow/utils.js +++ /dev/null @@ -1,123 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {TypeAliasResolutionStatus, TypeDeclarationMap} from '../utils'; - -/** - * This FlowFixMe is supposed to refer to an InterfaceDeclaration or TypeAlias - * declaration type. Unfortunately, we don't have those types, because flow-parser - * generates them, and flow-parser is not type-safe. In the future, we should find - * a way to get these types from our flow parser library. - * - * TODO(T71778680): Flow type AST Nodes - */ - -function getTypes(ast: $FlowFixMe): TypeDeclarationMap { - return ast.body.reduce((types, node) => { - if (node.type === 'ExportNamedDeclaration' && node.exportKind === 'type') { - if ( - node.declaration != null && - (node.declaration.type === 'TypeAlias' || - node.declaration.type === 'InterfaceDeclaration') - ) { - types[node.declaration.id.name] = node.declaration; - } - } else if ( - node.type === 'ExportNamedDeclaration' && - node.exportKind === 'value' && - node.declaration && - node.declaration.type === 'EnumDeclaration' - ) { - types[node.declaration.id.name] = node.declaration; - } else if ( - node.type === 'TypeAlias' || - node.type === 'InterfaceDeclaration' || - node.type === 'EnumDeclaration' - ) { - types[node.id.name] = node; - } - return types; - }, {}); -} - -// $FlowFixMe[unclear-type] there's no flowtype for ASTs -export type ASTNode = Object; - -const invariant = require('invariant'); - -function resolveTypeAnnotation( - // TODO(T71778680): This is an Flow TypeAnnotation. Flow-type this - typeAnnotation: $FlowFixMe, - types: TypeDeclarationMap, -): { - nullable: boolean, - typeAnnotation: $FlowFixMe, - typeAliasResolutionStatus: TypeAliasResolutionStatus, -} { - invariant( - typeAnnotation != null, - 'resolveTypeAnnotation(): typeAnnotation cannot be null', - ); - - let node = typeAnnotation; - let nullable = false; - let typeAliasResolutionStatus: TypeAliasResolutionStatus = { - successful: false, - }; - - for (;;) { - if (node.type === 'NullableTypeAnnotation') { - nullable = true; - node = node.typeAnnotation; - } else if (node.type === 'GenericTypeAnnotation') { - typeAliasResolutionStatus = { - successful: true, - aliasName: node.id.name, - }; - const resolvedTypeAnnotation = types[node.id.name]; - if ( - resolvedTypeAnnotation == null || - resolvedTypeAnnotation.type === 'EnumDeclaration' - ) { - break; - } - - invariant( - resolvedTypeAnnotation.type === 'TypeAlias', - `GenericTypeAnnotation '${node.id.name}' must resolve to a TypeAlias. Instead, it resolved to a '${resolvedTypeAnnotation.type}'`, - ); - - node = resolvedTypeAnnotation.right; - } else { - break; - } - } - - return { - nullable: nullable, - typeAnnotation: node, - typeAliasResolutionStatus, - }; -} - -function getValueFromTypes(value: ASTNode, types: TypeDeclarationMap): ASTNode { - if (value.type === 'GenericTypeAnnotation' && types[value.id.name]) { - return getValueFromTypes(types[value.id.name].right, types); - } - return value; -} - -module.exports = { - getValueFromTypes, - resolveTypeAnnotation, - getTypes, -}; diff --git a/packages/react-native-codegen/src/parsers/parser.js b/packages/react-native-codegen/src/parsers/parser.js deleted file mode 100644 index eec4faea60b7..000000000000 --- a/packages/react-native-codegen/src/parsers/parser.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type {ParserType} from './errors'; - -/** - * This is the main interface for Parsers of various languages. - * It exposes all the methods that contain language-specific logic. - */ -export interface Parser { - /** - * Given a type declaration, it possibly returns the name of the Enum type. - * @parameter maybeEnumDeclaration: an object possibly containing an Enum declaration. - * @returns: the name of the Enum type. - */ - getMaybeEnumMemberType(maybeEnumDeclaration: $FlowFixMe): string; - /** - * Given a type declaration, it returns a boolean specifying if is an Enum declaration. - * @parameter maybeEnumDeclaration: an object possibly containing an Enum declaration. - * @returns: a boolean specifying if is an Enum declaration. - */ - isEnumDeclaration(maybeEnumDeclaration: $FlowFixMe): boolean; - /** - * @returns: the Parser language. - */ - language(): ParserType; - /** - * Given a type annotation for a generic type, it returns the type name. - * @parameter typeAnnotation: the annotation for a type in the AST. - * @returns: the name of the type. - */ - nameForGenericTypeAnnotation(typeAnnotation: $FlowFixMe): string; -} diff --git a/packages/react-native-codegen/src/parsers/parsers-commons.js b/packages/react-native-codegen/src/parsers/parsers-commons.js deleted file mode 100644 index 28ac2725e264..000000000000 --- a/packages/react-native-codegen/src/parsers/parsers-commons.js +++ /dev/null @@ -1,240 +0,0 @@ -/** - * 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 - * @flow strict - */ - -'use strict'; - -import type { - SchemaType, - NativeModuleSchema, - NativeModuleTypeAnnotation, - Nullable, - NativeModuleMixedTypeAnnotation, - UnionTypeAnnotationMemberType, - NativeModuleUnionTypeAnnotation, -} from '../CodegenSchema.js'; -const { - MissingTypeParameterGenericParserError, - MoreThanOneTypeParameterGenericParserError, - UnsupportedUnionTypeAnnotationParserError, -} = require('./errors'); -import type {ParserType} from './errors'; -const { - UnsupportedObjectPropertyTypeAnnotationParserError, -} = require('./errors'); -const invariant = require('invariant'); -import type {TypeDeclarationMap} from './utils'; -const { - UnsupportedEnumDeclarationParserError, - UnsupportedGenericParserError, -} = require('./errors'); -import type {Parser} from './parser'; -import type {NativeModuleEnumDeclaration} from '../CodegenSchema'; - -function wrapModuleSchema( - nativeModuleSchema: NativeModuleSchema, - hasteModuleName: string, -): SchemaType { - return { - modules: { - [hasteModuleName]: nativeModuleSchema, - }, - }; -} - -function unwrapNullable<+T: NativeModuleTypeAnnotation>( - x: Nullable, -): [T, boolean] { - if (x.type === 'NullableTypeAnnotation') { - return [x.typeAnnotation, true]; - } - - return [x, false]; -} - -function wrapNullable<+T: NativeModuleTypeAnnotation>( - nullable: boolean, - typeAnnotation: T, -): Nullable { - if (!nullable) { - return typeAnnotation; - } - - return { - type: 'NullableTypeAnnotation', - typeAnnotation, - }; -} - -function assertGenericTypeAnnotationHasExactlyOneTypeParameter( - moduleName: string, - /** - * TODO(T108222691): Use flow-types for @babel/parser - */ - typeAnnotation: $FlowFixMe, - language: ParserType, -) { - if (typeAnnotation.typeParameters == null) { - throw new MissingTypeParameterGenericParserError( - moduleName, - typeAnnotation, - language, - ); - } - - const typeAnnotationType = - language === 'TypeScript' - ? 'TSTypeParameterInstantiation' - : 'TypeParameterInstantiation'; - - invariant( - typeAnnotation.typeParameters.type === typeAnnotationType, - `assertGenericTypeAnnotationHasExactlyOneTypeParameter: Type parameters must be an AST node of type '${typeAnnotationType}'`, - ); - - if (typeAnnotation.typeParameters.params.length !== 1) { - throw new MoreThanOneTypeParameterGenericParserError( - moduleName, - typeAnnotation, - language, - ); - } -} - -function emitMixedTypeAnnotation( - nullable: boolean, -): Nullable { - return wrapNullable(nullable, { - type: 'MixedTypeAnnotation', - }); -} - -function remapUnionTypeAnnotationMemberNames( - types: $FlowFixMe, - language: ParserType, -): UnionTypeAnnotationMemberType[] { - const remapLiteral = (item: $FlowFixMe) => { - if (language === 'Flow') { - return item.type - .replace('NumberLiteralTypeAnnotation', 'NumberTypeAnnotation') - .replace('StringLiteralTypeAnnotation', 'StringTypeAnnotation'); - } - - return item.literal - ? item.literal.type - .replace('NumericLiteral', 'NumberTypeAnnotation') - .replace('StringLiteral', 'StringTypeAnnotation') - : 'ObjectTypeAnnotation'; - }; - - return types - .map(remapLiteral) - .filter((value, index, self) => self.indexOf(value) === index); -} - -function emitUnionTypeAnnotation( - nullable: boolean, - hasteModuleName: string, - typeAnnotation: $FlowFixMe, - language: ParserType, -): Nullable { - const unionTypes = remapUnionTypeAnnotationMemberNames( - typeAnnotation.types, - language, - ); - - // Only support unionTypes of the same kind - if (unionTypes.length > 1) { - throw new UnsupportedUnionTypeAnnotationParserError( - hasteModuleName, - typeAnnotation, - unionTypes, - language, - ); - } - - return wrapNullable(nullable, { - type: 'UnionTypeAnnotation', - memberType: unionTypes[0], - }); -} - -function translateDefault( - hasteModuleName: string, - typeAnnotation: $FlowFixMe, - types: TypeDeclarationMap, - nullable: boolean, - parser: Parser, -): Nullable { - const maybeEnumDeclaration = - types[parser.nameForGenericTypeAnnotation(typeAnnotation)]; - - if (maybeEnumDeclaration && parser.isEnumDeclaration(maybeEnumDeclaration)) { - const memberType = parser.getMaybeEnumMemberType(maybeEnumDeclaration); - - if ( - memberType === 'NumberTypeAnnotation' || - memberType === 'StringTypeAnnotation' - ) { - return wrapNullable(nullable, { - type: 'EnumDeclaration', - memberType: memberType, - }); - } else { - throw new UnsupportedEnumDeclarationParserError( - hasteModuleName, - typeAnnotation, - memberType, - parser.language(), - ); - } - } - - throw new UnsupportedGenericParserError( - hasteModuleName, - typeAnnotation, - parser, - ); -} - -function getKeyName( - propertyOrIndex: $FlowFixMe, - hasteModuleName: string, - language: ParserType, -): string { - switch (propertyOrIndex.type) { - case 'ObjectTypeProperty': - case 'TSPropertySignature': - return propertyOrIndex.key.name; - case 'ObjectTypeIndexer': - // flow index name is optional - return propertyOrIndex.id?.name ?? 'key'; - case 'TSIndexSignature': - // TypeScript index name is mandatory - return propertyOrIndex.parameters[0].name; - default: - throw new UnsupportedObjectPropertyTypeAnnotationParserError( - hasteModuleName, - propertyOrIndex, - propertyOrIndex.type, - language, - ); - } -} - -module.exports = { - wrapModuleSchema, - unwrapNullable, - wrapNullable, - assertGenericTypeAnnotationHasExactlyOneTypeParameter, - emitMixedTypeAnnotation, - emitUnionTypeAnnotation, - getKeyName, - translateDefault, -}; diff --git a/packages/react-native-codegen/src/parsers/parsers-primitives.js b/packages/react-native-codegen/src/parsers/parsers-primitives.js deleted file mode 100644 index 1b450d044ee9..000000000000 --- a/packages/react-native-codegen/src/parsers/parsers-primitives.js +++ /dev/null @@ -1,197 +0,0 @@ -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -import type { - Nullable, - NativeModuleAliasMap, - NativeModuleBaseTypeAnnotation, - NativeModuleFunctionTypeAnnotation, - NativeModuleTypeAliasTypeAnnotation, - NativeModuleNumberTypeAnnotation, - BooleanTypeAnnotation, - DoubleTypeAnnotation, - Int32TypeAnnotation, - NativeModuleGenericObjectTypeAnnotation, - ReservedTypeAnnotation, - ObjectTypeAnnotation, - NativeModulePromiseTypeAnnotation, - StringTypeAnnotation, - VoidTypeAnnotation, - NativeModuleFloatTypeAnnotation, -} from '../CodegenSchema'; -import type {ParserType} from './errors'; -import type {TypeAliasResolutionStatus} from './utils'; - -const { - wrapNullable, - assertGenericTypeAnnotationHasExactlyOneTypeParameter, -} = require('./parsers-commons'); - -function emitBoolean(nullable: boolean): Nullable { - return wrapNullable(nullable, { - type: 'BooleanTypeAnnotation', - }); -} - -function emitInt32(nullable: boolean): Nullable { - return wrapNullable(nullable, { - type: 'Int32TypeAnnotation', - }); -} - -function emitNumber( - nullable: boolean, -): Nullable { - return wrapNullable(nullable, { - type: 'NumberTypeAnnotation', - }); -} - -function emitRootTag(nullable: boolean): Nullable { - return wrapNullable(nullable, { - type: 'ReservedTypeAnnotation', - name: 'RootTag', - }); -} - -function emitDouble(nullable: boolean): Nullable { - return wrapNullable(nullable, { - type: 'DoubleTypeAnnotation', - }); -} - -function emitVoid(nullable: boolean): Nullable { - return wrapNullable(nullable, { - type: 'VoidTypeAnnotation', - }); -} - -function emitStringish(nullable: boolean): Nullable { - return wrapNullable(nullable, { - type: 'StringTypeAnnotation', - }); -} -function emitFunction( - nullable: boolean, - translateFunctionTypeAnnotationValue: NativeModuleFunctionTypeAnnotation, -): Nullable { - return wrapNullable(nullable, translateFunctionTypeAnnotationValue); -} - -function emitString(nullable: boolean): Nullable { - return wrapNullable(nullable, { - type: 'StringTypeAnnotation', - }); -} - -function typeAliasResolution( - typeAliasResolutionStatus: TypeAliasResolutionStatus, - objectTypeAnnotation: ObjectTypeAnnotation< - Nullable, - >, - aliasMap: {...NativeModuleAliasMap}, - nullable: boolean, -): - | Nullable - | Nullable>> { - if (!typeAliasResolutionStatus.successful) { - return wrapNullable(nullable, objectTypeAnnotation); - } - - /** - * All aliases RHS are required. - */ - aliasMap[typeAliasResolutionStatus.aliasName] = objectTypeAnnotation; - - /** - * Nullability of type aliases is transitive. - * - * Consider this case: - * - * type Animal = ?{ - * name: string, - * }; - * - * type B = Animal - * - * export interface Spec extends TurboModule { - * +greet: (animal: B) => void; - * } - * - * In this case, we follow B to Animal, and then Animal to ?{name: string}. - * - * We: - * 1. Replace `+greet: (animal: B) => void;` with `+greet: (animal: ?Animal) => void;`, - * 2. Pretend that Animal = {name: string}. - * - * Why do we do this? - * 1. In ObjC, we need to generate a struct called Animal, not B. - * 2. This design is simpler than managing nullability within both the type alias usage, and the type alias RHS. - * 3. What does it mean for a C++ struct, which is what this type alias RHS will generate, to be nullable? ¯\_(ツ)_/¯ - * Nullability is a concept that only makes sense when talking about instances (i.e: usages) of the C++ structs. - * Hence, it's better to manage nullability within the actual TypeAliasTypeAnnotation nodes, and not the - * associated ObjectTypeAnnotations. - */ - return wrapNullable(nullable, { - type: 'TypeAliasTypeAnnotation', - name: typeAliasResolutionStatus.aliasName, - }); -} - -function emitPromise( - hasteModuleName: string, - typeAnnotation: $FlowFixMe, - language: ParserType, - nullable: boolean, -): Nullable { - assertGenericTypeAnnotationHasExactlyOneTypeParameter( - hasteModuleName, - typeAnnotation, - language, - ); - - return wrapNullable(nullable, { - type: 'PromiseTypeAnnotation', - }); -} - -function emitObject( - nullable: boolean, -): Nullable { - return wrapNullable(nullable, { - type: 'GenericObjectTypeAnnotation', - }); -} - -function emitFloat( - nullable: boolean, -): Nullable { - return wrapNullable(nullable, { - type: 'FloatTypeAnnotation', - }); -} - -module.exports = { - emitBoolean, - emitDouble, - emitFloat, - emitFunction, - emitInt32, - emitNumber, - emitObject, - emitPromise, - emitRootTag, - emitVoid, - emitString, - emitStringish, - typeAliasResolution, -}; diff --git a/packages/react-native-codegen/src/parsers/parsers-utils.js b/packages/react-native-codegen/src/parsers/parsers-utils.js deleted file mode 100644 index 696d308c990d..000000000000 --- a/packages/react-native-codegen/src/parsers/parsers-utils.js +++ /dev/null @@ -1,19 +0,0 @@ -/** - * 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 - * @flow strict - */ - -'use strict'; - -function nullGuard(fn: () => T): ?T { - return fn(); -} - -module.exports = { - nullGuard, -}; diff --git a/packages/react-native-codegen/src/parsers/schema/index.js b/packages/react-native-codegen/src/parsers/schema/index.js deleted file mode 100644 index 646aa86fcee8..000000000000 --- a/packages/react-native-codegen/src/parsers/schema/index.js +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {SchemaType} from '../../CodegenSchema.js'; - -function parse(filename: string): ?SchemaType { - try { - // $FlowFixMe[unsupported-syntax] Can't require dynamic variables - return require(filename); - } catch (err) { - // Ignore - } -} - -module.exports = { - parse, -}; diff --git a/packages/react-native-codegen/src/parsers/typescript/components/__test_fixtures__/failures.js b/packages/react-native-codegen/src/parsers/typescript/components/__test_fixtures__/failures.js deleted file mode 100644 index eefd9e316f18..000000000000 --- a/packages/react-native-codegen/src/parsers/typescript/components/__test_fixtures__/failures.js +++ /dev/null @@ -1,505 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -// @licenselint-loose-mode - -'use strict'; - -const COMMANDS_DEFINED_INLINE = ` -/** - * 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 - */ - -const codegenNativeCommands = require('codegenNativeCommands'); -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {Int32} from 'CodegenTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -export interface ModuleProps extends ViewProps { - // No props -} - -export const Commands = codegenNativeCommands<{ - readonly hotspotUpdate: ( - ref: React.Ref<'RCTView'>, - x: Int32, - y: Int32, - ) => void; -}>({ - supportedCommands: ['hotspotUpdate'], -}); - -export default codegenNativeComponent( - 'Module', -) as HostComponent; -`; - -const COMMANDS_DEFINED_MULTIPLE_TIMES = ` -/** - * 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 - */ - -const codegenNativeCommands = require('codegenNativeCommands'); -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {Int32} from 'CodegenTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -interface NativeCommands { - readonly hotspotUpdate: ( - viewRef: React.Ref<'RCTView'>, - x: Int32, - y: Int32, - ) => void; -} - -export interface ModuleProps extends ViewProps { - // No props or events -} - -export const Commands = codegenNativeCommands({ - supportedCommands: ['hotspotUpdate'], -}); -export const Commands2 = codegenNativeCommands({ - supportedCommands: ['hotspotUpdate'], -}); - -export default codegenNativeComponent( - 'Module', -) as HostComponent; -`; - -const COMMANDS_DEFINED_WITHOUT_REF = ` -/** - * 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 - */ - -const codegenNativeCommands = require('codegenNativeCommands'); -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {Int32} from 'CodegenTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -interface NativeCommands { - readonly hotspotUpdate: (x: Int32, y: Int32) => void; -} - -export interface ModuleProps extends ViewProps { - // No props or events -} - -export const Commands = codegenNativeCommands({ - supportedCommands: ['hotspotUpdate'], -}); - -export default codegenNativeComponent( - 'Module', -) as HostComponent; -`; - -const COMMANDS_DEFINED_WITH_NULLABLE_REF = ` -/** - * 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 - */ - -const codegenNativeCommands = require('codegenNativeCommands'); -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {Int32} from 'CodegenTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -interface NativeCommands { - readonly hotspotUpdate: (viewRef: React.Ref<'RCTView'> | null | undefined, x: Int32, y: Int32) => void; -} - -export interface ModuleProps extends ViewProps { - // No props or events -} - -export const Commands = codegenNativeCommands({ - supportedCommands: ['hotspotUpdate'], -}); - -export default codegenNativeComponent( - 'Module', -) as HostComponent; -`; - -const COMMANDS_DEFINED_WITH_MISMATCHED_METHOD_NAMES = ` -/** - * 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 - */ - -const codegenNativeCommands = require('codegenNativeCommands'); -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {Int32} from 'CodegenTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -interface NativeCommands { - readonly hotspotUpdate: (viewRef: React.Ref<'RCTView'>, x: Int32, y: Int32) => void; - readonly scrollTo: ( - viewRef: React.Ref<'RCTView'>, - y: Int32, - animated: boolean, - ) => void; -} - -export interface ModuleProps extends ViewProps { - // No props or events -} - -export const Commands = codegenNativeCommands({ - supportedCommands: ['scrollTo'], -}); -export default codegenNativeComponent( - 'Module', -) as HostComponent; -`; - -const COMMANDS_DEFINED_WITHOUT_METHOD_NAMES = ` -/** - * 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 - */ - -const codegenNativeCommands = require('codegenNativeCommands'); -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {Int32} from 'CodegenTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -interface NativeCommands { - readonly hotspotUpdate: (viewRef: React.Ref<'RCTView'>, x: Int32, y: Int32) => void; - readonly scrollTo: ( - viewRef: React.Ref<'RCTView'>, - y: Int32, - animated: boolean, - ) => void; -} - -export interface ModuleProps extends ViewProps { - // No props or events -} - -export const Commands = codegenNativeCommands(); - -export default codegenNativeComponent( - 'Module', -) as HostComponent; -`; - -const NULLABLE_WITH_DEFAULT = ` -/** - * 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 - */ - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {WithDefault, Float} from 'CodegenTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -export interface ModuleProps extends ViewProps { - nullable_with_default: WithDefault | null | undefined; -} - -export default codegenNativeComponent( - 'Module', -) as HostComponent; -`; - -const NON_OPTIONAL_KEY_WITH_DEFAULT_VALUE = ` -/** - * 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 - */ - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {WithDefault, Float} from 'CodegenTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -export interface ModuleProps extends ViewProps { - required_key_with_default: WithDefault; -} - -export default codegenNativeComponent( - 'Module', -) as HostComponent; -`; - -const PROPS_CONFLICT_NAMES = ` -/** - * 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 - */ - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -export interface ModuleProps extends ViewProps { - isEnabled: string, - - isEnabled: boolean, -} - -export default codegenNativeComponent( - 'Module', -) as HostComponent; -`; - -const PROPS_CONFLICT_WITH_SPREAD_PROPS = ` -/** - * 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 - */ - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -type PropsInFile = Readonly<{ - isEnabled: boolean, -}>; - -export interface ModuleProps extends ViewProps, PropsInFile { - isEnabled: boolean, -} - -export default codegenNativeComponent( - 'Module', -) as HostComponent; -`; - -const PROP_NUMBER_TYPE = ` -/** - * 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 - */ - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -export interface ModuleProps extends ViewProps { - someProp: number -} - -export default codegenNativeComponent( - 'Module', -) as HostComponent; -`; - -const PROP_MIXED_ENUM = ` -/** - * 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 - */ - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; -import type {WithDefault} from 'CodegenTypes'; - -export interface ModuleProps extends ViewProps { - someProp?: WithDefault<'foo' | 1, 1>; -} - -export default codegenNativeComponent( - 'Module', -) as HostComponent; -`; - -const PROP_ENUM_BOOLEAN = ` -/** - * 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 - */ - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; -import type {WithDefault} from 'CodegenTypes'; - -export interface ModuleProps extends ViewProps { - someProp?: WithDefault -} - -export default codegenNativeComponent( - 'Module', -) as HostComponent; -`; - -const PROP_ARRAY_MIXED_ENUM = ` -/** - * 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 - */ - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; -import type {WithDefault} from 'CodegenTypes'; - -export interface ModuleProps extends ViewProps { - someProp?: WithDefault, 1>; -} - -export default codegenNativeComponent( - 'Module', -) as HostComponent; -`; - -const PROP_ARRAY_ENUM_BOOLEAN = ` -/** - * 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 - */ - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; -import type {WithDefault} from 'CodegenTypes'; - -export interface ModuleProps extends ViewProps { - someProp?: WithDefault, false>; -} - -export default codegenNativeComponent( - 'Module', -) as HostComponent; -`; - -const PROP_ARRAY_ENUM_INT = ` -/** - * 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 - */ - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; -import type {WithDefault} from 'CodegenTypes'; - -export interface ModuleProps extends ViewProps { - someProp?: WithDefault, 0>; -} - -export default codegenNativeComponent( - 'Module', -) as HostComponent; -`; - -module.exports = { - COMMANDS_DEFINED_INLINE, - COMMANDS_DEFINED_MULTIPLE_TIMES, - COMMANDS_DEFINED_WITH_MISMATCHED_METHOD_NAMES, - COMMANDS_DEFINED_WITHOUT_METHOD_NAMES, - COMMANDS_DEFINED_WITHOUT_REF, - COMMANDS_DEFINED_WITH_NULLABLE_REF, - NULLABLE_WITH_DEFAULT, - NON_OPTIONAL_KEY_WITH_DEFAULT_VALUE, - PROPS_CONFLICT_NAMES, - PROPS_CONFLICT_WITH_SPREAD_PROPS, - PROP_NUMBER_TYPE, - PROP_MIXED_ENUM, - PROP_ENUM_BOOLEAN, - PROP_ARRAY_MIXED_ENUM, - PROP_ARRAY_ENUM_BOOLEAN, - PROP_ARRAY_ENUM_INT, -}; diff --git a/packages/react-native-codegen/src/parsers/typescript/components/__test_fixtures__/fixtures.js b/packages/react-native-codegen/src/parsers/typescript/components/__test_fixtures__/fixtures.js deleted file mode 100644 index 4005574ba68d..000000000000 --- a/packages/react-native-codegen/src/parsers/typescript/components/__test_fixtures__/fixtures.js +++ /dev/null @@ -1,1158 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -// @licenselint-loose-mode - -'use strict'; - -const EVENT_DEFINITION = ` - boolean_required: boolean; - boolean_optional_key?: boolean; - boolean_optional_value: boolean | null | undefined; - boolean_optional_both?: boolean | null | undefined; - - string_required: string; - string_optional_key?: (string); - string_optional_value: (string) | null | undefined; - string_optional_both?: (string | null | undefined); - - double_required: Double; - double_optional_key?: Double; - double_optional_value: Double | null | undefined; - double_optional_both?: Double | null | undefined; - - float_required: Float; - float_optional_key?: Float; - float_optional_value: Float | null | undefined; - float_optional_both?: Float | null | undefined; - - int32_required: Int32; - int32_optional_key?: Int32; - int32_optional_value: Int32 | null | undefined; - int32_optional_both?: Int32 | null | undefined; - - enum_required: 'small' | 'large'; - enum_optional_key?: 'small' | 'large'; - enum_optional_value: ('small' | 'large') | null | undefined; - enum_optional_both?: ('small' | 'large') | null | undefined; - - object_required: { - boolean_required: boolean; - }; - - object_optional_key?: { - string_optional_key?: string; - }; - - object_optional_value: { - float_optional_value: Float | null | undefined; - } | null | undefined; - - object_optional_both?: { - int32_optional_both?: Int32 | null | undefined; - } | null | undefined; - - object_required_nested_2_layers: { - object_optional_nested_1_layer?: { - boolean_required: Int32; - string_optional_key?: string; - double_optional_value: Double | null | undefined; - float_optional_value: Float | null | undefined; - int32_optional_both?: Int32 | null | undefined; - } | null | undefined; - }; - - object_readonly_required: Readonly<{ - boolean_required: boolean; - }>; - - object_readonly_optional_key?: Readonly<{ - string_optional_key?: string; - }>; - - object_readonly_optional_value: Readonly<{ - float_optional_value: Float | null | undefined; - }> | null | undefined; - - object_readonly_optional_both?: Readonly<{ - int32_optional_both?: Int32 | null | undefined; - }> | null | undefined; -`; - -const ONE_OF_EACH_PROP_EVENT_DEFAULT_AND_OPTIONS = ` -/** - * 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 - */ - -'use strict'; - -import type { - BubblingEventHandler, - DirectEventHandler, - WithDefault, -} from 'CodegenTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -export interface ModuleProps extends ViewProps { - // Props - boolean_default_true_optional_both?: WithDefault; - - // Events - onDirectEventDefinedInlineNull: DirectEventHandler; - onBubblingEventDefinedInlineNull: BubblingEventHandler; -} - -export default codegenNativeComponent('Module', { - interfaceOnly: true, - paperComponentName: 'RCTModule', -}) as HostComponent; -`; - -const ONE_OF_EACH_PROP_EVENT_DEFAULT_AND_OPTIONS_NO_CAST = ` -/** - * 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 - */ - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type { - BubblingEventHandler, - DirectEventHandler, - WithDefault, -} from 'CodegenTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -export interface ModuleProps extends ViewProps { - // Props - boolean_default_true_optional_both?: WithDefault; - - // Events - onDirectEventDefinedInlineNull: DirectEventHandler; - onBubblingEventDefinedInlineNull: BubblingEventHandler; -} - -export default codegenNativeComponent('Module', { - interfaceOnly: true, - excludedPlatforms: ['android'], - paperComponentName: 'RCTModule', -}) as HostComponent; -`; - -const NO_PROPS_EVENTS_ONLY_DEPRECATED_VIEW_CONFIG_NAME_OPTION = ` -/** - * 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 - */ - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -export interface ModuleProps extends ViewProps { - -} - -export default codegenNativeComponent('Module', { - deprecatedViewConfigName: 'DeprecateModuleName', -}) as HostComponent; -`; - -const ALL_PROP_TYPES_NO_EVENTS = ` -/** - * 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 - */ - -'use strict'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {Int32, Double, Float, WithDefault} from 'CodegenTypes'; -import type {ImageSource} from 'ImageSource'; -import type { - ColorValue, - ColorArrayValue, - PointValue, - EdgeInsetsValue, -} from 'StyleSheetTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -export interface ModuleProps extends ViewProps { - // Props - // Boolean props - boolean_required: boolean; - boolean_optional_key?: WithDefault; - boolean_optional_both?: WithDefault; - - // Boolean props, null default - boolean_null_optional_key?: WithDefault; - boolean_null_optional_both?: WithDefault; - - // String props - string_required: string; - string_optional_key?: WithDefault; - string_optional_both?: WithDefault; - - // String props, null default - string_null_optional_key?: WithDefault; - string_null_optional_both?: WithDefault; - - // Stringish props - stringish_required: Stringish; - stringish_optional_key?: WithDefault; - stringish_optional_both?: WithDefault; - - // Stringish props, null default - stringish_null_optional_key?: WithDefault; - stringish_null_optional_both?: WithDefault; - - // Double props - double_required: Double; - double_optional_key?: WithDefault; - double_optional_both?: WithDefault; - - // Float props - float_required: Float; - float_optional_key?: WithDefault; - float_optional_both?: WithDefault; - - // Float props, null default - float_null_optional_key?: WithDefault; - float_null_optional_both?: WithDefault; - - // Int32 props - int32_required: Int32; - int32_optional_key?: WithDefault; - int32_optional_both?: WithDefault; - - // String enum props - enum_optional_key?: WithDefault<'small' | 'large', 'small'>; - enum_optional_both?: WithDefault<'small' | 'large', 'small'>; - - // Int enum props - int_enum_optional_key?: WithDefault<0 | 1, 0>; - - // Object props - object_optional_key?: Readonly<{prop: string}>; - object_optional_both?: Readonly<{prop: string} | null | undefined>; - object_optional_value: Readonly<{prop: string} | null | undefined>; - - // ImageSource props - image_required: ImageSource; - image_optional_value: ImageSource | null | undefined; - image_optional_both?: ImageSource | null | undefined; - - // ColorValue props - color_required: ColorValue; - color_optional_key?: ColorValue; - color_optional_value: ColorValue | null | undefined; - color_optional_both?: ColorValue | null | undefined; - - // ColorArrayValue props - color_array_required: ColorArrayValue; - color_array_optional_key?: ColorArrayValue; - color_array_optional_value: ColorArrayValue | null | undefined; - color_array_optional_both?: ColorArrayValue | null | undefined; - - // ProcessedColorValue props - processed_color_required: ProcessedColorValue; - processed_color_optional_key?: ProcessedColorValue; - processed_color_optional_value: ProcessedColorValue | null | undefined; - processed_color_optional_both?: ProcessedColorValue | null | undefined; - - // PointValue props - point_required: PointValue; - point_optional_key?: PointValue; - point_optional_value: PointValue | null | undefined; - point_optional_both?: PointValue | null | undefined; - - // EdgeInsets props - insets_required: EdgeInsetsValue; - insets_optional_key?: EdgeInsetsValue; - insets_optional_value: EdgeInsetsValue | null | undefined; - insets_optional_both?: EdgeInsetsValue | null | undefined; -} - -export default codegenNativeComponent( - 'Module', -) as HostComponent; -`; - -const ARRAY_PROP_TYPES_NO_EVENTS = ` -/** - * 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 - */ - -'use strict'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {Int32, Double, Float, WithDefault} from 'CodegenTypes'; -import type {ImageSource} from 'ImageSource'; -import type { - ColorValue, - ColorArrayValue, - PointValue, - EdgeInsetsValue, -} from 'StyleSheetTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -type ObjectType = Readonly<{prop: string}>; -type ArrayObjectType = ReadonlyArray>; - -export interface ModuleProps extends ViewProps { - // Props - // Boolean props - array_boolean_required: ReadonlyArray; - array_boolean_optional_key?: ReadonlyArray; - array_boolean_optional_value: ReadonlyArray | null | undefined; - array_boolean_optional_both?: ReadonlyArray | null | undefined; - - // String props - array_string_required: ReadonlyArray; - array_string_optional_key?: ReadonlyArray; - array_string_optional_value: ReadonlyArray | null | undefined; - array_string_optional_both?: ReadonlyArray | null | undefined; - - // Double props - array_double_required: ReadonlyArray; - array_double_optional_key?: ReadonlyArray; - array_double_optional_value: ReadonlyArray | null | undefined; - array_double_optional_both?: ReadonlyArray | null | undefined; - - // Float props - array_float_required: ReadonlyArray; - array_float_optional_key?: ReadonlyArray; - array_float_optional_value: ReadonlyArray | null | undefined; - array_float_optional_both?: ReadonlyArray | null | undefined; - - // Int32 props - array_int32_required: ReadonlyArray; - array_int32_optional_key?: ReadonlyArray; - array_int32_optional_value: ReadonlyArray | null | undefined; - array_int32_optional_both?: ReadonlyArray | null | undefined; - - // String enum props - array_enum_optional_key?: WithDefault< - ReadonlyArray<'small' | 'large'>, - 'small' - >; - array_enum_optional_both?: WithDefault< - ReadonlyArray<'small' | 'large'>, - 'small' - >; - - // ImageSource props - array_image_required: ReadonlyArray; - array_image_optional_key?: ReadonlyArray; - array_image_optional_value: ReadonlyArray | null | undefined; - array_image_optional_both?: ReadonlyArray | null | undefined; - - // ColorValue props - array_color_required: ReadonlyArray; - array_color_optional_key?: ReadonlyArray; - array_color_optional_value: ReadonlyArray | null | undefined; - array_color_optional_both?: ReadonlyArray | null | undefined; - - // PointValue props - array_point_required: ReadonlyArray; - array_point_optional_key?: ReadonlyArray; - array_point_optional_value: ReadonlyArray | null | undefined; - array_point_optional_both?: ReadonlyArray | null | undefined; - - // EdgeInsetsValue props - array_insets_required: ReadonlyArray; - array_insets_optional_key?: ReadonlyArray; - array_insets_optional_value: ReadonlyArray | null | undefined; - array_insets_optional_both?: ReadonlyArray | null | undefined; - - // Object props - array_object_required: ReadonlyArray>; - array_object_optional_key?: ReadonlyArray>; - array_object_optional_value: ArrayObjectType | null | undefined; - array_object_optional_both?: ReadonlyArray | null | undefined; - - // Nested array object types - array_of_array_object_required: ReadonlyArray< - Readonly<{ - // This needs to be the same name as the top level array above - array_object_required: ReadonlyArray>; - }> - >; - array_of_array_object_optional_key?: ReadonlyArray< - Readonly<{ - // This needs to be the same name as the top level array above - array_object_optional_key: ReadonlyArray>; - }> - >; - array_of_array_object_optional_value: ReadonlyArray< - Readonly<{ - // This needs to be the same name as the top level array above - array_object_optional_value: ReadonlyArray< - Readonly<{prop: string | null | undefined}> - >; - }> - > | null | undefined; - array_of_array_object_optional_both?: ReadonlyArray< - Readonly<{ - // This needs to be the same name as the top level array above - array_object_optional_both: ReadonlyArray< - Readonly<{prop?: string | null | undefined}> - >; - }> - > | null | undefined; - - // Nested array of array of object types - array_of_array_of_object_required: ReadonlyArray< - ReadonlyArray< - Readonly<{ - prop: string; - }> - > - >; - - // Nested array of array of object types (in file) - array_of_array_of_object_required_in_file: ReadonlyArray< - ReadonlyArray - >; -} - -export default codegenNativeComponent( - 'Module', -) as HostComponent; -`; - -const ARRAY2_PROP_TYPES_NO_EVENTS = ` -/** - * 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 - */ - -'use strict'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {Int32, Double, Float, WithDefault} from 'CodegenTypes'; -import type {ImageSource} from 'ImageSource'; -import type { - ColorValue, - ColorArrayValue, - PointValue, - EdgeInsetsValue, -} from 'StyleSheetTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -type ObjectType = Readonly<{prop: string}>; -type ArrayObjectType = readonly Readonly<{prop: string}>[]; - -export interface ModuleProps extends ViewProps { - // Props - // Boolean props - array_boolean_required: readonly boolean[]; - array_boolean_optional_key?: readonly boolean[]; - array_boolean_optional_value: readonly boolean[] | null | undefined; - array_boolean_optional_both?: readonly boolean[] | null | undefined; - - // String props - array_string_required: readonly string[]; - array_string_optional_key?: readonly string[]; - array_string_optional_value: readonly string[] | null | undefined; - array_string_optional_both?: readonly string[] | null | undefined; - - // Double props - array_double_required: readonly Double[]; - array_double_optional_key?: readonly Double[]; - array_double_optional_value: readonly Double[] | null | undefined; - array_double_optional_both?: readonly Double[] | null | undefined; - - // Float props - array_float_required: readonly Float[]; - array_float_optional_key?: readonly Float[]; - array_float_optional_value: readonly Float[] | null | undefined; - array_float_optional_both?: readonly Float[] | null | undefined; - - // Int32 props - array_int32_required: readonly Int32[]; - array_int32_optional_key?: readonly Int32[]; - array_int32_optional_value: readonly Int32[] | null | undefined; - array_int32_optional_both?: readonly Int32[] | null | undefined; - - // String enum props - array_enum_optional_key?: WithDefault< - readonly ('small' | 'large')[], - 'small' - >; - array_enum_optional_both?: WithDefault< - readonly ('small' | 'large')[], - 'small' - >; - - // ImageSource props - array_image_required: readonly ImageSource[]; - array_image_optional_key?: readonly ImageSource[]; - array_image_optional_value: readonly ImageSource[] | null | undefined; - array_image_optional_both?: readonly ImageSource[] | null | undefined; - - // ColorValue props - array_color_required: readonly ColorValue[]; - array_color_optional_key?: readonly ColorValue[]; - array_color_optional_value: readonly ColorValue[] | null | undefined; - array_color_optional_both?: readonly ColorValue[] | null | undefined; - - // PointValue props - array_point_required: readonly PointValue[]; - array_point_optional_key?: readonly PointValue[]; - array_point_optional_value: readonly PointValue[] | null | undefined; - array_point_optional_both?: readonly PointValue[] | null | undefined; - - // EdgeInsetsValue props - array_insets_required: readonly EdgeInsetsValue[]; - array_insets_optional_key?: readonly EdgeInsetsValue[]; - array_insets_optional_value: readonly EdgeInsetsValue[] | null | undefined; - array_insets_optional_both?: readonly EdgeInsetsValue[] | null | undefined; - - // Object props - array_object_required: readonly Readonly<{prop: string}>[]; - array_object_optional_key?: readonly Readonly<{prop: string}>[]; - array_object_optional_value: ArrayObjectType | null | undefined; - array_object_optional_both?: readonly ObjectType[] | null | undefined; - - // Nested array object types - array_of_array_object_required: readonly Readonly<{ - // This needs to be the same name as the top level array above - array_object_required: readonly Readonly<{prop: string}>[]; - }>[]; - array_of_array_object_optional_key?: readonly Readonly<{ - // This needs to be the same name as the top level array above - array_object_optional_key: readonly Readonly<{prop?: string}>[]; - }>[]; - array_of_array_object_optional_value: readonly Readonly<{ - // This needs to be the same name as the top level array above - array_object_optional_value: readonly Readonly<{prop: string | null | undefined}>[]; - }>[] | null | undefined; - array_of_array_object_optional_both?: readonly Readonly<{ - // This needs to be the same name as the top level array above - array_object_optional_both: readonly Readonly<{prop?: string | null | undefined}>[]; - }>[] | null | undefined; - - // Nested array of array of object types - array_of_array_of_object_required: readonly Readonly<{ - prop: string; - }>[][]; - - // Nested array of array of object types (in file) - array_of_array_of_object_required_in_file: readonly ObjectType[][]; -} - -export default codegenNativeComponent( - 'Module', -) as HostComponent; -`; - -const OBJECT_PROP_TYPES_NO_EVENTS = ` -/** - * 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 - */ - -'use strict'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {Int32, Double, Float, WithDefault} from 'CodegenTypes'; -import type {ImageSource} from 'ImageSource'; -import type { - ColorValue, - ColorArrayValue, - PointValue, - EdgeInsetsValue, -} from 'StyleSheetTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -export interface ModuleProps extends ViewProps { - // Props - // Boolean props - boolean_required: Readonly<{prop: boolean}>; - boolean_optional: Readonly<{prop?: WithDefault}>; - - // String props - string_required: Readonly<{prop: string}>; - string_optional: Readonly<{prop?: WithDefault}>; - - // Double props - double_required: Readonly<{prop: Double}>; - double_optional: Readonly<{prop?: WithDefault}>; - - // Float props - float_required: Readonly<{prop: Float}>; - float_optional: Readonly<{prop?: WithDefault}>; - - // Int32 props - int_required: Readonly<{prop: Int32}>; - int_optional: Readonly<{prop?: WithDefault}>; - - // String enum props - enum_optional: Readonly<{ - prop?: WithDefault, 'small'>; - }>; - - // ImageSource props - image_required: Readonly<{prop: ImageSource}>; - image_optional_key: Readonly<{prop?: ImageSource}>; - image_optional_value: Readonly<{prop: ImageSource | null | undefined}>; - image_optional_both: Readonly<{prop?: ImageSource | null | undefined}>; - - // ColorValue props - color_required: Readonly<{prop: ColorValue}>; - color_optional_key: Readonly<{prop?: ColorValue}>; - color_optional_value: Readonly<{prop: ColorValue | null | undefined}>; - color_optional_both: Readonly<{prop?: ColorValue | null | undefined}>; - - // ProcessedColorValue props - processed_color_required: Readonly<{prop: ProcessedColorValue}>; - processed_color_optional_key: Readonly<{prop?: ProcessedColorValue}>; - processed_color_optional_value: Readonly<{ - prop: ProcessedColorValue | null | undefined; - }>; - processed_color_optional_both: Readonly<{ - prop?: ProcessedColorValue | null | undefined; - }>; - - // PointValue props - point_required: Readonly<{prop: PointValue}>; - point_optional_key: Readonly<{prop?: PointValue}>; - point_optional_value: Readonly<{prop: PointValue | null | undefined}>; - point_optional_both: Readonly<{prop?: PointValue | null | undefined}>; - - // EdgeInsetsValue props - insets_required: Readonly<{prop: EdgeInsetsValue}>; - insets_optional_key: Readonly<{prop?: EdgeInsetsValue}>; - insets_optional_value: Readonly<{prop: EdgeInsetsValue | null | undefined}>; - insets_optional_both: Readonly<{prop?: EdgeInsetsValue | null | undefined}>; - - // Nested object props - object_required: Readonly<{prop: Readonly<{nestedProp: string}>}>; - object_optional_key?: Readonly<{prop: Readonly<{nestedProp: string}>}>; - object_optional_value: Readonly<{ - prop: Readonly<{nestedProp: string}>; - }> | null | undefined; - object_optional_both?: Readonly<{ - prop: Readonly<{nestedProp: string}>; - }> | null | undefined; -} - -export default codegenNativeComponent( - 'Module', -) as HostComponent; -`; - -const PROPS_ALIASED_LOCALLY = ` -/** - * 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 - */ - -'use strict'; - -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -type DeepSpread = Readonly<{ - otherStringProp: string; -}>; - -export interface PropsInFile extends DeepSpread { - isEnabled: boolean; - label: string; -} - -type ReadOnlyPropsInFile = Readonly; - -export interface ModuleProps extends ViewProps, ReadOnlyPropsInFile { - localType: ReadOnlyPropsInFile; - localArr: ReadonlyArray; -} - -export default codegenNativeComponent( - 'Module', -) as HostComponent; -`; - -const EVENTS_DEFINED_INLINE_WITH_ALL_TYPES = ` -/** - * 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 - */ - -import type {HostComponent} from 'react-native'; -const codegenNativeComponent = require('codegenNativeComponent'); - -import type { - Int32, - Double, - Float, - BubblingEventHandler, - DirectEventHandler, -} from 'CodegenTypes'; - -import type {ViewProps} from 'ViewPropTypes'; - -export interface ModuleProps extends ViewProps { - // No Props - - // Events - onDirectEventDefinedInline: DirectEventHandler< - Readonly<{ - ${EVENT_DEFINITION} - }> - >; - - onDirectEventDefinedInlineOptionalKey?: (DirectEventHandler< - Readonly<{ - ${EVENT_DEFINITION} - }> - >); - - onDirectEventDefinedInlineOptionalValue: (DirectEventHandler< - Readonly<{ - ${EVENT_DEFINITION} - }> - >) | null | undefined; - - onDirectEventDefinedInlineOptionalBoth?: (DirectEventHandler< - Readonly<{ - ${EVENT_DEFINITION} - }> - > | null | undefined); - - onDirectEventDefinedInlineWithPaperName?: DirectEventHandler< - Readonly<{ - ${EVENT_DEFINITION} - }>, - 'paperDirectEventDefinedInlineWithPaperName' - > | null | undefined; - - onBubblingEventDefinedInline: BubblingEventHandler< - Readonly<{ - ${EVENT_DEFINITION} - }> - >; - - onBubblingEventDefinedInlineOptionalKey?: BubblingEventHandler< - Readonly<{ - ${EVENT_DEFINITION} - }> - >; - - onBubblingEventDefinedInlineOptionalValue: BubblingEventHandler< - Readonly<{ - ${EVENT_DEFINITION} - }> - > | null | undefined; - - onBubblingEventDefinedInlineOptionalBoth?: BubblingEventHandler< - Readonly<{ - ${EVENT_DEFINITION} - }> - > | null | undefined; - - onBubblingEventDefinedInlineWithPaperName?: BubblingEventHandler< - Readonly<{ - ${EVENT_DEFINITION} - }>, - 'paperBubblingEventDefinedInlineWithPaperName' - > | null | undefined; -} - -export default codegenNativeComponent( - 'Module', -) as HostComponent; -`; - -const EVENTS_DEFINED_AS_NULL_INLINE = ` -/** - * 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 - */ - -'use strict'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {BubblingEventHandler, DirectEventHandler} from 'CodegenTypese'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -export interface ModuleProps extends ViewProps { - // No props - - // Events defined inline - onDirectEventDefinedInlineNull: DirectEventHandler; - onDirectEventDefinedInlineNullOptionalKey?: DirectEventHandler; - onDirectEventDefinedInlineNullOptionalValue: DirectEventHandler | null | undefined; - onDirectEventDefinedInlineNullOptionalBoth?: DirectEventHandler; - onDirectEventDefinedInlineNullWithPaperName?: DirectEventHandler< - null, - 'paperDirectEventDefinedInlineNullWithPaperName' - > | null | undefined; - - onBubblingEventDefinedInlineNull: BubblingEventHandler; - onBubblingEventDefinedInlineNullOptionalKey?: BubblingEventHandler; - onBubblingEventDefinedInlineNullOptionalValue: BubblingEventHandler | null | undefined; - onBubblingEventDefinedInlineNullOptionalBoth?: BubblingEventHandler | null | undefined; - onBubblingEventDefinedInlineNullWithPaperName?: BubblingEventHandler< - undefined, - 'paperBubblingEventDefinedInlineNullWithPaperName' - > | null | undefined; -} - -export default codegenNativeComponent( - 'Module', -) as HostComponent; -`; - -const PROPS_AND_EVENTS_TYPES_EXPORTED = ` -/** - * 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 - */ - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; -import type { - BubblingEventHandler, - DirectEventHandler, -} from 'CodegenTypes'; - -export type EventInFile = Readonly<{ - ${EVENT_DEFINITION} -}>; - -export interface ModuleProps extends ViewProps { - // No props - - // Events defined inline - onBubblingEventDefinedInline: BubblingEventHandler; - onBubblingEventDefinedInlineWithPaperName: BubblingEventHandler< - EventInFile, - 'paperBubblingEventDefinedInlineWithPaperName' - >; - onDirectEventDefinedInline: DirectEventHandler; - onDirectEventDefinedInlineWithPaperName: DirectEventHandler< - EventInFile, - 'paperDirectEventDefinedInlineWithPaperName' - >; -} - -export default codegenNativeComponent( - 'Module', -) as HostComponent; -`; - -const PROPS_AS_EXTERNAL_TYPES = ` -/** - * 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 - */ - -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {HostComponent} from 'react-native'; - -export type String = string; -export type AnotherArray = ReadonlyArray; - -export interface ModuleProps { - disable: String; - array: AnotherArray; -} - -export default codegenNativeComponent( - 'Module', -) as HostComponent; -`; - -const COMMANDS_DEFINED_WITH_ALL_TYPES = ` -/** - * 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 - */ - - const codegenNativeCommands = require('codegenNativeCommands'); - const codegenNativeComponent = require('codegenNativeComponent'); - - import type {Int32, Double, Float} from 'CodegenTypes'; - import type {RootTag} from 'RCTExport'; - import type {ViewProps} from 'ViewPropTypes'; - import type {HostComponent} from 'react-native'; - - -export interface ModuleProps extends ViewProps { - // No props or events -} - -type NativeType = HostComponent; - - interface NativeCommands { - readonly handleRootTag: (viewRef: React.ElementRef, rootTag: RootTag) => void; - readonly hotspotUpdate: (viewRef: React.ElementRef, x: Int32, y: Int32) => void; - readonly scrollTo: ( - viewRef: React.ElementRef, - x: Float, - y: Int32, - z: Double, - animated: boolean, - ) => void; - } - - export const Commands = codegenNativeCommands({ - supportedCommands: ['handleRootTag', 'hotspotUpdate', 'scrollTo'], - }); - -export default codegenNativeComponent( - 'Module', -) as NativeType; -`; - -const COMMANDS_WITH_EXTERNAL_TYPES = ` -/** - * 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 - */ - -const codegenNativeCommands = require('codegenNativeCommands'); -const codegenNativeComponent = require('codegenNativeComponent'); - -import type {Int32} from 'CodegenTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -export type Boolean = boolean; -export type Int = Int32; -export type Void = void; - -export interface ModuleProps extends ViewProps { - // No props or events -} - -type NativeType = HostComponent; - -export type ScrollTo = ( - viewRef: React.ElementRef, - y: Int, - animated: Boolean, -) => Void; - -interface NativeCommands { - readonly scrollTo: ScrollTo; -} - -export const Commands = codegenNativeCommands({ - supportedCommands: ['scrollTo'], -}); - -export default codegenNativeComponent('Module') as NativeType; - -`; - -const COMMANDS_EVENTS_TYPES_EXPORTED = ` -/** - * 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 - */ - -import type { - BubblingEventHandler, - DirectEventHandler, -} from 'CodegenTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -export type EventInFile = Readonly<{ - ${EVENT_DEFINITION} -}>; - -export type Boolean = boolean; -export type Int = Int32; -export type Void = void; - -export interface ModuleProps extends ViewProps { - // No props - - // Events defined inline - onBubblingEventDefinedInline: BubblingEventHandler, - onBubblingEventDefinedInlineWithPaperName: BubblingEventHandler, - onDirectEventDefinedInline: DirectEventHandler, - onDirectEventDefinedInlineWithPaperName: DirectEventHandler, -} - -// Add state here -export interface ModuleNativeState { - boolean_required: boolean, - boolean_optional_key?: WithDefault, - boolean_optional_both?: WithDefault, -} - -type NativeType = HostComponent; - -export type ScrollTo = (viewRef: React.ElementRef, y: Int, animated: Boolean) => Void; - -interface NativeCommands { - readonly scrollTo: ScrollTo; -} - -export const Commands = codegenNativeCommands({ - supportedCommands: ['scrollTo'] -}); - -export default codegenNativeComponent( - 'Module', -) as NativeType; -`; - -const PROPS_AND_EVENTS_WITH_INTERFACES = ` -import type { - BubblingEventHandler, - DirectEventHandler, - Int32, -} from 'CodegenTypes'; -import type {ViewProps} from 'ViewPropTypes'; -import type {HostComponent} from 'react-native'; - -const codegenNativeComponent = require('codegenNativeComponent'); - -export interface Base1 { - readonly x: string; -} - -export interface Base2 { - readonly y: Int32; -} - -export interface Derived extends Base1, Base2 { - readonly z: boolean; -} - -export interface ModuleProps extends ViewProps { - // Props - ordinary_prop: Derived; - readonly_prop: Readonly; - ordinary_array_prop?: readonly Derived[]; - readonly_array_prop?: readonly Readonly[]; - ordinary_nested_array_prop?: readonly Derived[][]; - readonly_nested_array_prop?: readonly Readonly[][]; - - // Events - onDirect: DirectEventHandler; - onBubbling: BubblingEventHandler>; -} - -export default codegenNativeComponent('Module', { - interfaceOnly: true, - paperComponentName: 'RCTModule', -}) as HostComponent; -`; - -module.exports = { - ALL_PROP_TYPES_NO_EVENTS, - ARRAY_PROP_TYPES_NO_EVENTS, - ARRAY2_PROP_TYPES_NO_EVENTS, - OBJECT_PROP_TYPES_NO_EVENTS, - PROPS_ALIASED_LOCALLY, - ONE_OF_EACH_PROP_EVENT_DEFAULT_AND_OPTIONS, - ONE_OF_EACH_PROP_EVENT_DEFAULT_AND_OPTIONS_NO_CAST, - NO_PROPS_EVENTS_ONLY_DEPRECATED_VIEW_CONFIG_NAME_OPTION, - EVENTS_DEFINED_INLINE_WITH_ALL_TYPES, - EVENTS_DEFINED_AS_NULL_INLINE, - PROPS_AND_EVENTS_TYPES_EXPORTED, - COMMANDS_EVENTS_TYPES_EXPORTED, - COMMANDS_DEFINED_WITH_ALL_TYPES, - PROPS_AS_EXTERNAL_TYPES, - COMMANDS_WITH_EXTERNAL_TYPES, - PROPS_AND_EVENTS_WITH_INTERFACES, -}; diff --git a/packages/react-native-codegen/src/parsers/typescript/components/__tests__/__snapshots__/typescript-component-parser-test.js.snap b/packages/react-native-codegen/src/parsers/typescript/components/__tests__/__snapshots__/typescript-component-parser-test.js.snap deleted file mode 100644 index 90947e1af64d..000000000000 --- a/packages/react-native-codegen/src/parsers/typescript/components/__tests__/__snapshots__/typescript-component-parser-test.js.snap +++ /dev/null @@ -1,10392 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`RN Codegen TypeScript Parser Fails with error message COMMANDS_DEFINED_INLINE 1`] = `"codegenNativeCommands doesn't support inline definitions. Specify a file local type alias"`; - -exports[`RN Codegen TypeScript Parser Fails with error message COMMANDS_DEFINED_MULTIPLE_TIMES 1`] = `"codegenNativeCommands may only be called once in a file"`; - -exports[`RN Codegen TypeScript Parser Fails with error message COMMANDS_DEFINED_WITH_MISMATCHED_METHOD_NAMES 1`] = `"codegenNativeCommands expected the same supportedCommands specified in the NativeCommands interface: hotspotUpdate, scrollTo"`; - -exports[`RN Codegen TypeScript Parser Fails with error message COMMANDS_DEFINED_WITH_NULLABLE_REF 1`] = `"The first argument of method hotspotUpdate must be of type React.ElementRef<>"`; - -exports[`RN Codegen TypeScript Parser Fails with error message COMMANDS_DEFINED_WITHOUT_METHOD_NAMES 1`] = `"codegenNativeCommands must be passed options including the supported commands"`; - -exports[`RN Codegen TypeScript Parser Fails with error message COMMANDS_DEFINED_WITHOUT_REF 1`] = `"The first argument of method hotspotUpdate must be of type React.ElementRef<>"`; - -exports[`RN Codegen TypeScript Parser Fails with error message NON_OPTIONAL_KEY_WITH_DEFAULT_VALUE 1`] = `"key required_key_with_default must be optional if used with WithDefault<> annotation"`; - -exports[`RN Codegen TypeScript Parser Fails with error message NULLABLE_WITH_DEFAULT 1`] = `"WithDefault<> is optional and does not need to be marked as optional. Please remove the union of undefined and/or null"`; - -exports[`RN Codegen TypeScript Parser Fails with error message PROP_ARRAY_ENUM_BOOLEAN 1`] = `"Unsupported union type for \\"someProp\\", received \\"BooleanLiteral\\""`; - -exports[`RN Codegen TypeScript Parser Fails with error message PROP_ARRAY_ENUM_INT 1`] = `"Arrays of int enums are not supported (see: \\"someProp\\")"`; - -exports[`RN Codegen TypeScript Parser Fails with error message PROP_ARRAY_MIXED_ENUM 1`] = `"Mixed types are not supported (see \\"someProp\\")"`; - -exports[`RN Codegen TypeScript Parser Fails with error message PROP_ENUM_BOOLEAN 1`] = `"Unsupported union type for \\"someProp\\", received \\"BooleanLiteral\\""`; - -exports[`RN Codegen TypeScript Parser Fails with error message PROP_MIXED_ENUM 1`] = `"Mixed types are not supported (see \\"someProp\\")"`; - -exports[`RN Codegen TypeScript Parser Fails with error message PROP_NUMBER_TYPE 1`] = `"Cannot use \\"TSNumberKeyword\\" type annotation for \\"someProp\\": must use a specific numeric type like Int32, Double, or Float"`; - -exports[`RN Codegen TypeScript Parser Fails with error message PROPS_CONFLICT_NAMES 1`] = `"A prop was already defined with the name isEnabled"`; - -exports[`RN Codegen TypeScript Parser Fails with error message PROPS_CONFLICT_WITH_SPREAD_PROPS 1`] = `"A prop was already defined with the name isEnabled"`; - -exports[`RN Codegen TypeScript Parser can generate fixture ALL_PROP_TYPES_NO_EVENTS 1`] = ` -"{ - 'modules': { - 'Module': { - 'type': 'Component', - 'components': { - 'Module': { - 'extendsProps': [ - { - 'type': 'ReactNativeBuiltInType', - 'knownTypeName': 'ReactNativeCoreViewProps' - } - ], - 'events': [], - 'props': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation', - 'default': false - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation', - 'default': true - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation', - 'default': true - } - }, - { - 'name': 'boolean_null_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation', - 'default': null - } - }, - { - 'name': 'boolean_null_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation', - 'default': null - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': '' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': '' - } - }, - { - 'name': 'string_null_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - }, - { - 'name': 'string_null_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - }, - { - 'name': 'stringish_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - }, - { - 'name': 'stringish_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': '' - } - }, - { - 'name': 'stringish_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': '' - } - }, - { - 'name': 'stringish_null_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - }, - { - 'name': 'stringish_null_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation', - 'default': 0 - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation', - 'default': 1.1 - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation', - 'default': 1.1 - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation', - 'default': 0 - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation', - 'default': 1.1 - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation', - 'default': 1.1 - } - }, - { - 'name': 'float_null_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation', - 'default': null - } - }, - { - 'name': 'float_null_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation', - 'default': null - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation', - 'default': 0 - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation', - 'default': 1 - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation', - 'default': 1 - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'default': 'small', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'default': 'small', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'int_enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32EnumTypeAnnotation', - 'default': 0, - 'options': [ - 0, - 1 - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - }, - { - 'name': 'image_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ImageSourcePrimitive' - } - }, - { - 'name': 'image_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ImageSourcePrimitive' - } - }, - { - 'name': 'image_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ImageSourcePrimitive' - } - }, - { - 'name': 'color_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - }, - { - 'name': 'color_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - }, - { - 'name': 'color_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - }, - { - 'name': 'color_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - }, - { - 'name': 'color_array_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - }, - { - 'name': 'color_array_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - }, - { - 'name': 'color_array_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - }, - { - 'name': 'color_array_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - }, - { - 'name': 'processed_color_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - }, - { - 'name': 'processed_color_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - }, - { - 'name': 'processed_color_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - }, - { - 'name': 'processed_color_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - }, - { - 'name': 'point_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'PointPrimitive' - } - }, - { - 'name': 'point_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'PointPrimitive' - } - }, - { - 'name': 'point_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'PointPrimitive' - } - }, - { - 'name': 'point_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'PointPrimitive' - } - }, - { - 'name': 'insets_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'EdgeInsetsPrimitive' - } - }, - { - 'name': 'insets_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'EdgeInsetsPrimitive' - } - }, - { - 'name': 'insets_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'EdgeInsetsPrimitive' - } - }, - { - 'name': 'insets_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'EdgeInsetsPrimitive' - } - } - ], - 'commands': [] - } - } - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture ARRAY_PROP_TYPES_NO_EVENTS 1`] = ` -"{ - 'modules': { - 'Module': { - 'type': 'Component', - 'components': { - 'Module': { - 'extendsProps': [ - { - 'type': 'ReactNativeBuiltInType', - 'knownTypeName': 'ReactNativeCoreViewProps' - } - ], - 'events': [], - 'props': [ - { - 'name': 'array_boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'BooleanTypeAnnotation' - } - } - }, - { - 'name': 'array_boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'BooleanTypeAnnotation' - } - } - }, - { - 'name': 'array_boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'BooleanTypeAnnotation' - } - } - }, - { - 'name': 'array_boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'BooleanTypeAnnotation' - } - } - }, - { - 'name': 'array_string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - }, - { - 'name': 'array_string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - }, - { - 'name': 'array_string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - }, - { - 'name': 'array_string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - }, - { - 'name': 'array_double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'DoubleTypeAnnotation' - } - } - }, - { - 'name': 'array_double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'DoubleTypeAnnotation' - } - } - }, - { - 'name': 'array_double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'DoubleTypeAnnotation' - } - } - }, - { - 'name': 'array_double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'DoubleTypeAnnotation' - } - } - }, - { - 'name': 'array_float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'FloatTypeAnnotation' - } - } - }, - { - 'name': 'array_float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'FloatTypeAnnotation' - } - } - }, - { - 'name': 'array_float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'FloatTypeAnnotation' - } - } - }, - { - 'name': 'array_float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'FloatTypeAnnotation' - } - } - }, - { - 'name': 'array_int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'Int32TypeAnnotation' - } - } - }, - { - 'name': 'array_int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'Int32TypeAnnotation' - } - } - }, - { - 'name': 'array_int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'Int32TypeAnnotation' - } - } - }, - { - 'name': 'array_int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'Int32TypeAnnotation' - } - } - }, - { - 'name': 'array_enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringEnumTypeAnnotation', - 'default': 'small', - 'options': [ - 'small', - 'large' - ] - } - } - }, - { - 'name': 'array_enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringEnumTypeAnnotation', - 'default': 'small', - 'options': [ - 'small', - 'large' - ] - } - } - }, - { - 'name': 'array_image_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ImageSourcePrimitive' - } - } - }, - { - 'name': 'array_image_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ImageSourcePrimitive' - } - } - }, - { - 'name': 'array_image_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ImageSourcePrimitive' - } - } - }, - { - 'name': 'array_image_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ImageSourcePrimitive' - } - } - }, - { - 'name': 'array_color_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - }, - { - 'name': 'array_color_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - }, - { - 'name': 'array_color_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - }, - { - 'name': 'array_color_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - }, - { - 'name': 'array_point_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'PointPrimitive' - } - } - }, - { - 'name': 'array_point_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'PointPrimitive' - } - } - }, - { - 'name': 'array_point_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'PointPrimitive' - } - } - }, - { - 'name': 'array_point_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'PointPrimitive' - } - } - }, - { - 'name': 'array_insets_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'EdgeInsetsPrimitive' - } - } - }, - { - 'name': 'array_insets_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'EdgeInsetsPrimitive' - } - } - }, - { - 'name': 'array_insets_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'EdgeInsetsPrimitive' - } - } - }, - { - 'name': 'array_insets_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'EdgeInsetsPrimitive' - } - } - }, - { - 'name': 'array_object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - }, - { - 'name': 'array_object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - }, - { - 'name': 'array_object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - }, - { - 'name': 'array_object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - }, - { - 'name': 'array_of_array_object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'array_object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - } - ] - } - } - }, - { - 'name': 'array_of_array_object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'array_object_optional_key', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - } - ] - } - } - }, - { - 'name': 'array_of_array_object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'array_object_optional_value', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - } - ] - } - } - }, - { - 'name': 'array_of_array_object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'array_object_optional_both', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - } - ] - } - } - }, - { - 'name': 'array_of_array_of_object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - } - }, - { - 'name': 'array_of_array_of_object_required_in_file', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - } - } - ], - 'commands': [] - } - } - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture ARRAY2_PROP_TYPES_NO_EVENTS 1`] = ` -"{ - 'modules': { - 'Module': { - 'type': 'Component', - 'components': { - 'Module': { - 'extendsProps': [ - { - 'type': 'ReactNativeBuiltInType', - 'knownTypeName': 'ReactNativeCoreViewProps' - } - ], - 'events': [], - 'props': [ - { - 'name': 'array_boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'BooleanTypeAnnotation' - } - } - }, - { - 'name': 'array_boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'BooleanTypeAnnotation' - } - } - }, - { - 'name': 'array_boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'BooleanTypeAnnotation' - } - } - }, - { - 'name': 'array_boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'BooleanTypeAnnotation' - } - } - }, - { - 'name': 'array_string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - }, - { - 'name': 'array_string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - }, - { - 'name': 'array_string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - }, - { - 'name': 'array_string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - }, - { - 'name': 'array_double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'DoubleTypeAnnotation' - } - } - }, - { - 'name': 'array_double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'DoubleTypeAnnotation' - } - } - }, - { - 'name': 'array_double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'DoubleTypeAnnotation' - } - } - }, - { - 'name': 'array_double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'DoubleTypeAnnotation' - } - } - }, - { - 'name': 'array_float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'FloatTypeAnnotation' - } - } - }, - { - 'name': 'array_float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'FloatTypeAnnotation' - } - } - }, - { - 'name': 'array_float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'FloatTypeAnnotation' - } - } - }, - { - 'name': 'array_float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'FloatTypeAnnotation' - } - } - }, - { - 'name': 'array_int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'Int32TypeAnnotation' - } - } - }, - { - 'name': 'array_int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'Int32TypeAnnotation' - } - } - }, - { - 'name': 'array_int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'Int32TypeAnnotation' - } - } - }, - { - 'name': 'array_int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'Int32TypeAnnotation' - } - } - }, - { - 'name': 'array_enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringEnumTypeAnnotation', - 'default': 'small', - 'options': [ - 'small', - 'large' - ] - } - } - }, - { - 'name': 'array_enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringEnumTypeAnnotation', - 'default': 'small', - 'options': [ - 'small', - 'large' - ] - } - } - }, - { - 'name': 'array_image_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ImageSourcePrimitive' - } - } - }, - { - 'name': 'array_image_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ImageSourcePrimitive' - } - } - }, - { - 'name': 'array_image_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ImageSourcePrimitive' - } - } - }, - { - 'name': 'array_image_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ImageSourcePrimitive' - } - } - }, - { - 'name': 'array_color_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - }, - { - 'name': 'array_color_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - }, - { - 'name': 'array_color_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - }, - { - 'name': 'array_color_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - }, - { - 'name': 'array_point_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'PointPrimitive' - } - } - }, - { - 'name': 'array_point_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'PointPrimitive' - } - } - }, - { - 'name': 'array_point_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'PointPrimitive' - } - } - }, - { - 'name': 'array_point_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'PointPrimitive' - } - } - }, - { - 'name': 'array_insets_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'EdgeInsetsPrimitive' - } - } - }, - { - 'name': 'array_insets_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'EdgeInsetsPrimitive' - } - } - }, - { - 'name': 'array_insets_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'EdgeInsetsPrimitive' - } - } - }, - { - 'name': 'array_insets_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'EdgeInsetsPrimitive' - } - } - }, - { - 'name': 'array_object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - }, - { - 'name': 'array_object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - }, - { - 'name': 'array_object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - }, - { - 'name': 'array_object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - }, - { - 'name': 'array_of_array_object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'array_object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - } - ] - } - } - }, - { - 'name': 'array_of_array_object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'array_object_optional_key', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - } - ] - } - } - }, - { - 'name': 'array_of_array_object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'array_object_optional_value', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - } - ] - } - } - }, - { - 'name': 'array_of_array_object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'array_object_optional_both', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - } - ] - } - } - }, - { - 'name': 'array_of_array_of_object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - } - }, - { - 'name': 'array_of_array_of_object_required_in_file', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - } - } - ], - 'commands': [] - } - } - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture COMMANDS_DEFINED_WITH_ALL_TYPES 1`] = ` -"{ - 'modules': { - 'Module': { - 'type': 'Component', - 'components': { - 'Module': { - 'extendsProps': [ - { - 'type': 'ReactNativeBuiltInType', - 'knownTypeName': 'ReactNativeCoreViewProps' - } - ], - 'events': [], - 'props': [], - 'commands': [ - { - 'name': 'handleRootTag', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'params': [ - { - 'name': 'rootTag', - 'typeAnnotation': { - 'type': 'ReservedTypeAnnotation', - 'name': 'RootTag' - } - } - ], - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - } - } - }, - { - 'name': 'hotspotUpdate', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'params': [ - { - 'name': 'x', - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'y', - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ], - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - } - } - }, - { - 'name': 'scrollTo', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'params': [ - { - 'name': 'x', - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'y', - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'z', - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'animated', - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ], - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - } - } - } - ] - } - } - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture COMMANDS_EVENTS_TYPES_EXPORTED 1`] = ` -"{ - 'modules': { - 'Module': { - 'type': 'Component', - 'components': { - 'Module': { - 'extendsProps': [ - { - 'type': 'ReactNativeBuiltInType', - 'knownTypeName': 'ReactNativeCoreViewProps' - } - ], - 'events': [ - { - 'name': 'onBubblingEventDefinedInline', - 'optional': false, - 'bubblingType': 'bubble', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - }, - { - 'name': 'onBubblingEventDefinedInlineWithPaperName', - 'optional': false, - 'bubblingType': 'bubble', - 'paperTopLevelNameDeprecated': 'paperBubblingEventDefinedInlineWithPaperName', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - }, - { - 'name': 'onDirectEventDefinedInline', - 'optional': false, - 'bubblingType': 'direct', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - }, - { - 'name': 'onDirectEventDefinedInlineWithPaperName', - 'optional': false, - 'bubblingType': 'direct', - 'paperTopLevelNameDeprecated': 'paperDirectEventDefinedInlineWithPaperName', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - } - ], - 'props': [], - 'commands': [ - { - 'name': 'scrollTo', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'params': [ - { - 'name': 'y', - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'animated', - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ], - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - } - } - } - ] - } - } - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture COMMANDS_WITH_EXTERNAL_TYPES 1`] = ` -"{ - 'modules': { - 'Module': { - 'type': 'Component', - 'components': { - 'Module': { - 'extendsProps': [ - { - 'type': 'ReactNativeBuiltInType', - 'knownTypeName': 'ReactNativeCoreViewProps' - } - ], - 'events': [], - 'props': [], - 'commands': [ - { - 'name': 'scrollTo', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'params': [ - { - 'name': 'y', - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'animated', - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ], - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - } - } - } - ] - } - } - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture EVENTS_DEFINED_AS_NULL_INLINE 1`] = ` -"{ - 'modules': { - 'Module': { - 'type': 'Component', - 'components': { - 'Module': { - 'extendsProps': [ - { - 'type': 'ReactNativeBuiltInType', - 'knownTypeName': 'ReactNativeCoreViewProps' - } - ], - 'events': [ - { - 'name': 'onDirectEventDefinedInlineNull', - 'optional': false, - 'bubblingType': 'direct', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [] - } - } - }, - { - 'name': 'onDirectEventDefinedInlineNullOptionalKey', - 'optional': true, - 'bubblingType': 'direct', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [] - } - } - }, - { - 'name': 'onDirectEventDefinedInlineNullOptionalValue', - 'optional': true, - 'bubblingType': 'direct', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [] - } - } - }, - { - 'name': 'onDirectEventDefinedInlineNullOptionalBoth', - 'optional': true, - 'bubblingType': 'direct', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [] - } - } - }, - { - 'name': 'onDirectEventDefinedInlineNullWithPaperName', - 'optional': true, - 'bubblingType': 'direct', - 'paperTopLevelNameDeprecated': 'paperDirectEventDefinedInlineNullWithPaperName', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [] - } - } - }, - { - 'name': 'onBubblingEventDefinedInlineNull', - 'optional': false, - 'bubblingType': 'bubble', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [] - } - } - }, - { - 'name': 'onBubblingEventDefinedInlineNullOptionalKey', - 'optional': true, - 'bubblingType': 'bubble', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [] - } - } - }, - { - 'name': 'onBubblingEventDefinedInlineNullOptionalValue', - 'optional': true, - 'bubblingType': 'bubble', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [] - } - } - }, - { - 'name': 'onBubblingEventDefinedInlineNullOptionalBoth', - 'optional': true, - 'bubblingType': 'bubble', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [] - } - } - }, - { - 'name': 'onBubblingEventDefinedInlineNullWithPaperName', - 'optional': true, - 'bubblingType': 'bubble', - 'paperTopLevelNameDeprecated': 'paperBubblingEventDefinedInlineNullWithPaperName', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [] - } - } - } - ], - 'props': [], - 'commands': [] - } - } - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture EVENTS_DEFINED_INLINE_WITH_ALL_TYPES 1`] = ` -"{ - 'modules': { - 'Module': { - 'type': 'Component', - 'components': { - 'Module': { - 'extendsProps': [ - { - 'type': 'ReactNativeBuiltInType', - 'knownTypeName': 'ReactNativeCoreViewProps' - } - ], - 'events': [ - { - 'name': 'onDirectEventDefinedInline', - 'optional': false, - 'bubblingType': 'direct', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - }, - { - 'name': 'onDirectEventDefinedInlineOptionalKey', - 'optional': true, - 'bubblingType': 'direct', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - }, - { - 'name': 'onDirectEventDefinedInlineOptionalValue', - 'optional': true, - 'bubblingType': 'direct', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - }, - { - 'name': 'onDirectEventDefinedInlineOptionalBoth', - 'optional': true, - 'bubblingType': 'direct', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - }, - { - 'name': 'onDirectEventDefinedInlineWithPaperName', - 'optional': true, - 'bubblingType': 'direct', - 'paperTopLevelNameDeprecated': 'paperDirectEventDefinedInlineWithPaperName', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - }, - { - 'name': 'onBubblingEventDefinedInline', - 'optional': false, - 'bubblingType': 'bubble', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - }, - { - 'name': 'onBubblingEventDefinedInlineOptionalKey', - 'optional': true, - 'bubblingType': 'bubble', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - }, - { - 'name': 'onBubblingEventDefinedInlineOptionalValue', - 'optional': true, - 'bubblingType': 'bubble', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - }, - { - 'name': 'onBubblingEventDefinedInlineOptionalBoth', - 'optional': true, - 'bubblingType': 'bubble', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - }, - { - 'name': 'onBubblingEventDefinedInlineWithPaperName', - 'optional': true, - 'bubblingType': 'bubble', - 'paperTopLevelNameDeprecated': 'paperBubblingEventDefinedInlineWithPaperName', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - } - ], - 'props': [], - 'commands': [] - } - } - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture NO_PROPS_EVENTS_ONLY_DEPRECATED_VIEW_CONFIG_NAME_OPTION 1`] = ` -"{ - 'modules': { - 'Module': { - 'type': 'Component', - 'components': { - 'Module': { - 'deprecatedViewConfigName': 'DeprecateModuleName', - 'extendsProps': [ - { - 'type': 'ReactNativeBuiltInType', - 'knownTypeName': 'ReactNativeCoreViewProps' - } - ], - 'events': [], - 'props': [], - 'commands': [] - } - } - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture OBJECT_PROP_TYPES_NO_EVENTS 1`] = ` -"{ - 'modules': { - 'Module': { - 'type': 'Component', - 'components': { - 'Module': { - 'extendsProps': [ - { - 'type': 'ReactNativeBuiltInType', - 'knownTypeName': 'ReactNativeCoreViewProps' - } - ], - 'events': [], - 'props': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation', - 'default': false - } - } - ] - } - }, - { - 'name': 'boolean_optional', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation', - 'default': false - } - } - ] - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - }, - { - 'name': 'string_optional', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': '' - } - } - ] - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation', - 'default': 0 - } - } - ] - } - }, - { - 'name': 'double_optional', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation', - 'default': 0 - } - } - ] - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation', - 'default': 0 - } - } - ] - } - }, - { - 'name': 'float_optional', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation', - 'default': 0 - } - } - ] - } - }, - { - 'name': 'int_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation', - 'default': 0 - } - } - ] - } - }, - { - 'name': 'int_optional', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation', - 'default': 0 - } - } - ] - } - }, - { - 'name': 'enum_optional', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringEnumTypeAnnotation', - 'default': 'small', - 'options': [ - 'small', - 'large' - ] - } - } - } - ] - } - }, - { - 'name': 'image_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ImageSourcePrimitive' - } - } - ] - } - }, - { - 'name': 'image_optional_key', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ImageSourcePrimitive' - } - } - ] - } - }, - { - 'name': 'image_optional_value', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ImageSourcePrimitive' - } - } - ] - } - }, - { - 'name': 'image_optional_both', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ImageSourcePrimitive' - } - } - ] - } - }, - { - 'name': 'color_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - ] - } - }, - { - 'name': 'color_optional_key', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - ] - } - }, - { - 'name': 'color_optional_value', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - ] - } - }, - { - 'name': 'color_optional_both', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - ] - } - }, - { - 'name': 'processed_color_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - ] - } - }, - { - 'name': 'processed_color_optional_key', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - ] - } - }, - { - 'name': 'processed_color_optional_value', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - ] - } - }, - { - 'name': 'processed_color_optional_both', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'ColorPrimitive' - } - } - ] - } - }, - { - 'name': 'point_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'PointPrimitive' - } - } - ] - } - }, - { - 'name': 'point_optional_key', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'PointPrimitive' - } - } - ] - } - }, - { - 'name': 'point_optional_value', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'PointPrimitive' - } - } - ] - } - }, - { - 'name': 'point_optional_both', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'PointPrimitive' - } - } - ] - } - }, - { - 'name': 'insets_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'EdgeInsetsPrimitive' - } - } - ] - } - }, - { - 'name': 'insets_optional_key', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'EdgeInsetsPrimitive' - } - } - ] - } - }, - { - 'name': 'insets_optional_value', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'EdgeInsetsPrimitive' - } - } - ] - } - }, - { - 'name': 'insets_optional_both', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ReservedPropTypeAnnotation', - 'name': 'EdgeInsetsPrimitive' - } - } - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'nestedProp', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'nestedProp', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'nestedProp', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'nestedProp', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - ] - } - } - ], - 'commands': [] - } - } - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture ONE_OF_EACH_PROP_EVENT_DEFAULT_AND_OPTIONS 1`] = ` -"{ - 'modules': { - 'Module': { - 'type': 'Component', - 'components': { - 'Module': { - 'interfaceOnly': true, - 'paperComponentName': 'RCTModule', - 'extendsProps': [ - { - 'type': 'ReactNativeBuiltInType', - 'knownTypeName': 'ReactNativeCoreViewProps' - } - ], - 'events': [ - { - 'name': 'onDirectEventDefinedInlineNull', - 'optional': false, - 'bubblingType': 'direct', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [] - } - } - }, - { - 'name': 'onBubblingEventDefinedInlineNull', - 'optional': false, - 'bubblingType': 'bubble', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [] - } - } - } - ], - 'props': [ - { - 'name': 'boolean_default_true_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation', - 'default': true - } - } - ], - 'commands': [] - } - } - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture ONE_OF_EACH_PROP_EVENT_DEFAULT_AND_OPTIONS_NO_CAST 1`] = ` -"{ - 'modules': { - 'Module': { - 'type': 'Component', - 'components': { - 'Module': { - 'interfaceOnly': true, - 'excludedPlatforms': [ - 'android' - ], - 'paperComponentName': 'RCTModule', - 'extendsProps': [ - { - 'type': 'ReactNativeBuiltInType', - 'knownTypeName': 'ReactNativeCoreViewProps' - } - ], - 'events': [ - { - 'name': 'onDirectEventDefinedInlineNull', - 'optional': false, - 'bubblingType': 'direct', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [] - } - } - }, - { - 'name': 'onBubblingEventDefinedInlineNull', - 'optional': false, - 'bubblingType': 'bubble', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [] - } - } - } - ], - 'props': [ - { - 'name': 'boolean_default_true_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation', - 'default': true - } - } - ], - 'commands': [] - } - } - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture PROPS_ALIASED_LOCALLY 1`] = ` -"{ - 'modules': { - 'Module': { - 'type': 'Component', - 'components': { - 'Module': { - 'extendsProps': [ - { - 'type': 'ReactNativeBuiltInType', - 'knownTypeName': 'ReactNativeCoreViewProps' - } - ], - 'events': [], - 'props': [ - { - 'name': 'otherStringProp', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - }, - { - 'name': 'isEnabled', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation', - 'default': false - } - }, - { - 'name': 'label', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - }, - { - 'name': 'localType', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'otherStringProp', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - }, - { - 'name': 'isEnabled', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation', - 'default': false - } - }, - { - 'name': 'label', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - }, - { - 'name': 'localArr', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'otherStringProp', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - }, - { - 'name': 'isEnabled', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation', - 'default': false - } - }, - { - 'name': 'label', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - } - ] - } - } - } - ], - 'commands': [] - } - } - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture PROPS_AND_EVENTS_TYPES_EXPORTED 1`] = ` -"{ - 'modules': { - 'Module': { - 'type': 'Component', - 'components': { - 'Module': { - 'extendsProps': [ - { - 'type': 'ReactNativeBuiltInType', - 'knownTypeName': 'ReactNativeCoreViewProps' - } - ], - 'events': [ - { - 'name': 'onBubblingEventDefinedInline', - 'optional': false, - 'bubblingType': 'bubble', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - }, - { - 'name': 'onBubblingEventDefinedInlineWithPaperName', - 'optional': false, - 'bubblingType': 'bubble', - 'paperTopLevelNameDeprecated': 'paperBubblingEventDefinedInlineWithPaperName', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - }, - { - 'name': 'onDirectEventDefinedInline', - 'optional': false, - 'bubblingType': 'direct', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - }, - { - 'name': 'onDirectEventDefinedInlineWithPaperName', - 'optional': false, - 'bubblingType': 'direct', - 'paperTopLevelNameDeprecated': 'paperDirectEventDefinedInlineWithPaperName', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'boolean_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'string_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'string_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'double_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'float_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'enum_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'enum_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringEnumTypeAnnotation', - 'options': [ - 'small', - 'large' - ] - } - }, - { - 'name': 'object_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_required_nested_2_layers', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'object_optional_nested_1_layer', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'double_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'DoubleTypeAnnotation' - } - }, - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - }, - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'object_readonly_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'boolean_required', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'string_optional_key', - 'optional': true, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'float_optional_value', - 'optional': true, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'object_readonly_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'int32_optional_both', - 'optional': true, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - } - ] - } - } - } - ], - 'props': [], - 'commands': [] - } - } - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture PROPS_AND_EVENTS_WITH_INTERFACES 1`] = ` -"{ - 'modules': { - 'Module': { - 'type': 'Component', - 'components': { - 'Module': { - 'interfaceOnly': true, - 'paperComponentName': 'RCTModule', - 'extendsProps': [ - { - 'type': 'ReactNativeBuiltInType', - 'knownTypeName': 'ReactNativeCoreViewProps' - } - ], - 'events': [ - { - 'name': 'onDirect', - 'optional': false, - 'bubblingType': 'direct', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'x', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'y', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'z', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - } - }, - { - 'name': 'onBubbling', - 'optional': false, - 'bubblingType': 'bubble', - 'typeAnnotation': { - 'type': 'EventTypeAnnotation', - 'argument': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'x', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'y', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - }, - { - 'name': 'z', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - } - } - ], - 'props': [ - { - 'name': 'ordinary_prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'x', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - }, - { - 'name': 'y', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation', - 'default': 0 - } - }, - { - 'name': 'z', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation', - 'default': false - } - } - ] - } - }, - { - 'name': 'readonly_prop', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'x', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - }, - { - 'name': 'y', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation', - 'default': 0 - } - }, - { - 'name': 'z', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation', - 'default': false - } - } - ] - } - }, - { - 'name': 'ordinary_array_prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'x', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - }, - { - 'name': 'y', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation', - 'default': 0 - } - }, - { - 'name': 'z', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation', - 'default': false - } - } - ] - } - } - }, - { - 'name': 'readonly_array_prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'x', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - }, - { - 'name': 'y', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation', - 'default': 0 - } - }, - { - 'name': 'z', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation', - 'default': false - } - } - ] - } - } - }, - { - 'name': 'ordinary_nested_array_prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'x', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - }, - { - 'name': 'y', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation', - 'default': 0 - } - }, - { - 'name': 'z', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation', - 'default': false - } - } - ] - } - } - } - }, - { - 'name': 'readonly_nested_array_prop', - 'optional': true, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'x', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - }, - { - 'name': 'y', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation', - 'default': 0 - } - }, - { - 'name': 'z', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation', - 'default': false - } - } - ] - } - } - } - } - ], - 'commands': [] - } - } - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture PROPS_AS_EXTERNAL_TYPES 1`] = ` -"{ - 'modules': { - 'Module': { - 'type': 'Component', - 'components': { - 'Module': { - 'extendsProps': [], - 'events': [], - 'props': [ - { - 'name': 'disable', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation', - 'default': null - } - }, - { - 'name': 'array', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - } - ], - 'commands': [] - } - } - } - } -}" -`; diff --git a/packages/react-native-codegen/src/parsers/typescript/components/__tests__/typescript-component-parser-test.js b/packages/react-native-codegen/src/parsers/typescript/components/__tests__/typescript-component-parser-test.js deleted file mode 100644 index 19a49a6b8ad2..000000000000 --- a/packages/react-native-codegen/src/parsers/typescript/components/__tests__/typescript-component-parser-test.js +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const TypeScriptParser = require('../../index.js'); -const {parseFile} = require('../../../utils.js'); -const fixtures = require('../__test_fixtures__/fixtures.js'); -const failureFixtures = require('../__test_fixtures__/failures.js'); -jest.mock('fs', () => ({ - readFileSync: filename => { - // Jest in the OSS does not allow to capture variables in closures. - // Therefore, we have to bring the variables inside the closure. - // see: https://github.com/facebook/jest/issues/2567 - const readFileFixtures = require('../__test_fixtures__/fixtures.js'); - const readFileFailureFixtures = require('../__test_fixtures__/failures.js'); - return readFileFixtures[filename] || readFileFailureFixtures[filename]; - }, -})); - -describe('RN Codegen TypeScript Parser', () => { - Object.keys(fixtures) - .sort() - .forEach(fixtureName => { - it(`can generate fixture ${fixtureName}`, () => { - const schema = parseFile(fixtureName, TypeScriptParser.buildSchema); - const serializedSchema = JSON.stringify(schema, null, 2).replace( - /"/g, - "'", - ); - expect(serializedSchema).toMatchSnapshot(); - }); - }); - - Object.keys(failureFixtures) - .sort() - .forEach(fixtureName => { - it(`Fails with error message ${fixtureName}`, () => { - expect(() => { - parseFile(fixtureName, TypeScriptParser.buildSchema); - }).toThrowErrorMatchingSnapshot(); - }); - }); -}); diff --git a/packages/react-native-codegen/src/parsers/typescript/components/commands.js b/packages/react-native-codegen/src/parsers/typescript/components/commands.js deleted file mode 100644 index 23e300c39e2f..000000000000 --- a/packages/react-native-codegen/src/parsers/typescript/components/commands.js +++ /dev/null @@ -1,128 +0,0 @@ -/** - * 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 - */ - -'use strict'; - -import type { - NamedShape, - CommandTypeAnnotation, -} from '../../../CodegenSchema.js'; -import type {TypeDeclarationMap} from '../../utils'; -const {parseTopLevelType} = require('../parseTopLevelType'); - -type EventTypeAST = Object; - -function buildCommandSchema(property: EventTypeAST, types: TypeDeclarationMap) { - const topLevelType = parseTopLevelType( - property.typeAnnotation.typeAnnotation, - types, - ); - const name = property.key.name; - const optional = property.optional || topLevelType.optional; - const value = topLevelType.type; - const firstParam = value.parameters[0].typeAnnotation; - - if ( - !( - firstParam.typeAnnotation != null && - firstParam.typeAnnotation.type === 'TSTypeReference' && - firstParam.typeAnnotation.typeName.left?.name === 'React' && - firstParam.typeAnnotation.typeName.right?.name === 'ElementRef' - ) - ) { - throw new Error( - `The first argument of method ${name} must be of type React.ElementRef<>`, - ); - } - - const params = value.parameters.slice(1).map(param => { - const paramName = param.name; - const paramValue = parseTopLevelType( - param.typeAnnotation.typeAnnotation, - types, - ).type; - - const type = - paramValue.type === 'TSTypeReference' - ? paramValue.typeName.name - : paramValue.type; - let returnType; - - switch (type) { - case 'RootTag': - returnType = { - type: 'ReservedTypeAnnotation', - name: 'RootTag', - }; - break; - case 'TSBooleanKeyword': - returnType = { - type: 'BooleanTypeAnnotation', - }; - break; - case 'Int32': - returnType = { - type: 'Int32TypeAnnotation', - }; - break; - case 'Double': - returnType = { - type: 'DoubleTypeAnnotation', - }; - break; - case 'Float': - returnType = { - type: 'FloatTypeAnnotation', - }; - break; - case 'TSStringKeyword': - returnType = { - type: 'StringTypeAnnotation', - }; - break; - default: - (type: empty); - throw new Error( - `Unsupported param type for method "${name}", param "${paramName}". Found ${type}`, - ); - } - - return { - name: paramName, - typeAnnotation: returnType, - }; - }); - - return { - name, - optional, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - params, - returnTypeAnnotation: { - type: 'VoidTypeAnnotation', - }, - }, - }; -} - -function getCommands( - commandTypeAST: $ReadOnlyArray, - types: TypeDeclarationMap, -): $ReadOnlyArray> { - return commandTypeAST - .filter(property => property.type === 'TSPropertySignature') - .map(property => buildCommandSchema(property, types)) - .filter(Boolean); -} - -module.exports = { - getCommands, -}; diff --git a/packages/react-native-codegen/src/parsers/typescript/components/componentsUtils.js b/packages/react-native-codegen/src/parsers/typescript/components/componentsUtils.js deleted file mode 100644 index 0d84786df8f2..000000000000 --- a/packages/react-native-codegen/src/parsers/typescript/components/componentsUtils.js +++ /dev/null @@ -1,528 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; -import type {ASTNode} from '../utils'; -import type {NamedShape} from '../../../CodegenSchema.js'; -const {parseTopLevelType} = require('../parseTopLevelType'); -import type {TypeDeclarationMap} from '../../utils'; - -function getProperties( - typeName: string, - types: TypeDeclarationMap, -): $FlowFixMe { - const alias = types[typeName]; - if (!alias) { - throw new Error( - `Failed to find definition for "${typeName}", please check that you have a valid codegen typescript file`, - ); - } - const aliasKind = - alias.type === 'TSInterfaceDeclaration' ? 'interface' : 'type'; - - try { - if (aliasKind === 'interface') { - return [...(alias.extends ?? []), ...alias.body.body]; - } - - return ( - alias.typeAnnotation.members || - alias.typeAnnotation.typeParameters.params[0].members || - alias.typeAnnotation.typeParameters.params - ); - } catch (e) { - throw new Error( - `Failed to find ${aliasKind} definition for "${typeName}", please check that you have a valid codegen typescript file`, - ); - } -} - -function getUnionOfLiterals( - name: string, - forArray: boolean, - elementTypes: $FlowFixMe[], - defaultValue: $FlowFixMe | void, - types: TypeDeclarationMap, -) { - elementTypes.reduce((lastType, currType) => { - const lastFlattenedType = - lastType && lastType.type === 'TSLiteralType' - ? lastType.literal.type - : lastType.type; - const currFlattenedType = - currType.type === 'TSLiteralType' ? currType.literal.type : currType.type; - - if (lastFlattenedType && currFlattenedType !== lastFlattenedType) { - throw new Error(`Mixed types are not supported (see "${name}")`); - } - return currType; - }); - - if (defaultValue === undefined) { - throw new Error(`A default enum value is required for "${name}"`); - } - - const unionType = elementTypes[0].type; - if ( - unionType === 'TSLiteralType' && - elementTypes[0].literal?.type === 'StringLiteral' - ) { - return { - type: 'StringEnumTypeAnnotation', - default: (defaultValue: string), - options: elementTypes.map(option => option.literal.value), - }; - } else if ( - unionType === 'TSLiteralType' && - elementTypes[0].literal?.type === 'NumericLiteral' - ) { - if (forArray) { - throw new Error(`Arrays of int enums are not supported (see: "${name}")`); - } else { - return { - type: 'Int32EnumTypeAnnotation', - default: (defaultValue: number), - options: elementTypes.map(option => option.literal.value), - }; - } - } else { - throw new Error( - `Unsupported union type for "${name}", received "${ - unionType === 'TSLiteralType' - ? elementTypes[0].literal?.type - : unionType - }"`, - ); - } -} - -function detectArrayType( - name: string, - typeAnnotation: $FlowFixMe | ASTNode, - defaultValue: $FlowFixMe | void, - types: TypeDeclarationMap, - buildSchema: (property: PropAST, types: TypeDeclarationMap) => ?NamedShape, -): $FlowFixMe { - // Covers: readonly T[] - if ( - typeAnnotation.type === 'TSTypeOperator' && - typeAnnotation.operator === 'readonly' && - typeAnnotation.typeAnnotation.type === 'TSArrayType' - ) { - return { - type: 'ArrayTypeAnnotation', - elementType: getTypeAnnotationForArray( - name, - typeAnnotation.typeAnnotation.elementType, - defaultValue, - types, - buildSchema, - ), - }; - } - - // Covers: T[] - if (typeAnnotation.type === 'TSArrayType') { - return { - type: 'ArrayTypeAnnotation', - elementType: getTypeAnnotationForArray( - name, - typeAnnotation.elementType, - defaultValue, - types, - buildSchema, - ), - }; - } - - // Covers: Array and ReadonlyArray - if ( - typeAnnotation.type === 'TSTypeReference' && - (typeAnnotation.typeName.name === 'ReadonlyArray' || - typeAnnotation.typeName.name === 'Array') - ) { - return { - type: 'ArrayTypeAnnotation', - elementType: getTypeAnnotationForArray( - name, - typeAnnotation.typeParameters.params[0], - defaultValue, - types, - buildSchema, - ), - }; - } - - return null; -} - -function getTypeAnnotationForArray( - name: string, - typeAnnotation: $FlowFixMe, - defaultValue: $FlowFixMe | void, - types: TypeDeclarationMap, - buildSchema: (property: PropAST, types: TypeDeclarationMap) => ?NamedShape, -): $FlowFixMe { - // unpack WithDefault, (T) or T|U - const topLevelType = parseTopLevelType(typeAnnotation, types); - if (topLevelType.defaultValue !== undefined) { - throw new Error( - 'Nested optionals such as "ReadonlyArray" are not supported, please declare optionals at the top level of value definitions as in "ReadonlyArray | null | undefined"', - ); - } - if (topLevelType.optional) { - throw new Error( - 'Nested optionals such as "ReadonlyArray" are not supported, please declare optionals at the top level of value definitions as in "ReadonlyArray | null | undefined"', - ); - } - - const extractedTypeAnnotation = topLevelType.type; - const arrayType = detectArrayType( - name, - extractedTypeAnnotation, - defaultValue, - types, - buildSchema, - ); - if (arrayType) { - if (arrayType.elementType.type !== 'ObjectTypeAnnotation') { - throw new Error( - `Only array of array of object is supported for "${name}".`, - ); - } - return arrayType; - } - - const type = - extractedTypeAnnotation.elementType === 'TSTypeReference' - ? extractedTypeAnnotation.elementType.typeName.name - : extractedTypeAnnotation.elementType?.type || - extractedTypeAnnotation.typeName?.name || - extractedTypeAnnotation.type; - - switch (type) { - case 'TSTypeLiteral': - case 'TSInterfaceDeclaration': { - const rawProperties = - type === 'TSInterfaceDeclaration' - ? [extractedTypeAnnotation] - : extractedTypeAnnotation.members; - if (rawProperties === undefined) { - throw new Error(type); - } - return { - type: 'ObjectTypeAnnotation', - properties: flattenProperties(rawProperties, types) - .map(prop => buildSchema(prop, types)) - .filter(Boolean), - }; - } - case 'TSNumberKeyword': - return { - type: 'FloatTypeAnnotation', - }; - case 'ImageSource': - return { - type: 'ReservedPropTypeAnnotation', - name: 'ImageSourcePrimitive', - }; - case 'ImageRequest': - return { - type: 'ReservedPropTypeAnnotation', - name: 'ImageRequestPrimitive', - }; - case 'ColorValue': - case 'ProcessedColorValue': - return { - type: 'ReservedPropTypeAnnotation', - name: 'ColorPrimitive', - }; - case 'PointValue': - return { - type: 'ReservedPropTypeAnnotation', - name: 'PointPrimitive', - }; - case 'EdgeInsetsValue': - return { - type: 'ReservedPropTypeAnnotation', - name: 'EdgeInsetsPrimitive', - }; - case 'Stringish': - return { - type: 'StringTypeAnnotation', - }; - case 'Int32': - return { - type: 'Int32TypeAnnotation', - }; - case 'Double': - return { - type: 'DoubleTypeAnnotation', - }; - case 'Float': - return { - type: 'FloatTypeAnnotation', - }; - case 'TSBooleanKeyword': - return { - type: 'BooleanTypeAnnotation', - }; - case 'TSStringKeyword': - return { - type: 'StringTypeAnnotation', - }; - case 'TSUnionType': - return getUnionOfLiterals( - name, - true, - extractedTypeAnnotation.types, - defaultValue, - types, - ); - default: - (type: empty); - throw new Error(`Unknown prop type for "${name}": ${type}`); - } -} - -function getTypeAnnotation( - name: string, - annotation: $FlowFixMe | ASTNode, - defaultValue: $FlowFixMe | void, - types: TypeDeclarationMap, - buildSchema: (property: PropAST, types: TypeDeclarationMap) => ?NamedShape, -): $FlowFixMe { - // unpack WithDefault, (T) or T|U - const topLevelType = parseTopLevelType(annotation, types); - const typeAnnotation = topLevelType.type; - const arrayType = detectArrayType( - name, - typeAnnotation, - defaultValue, - types, - buildSchema, - ); - if (arrayType) { - return arrayType; - } - - const type = - typeAnnotation.type === 'TSTypeReference' || - typeAnnotation.type === 'TSTypeAliasDeclaration' - ? typeAnnotation.typeName.name - : typeAnnotation.type; - - switch (type) { - case 'TSTypeLiteral': - case 'TSInterfaceDeclaration': { - const rawProperties = - type === 'TSInterfaceDeclaration' - ? [typeAnnotation] - : typeAnnotation.members; - const flattenedProperties = flattenProperties(rawProperties, types); - const properties = flattenedProperties - .map(prop => buildSchema(prop, types)) - .filter(Boolean); - - return { - type: 'ObjectTypeAnnotation', - properties, - }; - } - case 'ImageSource': - return { - type: 'ReservedPropTypeAnnotation', - name: 'ImageSourcePrimitive', - }; - case 'ImageRequest': - return { - type: 'ReservedPropTypeAnnotation', - name: 'ImageRequestPrimitive', - }; - case 'ColorValue': - case 'ProcessedColorValue': - return { - type: 'ReservedPropTypeAnnotation', - name: 'ColorPrimitive', - }; - case 'ColorArrayValue': - return { - type: 'ArrayTypeAnnotation', - elementType: { - type: 'ReservedPropTypeAnnotation', - name: 'ColorPrimitive', - }, - }; - case 'PointValue': - return { - type: 'ReservedPropTypeAnnotation', - name: 'PointPrimitive', - }; - case 'EdgeInsetsValue': - return { - type: 'ReservedPropTypeAnnotation', - name: 'EdgeInsetsPrimitive', - }; - case 'Int32': - return { - type: 'Int32TypeAnnotation', - default: ((defaultValue ? defaultValue : 0): number), - }; - case 'Double': - return { - type: 'DoubleTypeAnnotation', - default: ((defaultValue ? defaultValue : 0): number), - }; - case 'Float': - return { - type: 'FloatTypeAnnotation', - default: ((defaultValue === null - ? null - : defaultValue - ? defaultValue - : 0): number | null), - }; - case 'TSBooleanKeyword': - return { - type: 'BooleanTypeAnnotation', - default: defaultValue === null ? null : !!defaultValue, - }; - case 'TSStringKeyword': - return { - type: 'StringTypeAnnotation', - default: ((defaultValue === undefined ? null : defaultValue): - | string - | null), - }; - case 'Stringish': - return { - type: 'StringTypeAnnotation', - default: ((defaultValue === undefined ? null : defaultValue): - | string - | null), - }; - case 'TSNumberKeyword': - throw new Error( - `Cannot use "${type}" type annotation for "${name}": must use a specific numeric type like Int32, Double, or Float`, - ); - case 'TSUnionType': - return getUnionOfLiterals( - name, - false, - typeAnnotation.types, - defaultValue, - types, - ); - default: - (type: empty); - throw new Error(`Unknown prop type for "${name}": "${type}"`); - } -} - -type SchemaInfo = { - name: string, - optional: boolean, - typeAnnotation: $FlowFixMe, - defaultValue: $FlowFixMe, -}; - -function getSchemaInfo( - property: PropAST, - types: TypeDeclarationMap, -): SchemaInfo { - // unpack WithDefault, (T) or T|U - const topLevelType = parseTopLevelType( - property.typeAnnotation.typeAnnotation, - types, - ); - - const name = property.key.name; - - if (!property.optional && topLevelType.defaultValue !== undefined) { - throw new Error( - `key ${name} must be optional if used with WithDefault<> annotation`, - ); - } - - return { - name, - optional: property.optional || topLevelType.optional, - typeAnnotation: topLevelType.type, - defaultValue: topLevelType.defaultValue, - }; -} - -// $FlowFixMe[unclear-type] TODO(T108222691): Use flow-types for @babel/parser -type PropAST = Object; - -function verifyPropNotAlreadyDefined( - props: $ReadOnlyArray, - needleProp: PropAST, -) { - const propName = needleProp.key.name; - const foundProp = props.some(prop => prop.key.name === propName); - if (foundProp) { - throw new Error(`A prop was already defined with the name ${propName}`); - } -} - -function flattenProperties( - typeDefinition: $ReadOnlyArray, - types: TypeDeclarationMap, -): $ReadOnlyArray { - return typeDefinition - .map(property => { - if (property.type === 'TSPropertySignature') { - return property; - } else if (property.type === 'TSTypeReference') { - return flattenProperties( - getProperties(property.typeName.name, types), - types, - ); - } else if ( - property.type === 'TSExpressionWithTypeArguments' || - property.type === 'TSInterfaceHeritage' - ) { - return flattenProperties( - getProperties(property.expression.name, types), - types, - ); - } else if (property.type === 'TSTypeLiteral') { - return flattenProperties(property.members, types); - } else if (property.type === 'TSInterfaceDeclaration') { - return flattenProperties(getProperties(property.id.name, types), types); - } else { - throw new Error( - `${property.type} is not a supported object literal type.`, - ); - } - }) - .filter(Boolean) - .reduce((acc, item) => { - if (Array.isArray(item)) { - item.forEach(prop => { - verifyPropNotAlreadyDefined(acc, prop); - }); - return acc.concat(item); - } else { - verifyPropNotAlreadyDefined(acc, item); - acc.push(item); - return acc; - } - }, []) - .filter(Boolean); -} - -module.exports = { - getProperties, - getSchemaInfo, - getTypeAnnotation, - flattenProperties, -}; diff --git a/packages/react-native-codegen/src/parsers/typescript/components/events.js b/packages/react-native-codegen/src/parsers/typescript/components/events.js deleted file mode 100644 index 0fbfb4b71f44..000000000000 --- a/packages/react-native-codegen/src/parsers/typescript/components/events.js +++ /dev/null @@ -1,258 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type { - EventTypeShape, - NamedShape, - EventTypeAnnotation, -} from '../../../CodegenSchema.js'; -import type {TypeDeclarationMap} from '../../utils'; -const {flattenProperties} = require('./componentsUtils'); -const {parseTopLevelType} = require('../parseTopLevelType'); - -function getPropertyType( - /* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's - * LTI update could not be added via codemod */ - name, - optionalProperty: boolean, - /* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's - * LTI update could not be added via codemod */ - annotation, -): NamedShape { - const topLevelType = parseTopLevelType(annotation); - const typeAnnotation = topLevelType.type; - const optional = optionalProperty || topLevelType.optional; - const type = - typeAnnotation.type === 'TSTypeReference' - ? typeAnnotation.typeName.name - : typeAnnotation.type; - - switch (type) { - case 'TSBooleanKeyword': - return { - name, - optional, - typeAnnotation: { - type: 'BooleanTypeAnnotation', - }, - }; - case 'TSStringKeyword': - return { - name, - optional, - typeAnnotation: { - type: 'StringTypeAnnotation', - }, - }; - case 'Int32': - return { - name, - optional, - typeAnnotation: { - type: 'Int32TypeAnnotation', - }, - }; - case 'Double': - return { - name, - optional, - typeAnnotation: { - type: 'DoubleTypeAnnotation', - }, - }; - case 'Float': - return { - name, - optional, - typeAnnotation: { - type: 'FloatTypeAnnotation', - }, - }; - case 'TSTypeLiteral': - return { - name, - optional, - typeAnnotation: { - type: 'ObjectTypeAnnotation', - properties: typeAnnotation.members.map(buildPropertiesForEvent), - }, - }; - - case 'TSUnionType': - return { - name, - optional, - typeAnnotation: { - type: 'StringEnumTypeAnnotation', - options: typeAnnotation.types.map(option => option.literal.value), - }, - }; - default: - (type: empty); - throw new Error(`Unable to determine event type for "${name}": ${type}`); - } -} - -function findEventArgumentsAndType( - typeAnnotation: $FlowFixMe, - types: TypeDeclarationMap, - bubblingType: void | 'direct' | 'bubble', - paperName: ?$FlowFixMe, -) { - if (typeAnnotation.type === 'TSInterfaceDeclaration') { - return { - argumentProps: flattenProperties([typeAnnotation], types), - paperTopLevelNameDeprecated: paperName, - bubblingType, - }; - } - - if (typeAnnotation.type === 'TSTypeLiteral') { - return { - argumentProps: typeAnnotation.members, - paperTopLevelNameDeprecated: paperName, - bubblingType, - }; - } - - if (!typeAnnotation.typeName) { - throw new Error("typeAnnotation of event doesn't have a name"); - } - const name = typeAnnotation.typeName.name; - if (name === 'Readonly') { - return findEventArgumentsAndType( - typeAnnotation.typeParameters.params[0], - types, - bubblingType, - paperName, - ); - } else if (name === 'BubblingEventHandler' || name === 'DirectEventHandler') { - const eventType = name === 'BubblingEventHandler' ? 'bubble' : 'direct'; - const paperTopLevelNameDeprecated = - typeAnnotation.typeParameters.params.length > 1 - ? typeAnnotation.typeParameters.params[1].literal.value - : null; - - switch (typeAnnotation.typeParameters.params[0].type) { - case 'TSNullKeyword': - case 'TSUndefinedKeyword': - return { - argumentProps: [], - bubblingType: eventType, - paperTopLevelNameDeprecated, - }; - default: - return findEventArgumentsAndType( - typeAnnotation.typeParameters.params[0], - types, - eventType, - paperTopLevelNameDeprecated, - ); - } - } else if (types[name]) { - let elementType = types[name]; - if (elementType.type === 'TSTypeAliasDeclaration') { - elementType = elementType.typeAnnotation; - } - return findEventArgumentsAndType( - elementType, - types, - bubblingType, - paperName, - ); - } else { - return { - argumentProps: null, - bubblingType: null, - paperTopLevelNameDeprecated: null, - }; - } -} - -/* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's - * LTI update could not be added via codemod */ -function buildPropertiesForEvent(property): NamedShape { - const name = property.key.name; - const optional = property.optional || false; - let typeAnnotation = property.typeAnnotation.typeAnnotation; - - return getPropertyType(name, optional, typeAnnotation); -} - -/* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's - * LTI update could not be added via codemod */ -function getEventArgument(argumentProps, name: $FlowFixMe) { - return { - type: 'ObjectTypeAnnotation', - properties: argumentProps.map(buildPropertiesForEvent), - }; -} - -// $FlowFixMe[unclear-type] TODO(T108222691): Use flow-types for @babel/parser -type EventTypeAST = Object; - -function buildEventSchema( - types: TypeDeclarationMap, - property: EventTypeAST, -): EventTypeShape { - // unpack WithDefault, (T) or T|U - const topLevelType = parseTopLevelType( - property.typeAnnotation.typeAnnotation, - types, - ); - - const name = property.key.name; - const typeAnnotation = topLevelType.type; - const optional = property.optional || topLevelType.optional; - const {argumentProps, bubblingType, paperTopLevelNameDeprecated} = - findEventArgumentsAndType(typeAnnotation, types); - - if (!argumentProps) { - throw new Error(`Unable to determine event arguments for "${name}"`); - } else if (!bubblingType) { - throw new Error(`Unable to determine event bubbling type for "${name}"`); - } else { - if (paperTopLevelNameDeprecated != null) { - return { - name, - optional, - bubblingType, - paperTopLevelNameDeprecated, - typeAnnotation: { - type: 'EventTypeAnnotation', - argument: getEventArgument(argumentProps, name), - }, - }; - } - - return { - name, - optional, - bubblingType, - typeAnnotation: { - type: 'EventTypeAnnotation', - argument: getEventArgument(argumentProps, name), - }, - }; - } -} - -function getEvents( - eventTypeAST: $ReadOnlyArray, - types: TypeDeclarationMap, -): $ReadOnlyArray { - return eventTypeAST.map(property => buildEventSchema(types, property)); -} - -module.exports = { - getEvents, -}; diff --git a/packages/react-native-codegen/src/parsers/typescript/components/extends.js b/packages/react-native-codegen/src/parsers/typescript/components/extends.js deleted file mode 100644 index e9fda8c46ee7..000000000000 --- a/packages/react-native-codegen/src/parsers/typescript/components/extends.js +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {ExtendsPropsShape} from '../../../CodegenSchema.js'; -import type {TypeDeclarationMap} from '../../utils'; -const {parseTopLevelType} = require('../parseTopLevelType'); -const {flattenProperties} = require('./componentsUtils.js'); - -function extendsForProp(prop: PropsAST, types: TypeDeclarationMap) { - if (!prop.expression) { - console.log('null', prop); - } - const name = prop.expression.name; - - if (types[name] != null) { - // This type is locally defined in the file - return null; - } - - switch (name) { - case 'ViewProps': - return { - type: 'ReactNativeBuiltInType', - knownTypeName: 'ReactNativeCoreViewProps', - }; - default: { - throw new Error(`Unable to handle prop spread: ${name}`); - } - } -} - -function isEvent(typeAnnotation: $FlowFixMe): boolean { - if (typeAnnotation.type !== 'TSTypeReference') { - return false; - } - const eventNames = new Set(['BubblingEventHandler', 'DirectEventHandler']); - return eventNames.has(typeAnnotation.typeName.name); -} - -function isProp(name: string, typeAnnotation: $FlowFixMe): boolean { - if (typeAnnotation.type !== 'TSTypeReference') { - return true; - } - const isStyle = - name === 'style' && - typeAnnotation.type === 'GenericTypeAnnotation' && - typeAnnotation.typeName.name === 'ViewStyleProp'; - return !isStyle; -} - -// $FlowFixMe[unclear-type] TODO(T108222691): Use flow-types for @babel/parser -type PropsAST = Object; - -function categorizeProps( - typeDefinition: $ReadOnlyArray, - types: TypeDeclarationMap, - extendsProps: Array, - props: Array, - events: Array, -): void { - const remaining: Array = []; - for (const prop of typeDefinition) { - // find extends - if (prop.type === 'TSExpressionWithTypeArguments') { - const extend = extendsForProp(prop, types); - if (extend) { - extendsProps.push(extend); - continue; - } - } - - remaining.push(prop); - } - - // find events and props - for (const prop of flattenProperties(remaining, types)) { - if (prop.type === 'TSPropertySignature') { - const topLevelType = parseTopLevelType( - prop.typeAnnotation.typeAnnotation, - types, - ); - - if (isEvent(topLevelType.type)) { - events.push(prop); - } else if (isProp(prop.key.name, prop)) { - props.push(prop); - } - } - } -} - -module.exports = { - categorizeProps, -}; diff --git a/packages/react-native-codegen/src/parsers/typescript/components/index.js b/packages/react-native-codegen/src/parsers/typescript/components/index.js deleted file mode 100644 index 46cbba5dd505..000000000000 --- a/packages/react-native-codegen/src/parsers/typescript/components/index.js +++ /dev/null @@ -1,239 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; -import type {ExtendsPropsShape} from '../../../CodegenSchema.js'; -import type {TypeDeclarationMap} from '../../utils'; -import type {CommandOptions} from './options'; -import type {ComponentSchemaBuilderConfig} from './schema.js'; - -const {getTypes} = require('../utils'); -const {getCommands} = require('./commands'); -const {getEvents} = require('./events'); -const {categorizeProps} = require('./extends'); -const {getCommandOptions, getOptions} = require('./options'); -const {getProps} = require('./props'); -const {getProperties} = require('./componentsUtils.js'); - -/* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's - * LTI update could not be added via codemod */ -function findComponentConfig(ast) { - const foundConfigs = []; - - const defaultExports = ast.body.filter( - node => node.type === 'ExportDefaultDeclaration', - ); - - defaultExports.forEach(statement => { - let declaration = statement.declaration; - - // codegenNativeComponent can be nested inside a cast - // expression so we need to go one level deeper - if (declaration.type === 'TSAsExpression') { - declaration = declaration.expression; - } - - try { - if (declaration.callee.name === 'codegenNativeComponent') { - const typeArgumentParams = declaration.typeParameters.params; - const funcArgumentParams = declaration.arguments; - - const nativeComponentType: {[string]: string} = { - propsTypeName: typeArgumentParams[0].typeName.name, - componentName: funcArgumentParams[0].value, - }; - if (funcArgumentParams.length > 1) { - nativeComponentType.optionsExpression = funcArgumentParams[1]; - } - foundConfigs.push(nativeComponentType); - } - } catch (e) { - // ignore - } - }); - - if (foundConfigs.length === 0) { - throw new Error('Could not find component config for native component'); - } - if (foundConfigs.length > 1) { - throw new Error('Only one component is supported per file'); - } - - const foundConfig = foundConfigs[0]; - - const namedExports = ast.body.filter( - node => node.type === 'ExportNamedDeclaration', - ); - - const commandsTypeNames = namedExports - .map(statement => { - let callExpression; - let calleeName; - try { - callExpression = statement.declaration.declarations[0].init; - calleeName = callExpression.callee.name; - } catch (e) { - return; - } - - if (calleeName !== 'codegenNativeCommands') { - return; - } - - // const statement.declaration.declarations[0].init - if (callExpression.arguments.length !== 1) { - throw new Error( - 'codegenNativeCommands must be passed options including the supported commands', - ); - } - - const typeArgumentParam = callExpression.typeParameters.params[0]; - - if (typeArgumentParam.type !== 'TSTypeReference') { - throw new Error( - "codegenNativeCommands doesn't support inline definitions. Specify a file local type alias", - ); - } - - return { - commandTypeName: typeArgumentParam.typeName.name, - commandOptionsExpression: callExpression.arguments[0], - }; - }) - .filter(Boolean); - - if (commandsTypeNames.length > 1) { - throw new Error('codegenNativeCommands may only be called once in a file'); - } - - return { - ...foundConfig, - commandTypeName: - commandsTypeNames[0] == null - ? null - : commandsTypeNames[0].commandTypeName, - commandOptionsExpression: - commandsTypeNames[0] == null - ? null - : commandsTypeNames[0].commandOptionsExpression, - }; -} - -function getCommandProperties( - /* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's - * LTI update could not be added via codemod */ - commandTypeName, - types: TypeDeclarationMap, - commandOptions: ?CommandOptions, -) { - if (commandTypeName == null) { - return []; - } - - const typeAlias = types[commandTypeName]; - - if (typeAlias.type !== 'TSInterfaceDeclaration') { - throw new Error( - `The type argument for codegenNativeCommands must be an interface, received ${typeAlias.type}`, - ); - } - - let properties; - try { - properties = typeAlias.body.body; - } catch (e) { - throw new Error( - `Failed to find type definition for "${commandTypeName}", please check that you have a valid codegen typescript file`, - ); - } - - const typeScriptPropertyNames = properties - .map(property => property && property.key && property.key.name) - .filter(Boolean); - - if (commandOptions == null || commandOptions.supportedCommands == null) { - throw new Error( - 'codegenNativeCommands must be given an options object with supportedCommands array', - ); - } - - if ( - commandOptions.supportedCommands.length !== - typeScriptPropertyNames.length || - !commandOptions.supportedCommands.every(supportedCommand => - typeScriptPropertyNames.includes(supportedCommand), - ) - ) { - throw new Error( - `codegenNativeCommands expected the same supportedCommands specified in the ${commandTypeName} interface: ${typeScriptPropertyNames.join( - ', ', - )}`, - ); - } - - return properties; -} - -// $FlowFixMe[unclear-type] TODO(T108222691): Use flow-types for @babel/parser -type PropsAST = Object; - -// $FlowFixMe[signature-verification-failure] TODO(T108222691): Use flow-types for @babel/parser -/* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's - * LTI update could not be added via codemod */ -function buildComponentSchema(ast): ComponentSchemaBuilderConfig { - const { - componentName, - propsTypeName, - commandTypeName, - commandOptionsExpression, - optionsExpression, - } = findComponentConfig(ast); - - const types = getTypes(ast); - - const propProperties = getProperties(propsTypeName, types); - const commandOptions = getCommandOptions(commandOptionsExpression); - - const commandProperties = getCommandProperties( - commandTypeName, - types, - commandOptions, - ); - - const options = getOptions(optionsExpression); - - const extendsProps: Array = []; - const componentPropAsts: Array = []; - const componentEventAsts: Array = []; - categorizeProps( - propProperties, - types, - extendsProps, - componentPropAsts, - componentEventAsts, - ); - const props = getProps(componentPropAsts, types); - const events = getEvents(componentEventAsts, types); - const commands = getCommands(commandProperties, types); - - return { - filename: componentName, - componentName, - options, - extendsProps, - events, - props, - commands, - }; -} - -module.exports = { - buildComponentSchema, -}; diff --git a/packages/react-native-codegen/src/parsers/typescript/components/options.js b/packages/react-native-codegen/src/parsers/typescript/components/options.js deleted file mode 100644 index 4b0f9711172f..000000000000 --- a/packages/react-native-codegen/src/parsers/typescript/components/options.js +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {OptionsShape} from '../../../CodegenSchema.js'; - -// $FlowFixMe[unclear-type] TODO(T108222691): Use flow-types for @babel/parser -type OptionsAST = Object; - -export type CommandOptions = $ReadOnly<{ - supportedCommands: $ReadOnlyArray, -}>; - -function getCommandOptions( - commandOptionsExpression: OptionsAST, -): ?CommandOptions { - if (commandOptionsExpression == null) { - return null; - } - - let foundOptions; - try { - foundOptions = commandOptionsExpression.properties.reduce( - (options, prop) => { - options[prop.key.name] = ( - (prop && prop.value && prop.value.elements) || - [] - ).map(element => element && element.value); - return options; - }, - {}, - ); - } catch (e) { - throw new Error( - 'Failed to parse command options, please check that they are defined correctly', - ); - } - - return foundOptions; -} - -function getOptions(optionsExpression: OptionsAST): ?OptionsShape { - if (!optionsExpression) { - return null; - } - let foundOptions; - try { - foundOptions = optionsExpression.properties.reduce((options, prop) => { - if (prop.value.type === 'ArrayExpression') { - options[prop.key.name] = prop.value.elements.map( - element => element.value, - ); - } else { - options[prop.key.name] = prop.value.value; - } - return options; - }, {}); - } catch (e) { - throw new Error( - 'Failed to parse codegen options, please check that they are defined correctly', - ); - } - - if ( - foundOptions.paperComponentName && - foundOptions.paperComponentNameDeprecated - ) { - throw new Error( - 'Failed to parse codegen options, cannot use both paperComponentName and paperComponentNameDeprecated', - ); - } - - return foundOptions; -} - -module.exports = { - getCommandOptions, - getOptions, -}; diff --git a/packages/react-native-codegen/src/parsers/typescript/components/props.js b/packages/react-native-codegen/src/parsers/typescript/components/props.js deleted file mode 100644 index a2b1bcfad482..000000000000 --- a/packages/react-native-codegen/src/parsers/typescript/components/props.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; -const {getSchemaInfo, getTypeAnnotation} = require('./componentsUtils.js'); - -import type {NamedShape, PropTypeAnnotation} from '../../../CodegenSchema.js'; -import type {TypeDeclarationMap} from '../../utils'; - -// $FlowFixMe[unclear-type] there's no flowtype for ASTs -type PropAST = Object; - -function buildPropSchema( - property: PropAST, - types: TypeDeclarationMap, -): NamedShape { - const info = getSchemaInfo(property, types); - const {name, optional, typeAnnotation, defaultValue} = info; - return { - name, - optional, - typeAnnotation: getTypeAnnotation( - name, - typeAnnotation, - defaultValue, - types, - buildPropSchema, - ), - }; -} - -function getProps( - typeDefinition: $ReadOnlyArray, - types: TypeDeclarationMap, -): $ReadOnlyArray> { - return typeDefinition.map(property => buildPropSchema(property, types)); -} - -module.exports = { - getProps, -}; diff --git a/packages/react-native-codegen/src/parsers/typescript/components/schema.js b/packages/react-native-codegen/src/parsers/typescript/components/schema.js deleted file mode 100644 index ab165031cd25..000000000000 --- a/packages/react-native-codegen/src/parsers/typescript/components/schema.js +++ /dev/null @@ -1,62 +0,0 @@ -/** - * 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 - * @flow strict - */ - -'use strict'; - -import type { - EventTypeShape, - NamedShape, - CommandTypeAnnotation, - PropTypeAnnotation, - ExtendsPropsShape, - SchemaType, - OptionsShape, -} from '../../../CodegenSchema.js'; - -export type ComponentSchemaBuilderConfig = $ReadOnly<{ - filename: string, - componentName: string, - extendsProps: $ReadOnlyArray, - events: $ReadOnlyArray, - props: $ReadOnlyArray>, - commands: $ReadOnlyArray>, - options?: ?OptionsShape, -}>; - -function wrapComponentSchema({ - filename, - componentName, - extendsProps, - events, - props, - options, - commands, -}: ComponentSchemaBuilderConfig): SchemaType { - return { - modules: { - [filename]: { - type: 'Component', - components: { - [componentName]: { - ...(options || {}), - extendsProps, - events, - props, - commands, - }, - }, - }, - }, - }; -} - -module.exports = { - wrapComponentSchema, -}; diff --git a/packages/react-native-codegen/src/parsers/typescript/index.js b/packages/react-native-codegen/src/parsers/typescript/index.js deleted file mode 100644 index 426e4c8eef95..000000000000 --- a/packages/react-native-codegen/src/parsers/typescript/index.js +++ /dev/null @@ -1,94 +0,0 @@ -/** - * 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 - */ - -'use strict'; - -import type {SchemaType} from '../../CodegenSchema.js'; - -const babelParser = require('@babel/parser'); -const fs = require('fs'); -const { - buildSchemaFromConfigType, - getConfigType, - isModuleRegistryCall, -} = require('../utils'); -const {buildComponentSchema} = require('./components'); -const {wrapComponentSchema} = require('./components/schema'); -const {buildModuleSchema} = require('./modules'); - -function Visitor(infoMap: {isComponent: boolean, isModule: boolean}) { - return { - CallExpression(node: $FlowFixMe) { - if ( - node.callee.type === 'Identifier' && - node.callee.name === 'codegenNativeComponent' - ) { - infoMap.isComponent = true; - } - - if (isModuleRegistryCall(node)) { - infoMap.isModule = true; - } - }, - - TSInterfaceDeclaration(node: $FlowFixMe) { - if ( - Array.isArray(node.extends) && - node.extends.some( - extension => extension.expression.name === 'TurboModule', - ) - ) { - infoMap.isModule = true; - } - }, - }; -} - -function buildSchema(contents: string, filename: ?string): SchemaType { - // Early return for non-Spec JavaScript files - if ( - !contents.includes('codegenNativeComponent') && - !contents.includes('TurboModule') - ) { - return {modules: {}}; - } - - const ast = babelParser.parse(contents, { - sourceType: 'module', - plugins: ['typescript'], - }).program; - - const configType = getConfigType(ast, Visitor); - - return buildSchemaFromConfigType( - configType, - filename, - ast, - wrapComponentSchema, - buildComponentSchema, - buildModuleSchema, - ); -} - -function parseModuleFixture(filename: string): SchemaType { - const contents = fs.readFileSync(filename, 'utf8'); - - return buildSchema(contents, 'path/NativeSampleTurboModule.ts'); -} - -function parseString(contents: string, filename: ?string): SchemaType { - return buildSchema(contents, filename); -} - -module.exports = { - buildSchema, - parseModuleFixture, - parseString, -}; diff --git a/packages/react-native-codegen/src/parsers/typescript/modules/__test_fixtures__/failures.js b/packages/react-native-codegen/src/parsers/typescript/modules/__test_fixtures__/failures.js deleted file mode 100644 index f25e8b3d1034..000000000000 --- a/packages/react-native-codegen/src/parsers/typescript/modules/__test_fixtures__/failures.js +++ /dev/null @@ -1,167 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -// @licenselint-loose-mode - -const NATIVE_MODULES_WITH_ARRAY_WITH_NO_TYPE_FOR_CONTENT = ` -/** - * 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 - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export interface Spec extends TurboModule { - getString: (arg: string) => Array; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); -`; - -const NATIVE_MODULES_WITH_ARRAY_WITH_NO_TYPE_FOR_CONTENT_AS_PARAM = ` -/** - * 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 - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export interface Spec extends TurboModule { - getString: (arg: Array) => string; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); -`; - -const NATIVE_MODULES_WITH_NOT_ONLY_METHODS = ` -/** - * 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 - */ - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -export interface Spec extends TurboModule { - readonly getBool: (arg: boolean) => boolean; - readonly getNumber: (arg: number) => number; - readonly getString: (arg: string) => string; - sampleBool: boolean, - -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); - -`; - -const NATIVE_MODULES_WITH_UNNAMED_PARAMS = ` -/** - * 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 - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export interface Spec extends TurboModule { - readonly getBool: (boolean) => boolean; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); -`; - -const NATIVE_MODULES_WITH_PROMISE_WITHOUT_TYPE = ` -/** - * 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 - */ - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -export interface Spec extends TurboModule { - readonly getBool: (arg: boolean) => Promise; - -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); - -`; - -const TWO_NATIVE_MODULES_EXPORTED_WITH_DEFAULT = ` -/** - * 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 - */ - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule1'); -export default TurboModuleRegistry.getEnforcing('SampleTurboModule2'); -`; - -const TWO_NATIVE_EXTENDING_TURBO_MODULE = ` -/** - * 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 - */ - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -export interface Spec extends TurboModule { - readonly getSth: (a: number | null | undefined) => void; -} - -export interface Spec2 extends TurboModule { - readonly getSth: (a: number | null | undefined) => void; -} -`; - -module.exports = { - NATIVE_MODULES_WITH_UNNAMED_PARAMS, - NATIVE_MODULES_WITH_PROMISE_WITHOUT_TYPE, - NATIVE_MODULES_WITH_ARRAY_WITH_NO_TYPE_FOR_CONTENT_AS_PARAM, - NATIVE_MODULES_WITH_ARRAY_WITH_NO_TYPE_FOR_CONTENT, - TWO_NATIVE_MODULES_EXPORTED_WITH_DEFAULT, - NATIVE_MODULES_WITH_NOT_ONLY_METHODS, - TWO_NATIVE_EXTENDING_TURBO_MODULE, -}; diff --git a/packages/react-native-codegen/src/parsers/typescript/modules/__test_fixtures__/fixtures.js b/packages/react-native-codegen/src/parsers/typescript/modules/__test_fixtures__/fixtures.js deleted file mode 100644 index 83483075d5ba..000000000000 --- a/packages/react-native-codegen/src/parsers/typescript/modules/__test_fixtures__/fixtures.js +++ /dev/null @@ -1,700 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -// @licenselint-loose-mode - -const EMPTY_NATIVE_MODULE = ` -/** - * 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 - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export interface Spec extends TurboModule { - -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); -`; - -const NATIVE_MODULE_WITH_COMPLEX_OBJECTS = ` -/** - * 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 - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export type String = string; - -export interface Spec extends TurboModule { - // Exported methods. - readonly getObject: (arg: {const1: {const1: boolean}}) => { - const1: {const1: boolean}, - }; - readonly getReadOnlyObject: (arg: Readonly<{const1: Readonly<{const1: boolean}>}>) => Readonly<{ - const1: {const1: boolean}, - }>; - readonly getObject2: (arg: { a: String }) => Object; - readonly getObjectInArray: (arg: {const1: {const1: boolean}}) => Array<{ - const1: {const1: boolean}, - }>; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); -`; - -const NATIVE_MODULE_WITH_COMPLEX_OBJECTS_WITH_NULLABLE_KEY = ` -/** - * 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 - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export type String = string; - -export interface Spec extends TurboModule { - readonly getConstants: () => { - isTesting: boolean; - reactNativeVersion: { - major: number; - minor: number; - patch?: number; - prerelease: number | null | undefined; - }; - forceTouchAvailable: boolean; - osVersion: string; - systemName: string; - interfaceIdiom: string; - }; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); -`; - -const NATIVE_MODULE_WITH_BASIC_PARAM_TYPES = ` -/** - * 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 - */ - - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -export interface Spec extends TurboModule { - readonly passBool?: (arg: boolean) => void; - readonly passNumber: (arg: number) => void; - readonly passString: (arg: string) => void; - readonly passStringish: (arg: Stringish) => void; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); - -`; - -const NATIVE_MODULE_WITH_ALIASES = ` -/** - * 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 - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -type NumNum = number; -export type Num = (arg: NumNum) => void; -type Num2 = Num; -export type Void = void; -export type A = number; -export type B = number; -export type ObjectAlias = { - x: number; - y: number; - label: string; - truthy: boolean; -}; -export type ReadOnlyAlias = Readonly; - -export interface Spec extends TurboModule { - // Exported methods. - readonly getNumber: Num2; - readonly getVoid: () => Void; - readonly getArray: (a: Array) => {a: B}; - readonly getStringFromAlias: (a: ObjectAlias) => string; - readonly getStringFromNullableAlias: (a: ObjectAlias | null) => string; - readonly getStringFromReadOnlyAlias: (a: ReadOnlyAlias) => string; - readonly getStringFromNullableReadOnlyAlias: (a: ReadOnlyAlias | null) => string; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); -`; - -const NATIVE_MODULE_WITH_NESTED_ALIASES = ` -/** - * 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 - */ - - -import type {TurboModule} from '../RCTExport'; -import * as TurboModuleRegistry from '../TurboModuleRegistry'; - -type Bar = { - z: number -}; - -type Foo = { - bar1: Bar, - bar2: Bar, -}; - -export interface Spec extends TurboModule { - // Exported methods. - foo1: (x: Foo) => Foo; - foo2: (x: Foo) => void; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); - -`; - -const NATIVE_MODULE_WITH_FLOAT_AND_INT32 = ` -/** - * 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 - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import type {Int32, Float} from 'react-native/Libraries/Types/CodegenTypes'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export interface Spec extends TurboModule { - readonly getInt: (arg: Int32) => Int32; - readonly getFloat: (arg: Float) => Float; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); -`; - -const NATIVE_MODULE_WITH_SIMPLE_OBJECT = ` -/** - * 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 - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export interface Spec extends TurboModule { - readonly getObject: (o: Object) => Object, -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); -`; - -const NATIVE_MODULE_WITH_UNSAFE_OBJECT = ` -/** - * 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 - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; -import type {UnsafeObject} from 'react-native/Libraries/Types/CodegenTypes'; - -export interface Spec extends TurboModule { - readonly getUnsafeObject: (o: UnsafeObject) => UnsafeObject; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); -`; - -const NATIVE_MODULE_WITH_ROOT_TAG = ` -/** - * 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 - */ - -import type { - TurboModule, - RootTag, -} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export interface Spec extends TurboModule { - readonly getRootTag: (rootTag: RootTag) => RootTag; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); -`; - -const NATIVE_MODULE_WITH_NULLABLE_PARAM = ` -/** - * 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 - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export interface Spec extends TurboModule { - readonly voidFunc: (arg: string | null | undefined) => void; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); -`; - -const NATIVE_MODULE_WITH_BASIC_ARRAY = ` -/** - * 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 - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export interface Spec extends TurboModule { - readonly getArray: (arg: Array) => (Array<(string)>); - readonly getArray: (arg: ReadonlyArray) => (ReadonlyArray<(string)>); -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); -`; - -const NATIVE_MODULE_WITH_BASIC_ARRAY2 = ` -/** - * 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 - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export interface Spec extends TurboModule { - readonly getArray: (arg: string[]) => ((string)[]); - readonly getArray: (arg: readonly string[]) => (readonly (string)[]); -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); -`; - -const NATIVE_MODULE_WITH_OBJECT_WITH_OBJECT_DEFINED_IN_FILE_AS_PROPERTY = ` -/** - * 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 - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -type DisplayMetricsAndroid = { - width: number; -}; - -export interface Spec extends TurboModule { - readonly getConstants: () => { - readonly Dimensions: { - windowPhysicalPixels: DisplayMetricsAndroid; - }; - }; - readonly getConstants2: () => Readonly<{ - readonly Dimensions: { - windowPhysicalPixels: DisplayMetricsAndroid; - }; - }>; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); -`; - -const NATIVE_MODULE_WITH_ARRAY_WITH_UNION_AND_TOUPLE = ` -/** - * 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 - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export interface Spec extends TurboModule { - readonly getArray: ( - arg: Array<[string, string]>, - ) => Array; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); -`; - -const NATIVE_MODULE_WITH_ARRAY2_WITH_UNION_AND_TOUPLE = ` -/** - * 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 - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export interface Spec extends TurboModule { - readonly getArray: ( - arg: [string, string][], - ) => (string | number | boolean)[]; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); -`; - -const NATIVE_MODULE_WITH_ARRAY_WITH_ALIAS = ` -/** - * 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 - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export type SomeString = string; - -export interface Spec extends TurboModule { - readonly getArray: (arg: Array) => Array; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); -`; - -const NATIVE_MODULE_WITH_ARRAY2_WITH_ALIAS = ` -/** - * 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 - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export type SomeString = string; - -export interface Spec extends TurboModule { - readonly getArray: (arg: SomeString[]) => string[]; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); -`; - -const NATIVE_MODULE_WITH_COMPLEX_ARRAY = ` -/** - * 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 - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export interface Spec extends TurboModule { - readonly getArray: ( - arg: Array>>>>, - ) => Array>>; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); -`; - -const NATIVE_MODULE_WITH_COMPLEX_ARRAY2 = ` -/** - * 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 - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export interface Spec extends TurboModule { - readonly getArray: ( - arg: string[][][][][], - ) => string[][][]; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); -`; - -const NATIVE_MODULE_WITH_PROMISE = ` -/** - * 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 - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export type String = string; -export type SomeObj = { a: string }; - -export interface Spec extends TurboModule { - readonly getValueWithPromise: () => Promise; - readonly getValueWithPromiseDefinedSomewhereElse: () => Promise; - readonly getValueWithPromiseObjDefinedSomewhereElse: () => Promise; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); -`; - -const NATIVE_MODULE_WITH_CALLBACK = ` -/** - * 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 - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export interface Spec extends TurboModule { - readonly getValueWithCallback: ( - callback: (value: string, arr: Array>) => void, - ) => void; -} - -export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); -`; - -const ANDROID_ONLY_NATIVE_MODULE = ` -/** - * 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 - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export interface Spec extends TurboModule {} - -export default TurboModuleRegistry.getEnforcing( - 'SampleTurboModuleAndroid', -); -`; - -const IOS_ONLY_NATIVE_MODULE = ` -/** - * 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 - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export enum Quality { - SD, - HD, -} - -export enum Resolution { - Low = 720, - High = 1080, -} - -export enum Floppy { - LowDensity = 0.72, - HighDensity = 1.44, -} - -export enum StringOptions { - One = 'one', - Two = 'two', - Three = 'three', -} - -export interface Spec extends TurboModule { - readonly getEnums: (quality: Quality, resolution?: Resolution, floppy: Floppy, stringOptions: StringOptions) => string; -} - -export default TurboModuleRegistry.getEnforcing( - 'SampleTurboModuleIOS', -); -`; - -const CXX_ONLY_NATIVE_MODULE = ` -/** - * 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 - */ - -import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; -import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; - -export enum Quality { - SD, - HD, -} - -export enum Resolution { - Low = 720, - High = 1080, -} - -export enum Floppy { - LowDensity = 0.72, - HighDensity = 1.44, -} - -export enum StringOptions { - One = 'one', - Two = 'two', - Three = 'three', -} - -export type ChooseInt = 1 | 2 | 3; -export type ChooseFloat = 1.44 | 2.88 | 5.76; -export type ChooseObject = {} | {low: string}; -export type ChooseString = 'One' | 'Two' | 'Three'; - -export interface Spec extends TurboModule { - readonly getCallback: () => () => void; - readonly getMixed: (arg: unknown) => unknown; - readonly getEnums: (quality: Quality, resolution?: Resolution, floppy: Floppy, stringOptions: StringOptions) => string; - readonly getMap: (arg: {[a: string]: number | null;}) => {[b: string]: number | null;}; - readonly getAnotherMap: (arg: {[key: string]: string}) => {[key: string]: string}; - readonly getUnion: (chooseInt: ChooseInt, chooseFloat: ChooseFloat, chooseObject: ChooseObject, chooseString: ChooseString) => ChooseObject; -} - -export default TurboModuleRegistry.getEnforcing( - 'SampleTurboModuleCxx', -); -`; - -module.exports = { - NATIVE_MODULE_WITH_OBJECT_WITH_OBJECT_DEFINED_IN_FILE_AS_PROPERTY, - NATIVE_MODULE_WITH_ARRAY_WITH_UNION_AND_TOUPLE, - NATIVE_MODULE_WITH_ARRAY2_WITH_UNION_AND_TOUPLE, - NATIVE_MODULE_WITH_FLOAT_AND_INT32, - NATIVE_MODULE_WITH_ALIASES, - NATIVE_MODULE_WITH_NESTED_ALIASES, - NATIVE_MODULE_WITH_PROMISE, - NATIVE_MODULE_WITH_COMPLEX_OBJECTS, - NATIVE_MODULE_WITH_COMPLEX_OBJECTS_WITH_NULLABLE_KEY, - NATIVE_MODULE_WITH_SIMPLE_OBJECT, - NATIVE_MODULE_WITH_UNSAFE_OBJECT, - NATIVE_MODULE_WITH_ROOT_TAG, - NATIVE_MODULE_WITH_NULLABLE_PARAM, - NATIVE_MODULE_WITH_BASIC_ARRAY, - NATIVE_MODULE_WITH_BASIC_ARRAY2, - NATIVE_MODULE_WITH_COMPLEX_ARRAY, - NATIVE_MODULE_WITH_COMPLEX_ARRAY2, - NATIVE_MODULE_WITH_ARRAY_WITH_ALIAS, - NATIVE_MODULE_WITH_ARRAY2_WITH_ALIAS, - NATIVE_MODULE_WITH_BASIC_PARAM_TYPES, - NATIVE_MODULE_WITH_CALLBACK, - EMPTY_NATIVE_MODULE, - ANDROID_ONLY_NATIVE_MODULE, - IOS_ONLY_NATIVE_MODULE, - CXX_ONLY_NATIVE_MODULE, -}; diff --git a/packages/react-native-codegen/src/parsers/typescript/modules/__tests__/__snapshots__/typescript-module-parser-snapshot-test.js.snap b/packages/react-native-codegen/src/parsers/typescript/modules/__tests__/__snapshots__/typescript-module-parser-snapshot-test.js.snap deleted file mode 100644 index 185a836a0667..000000000000 --- a/packages/react-native-codegen/src/parsers/typescript/modules/__tests__/__snapshots__/typescript-module-parser-snapshot-test.js.snap +++ /dev/null @@ -1,1873 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`RN Codegen TypeScript Parser Fails with error message NATIVE_MODULES_WITH_ARRAY_WITH_NO_TYPE_FOR_CONTENT 1`] = `"Module NativeSampleTurboModule: Generic 'Array' must have type parameters."`; - -exports[`RN Codegen TypeScript Parser Fails with error message NATIVE_MODULES_WITH_ARRAY_WITH_NO_TYPE_FOR_CONTENT_AS_PARAM 1`] = `"Module NativeSampleTurboModule: Generic 'Array' must have type parameters."`; - -exports[`RN Codegen TypeScript Parser Fails with error message NATIVE_MODULES_WITH_NOT_ONLY_METHODS 1`] = `"Module NativeSampleTurboModule: TypeScript interfaces extending TurboModule must only contain 'FunctionTypeAnnotation's. Property 'sampleBool' refers to a 'TSBooleanKeyword'."`; - -exports[`RN Codegen TypeScript Parser Fails with error message NATIVE_MODULES_WITH_PROMISE_WITHOUT_TYPE 1`] = `"Module NativeSampleTurboModule: Generic 'Promise' must have type parameters."`; - -exports[`RN Codegen TypeScript Parser Fails with error message NATIVE_MODULES_WITH_UNNAMED_PARAMS 1`] = `"Module NativeSampleTurboModule: All function parameters must be named."`; - -exports[`RN Codegen TypeScript Parser Fails with error message TWO_NATIVE_EXTENDING_TURBO_MODULE 1`] = `"Module NativeSampleTurboModule: Every NativeModule spec file must declare exactly one NativeModule TypeScript interface. This file declares 2: 'Spec', and 'Spec2'. Please remove the extraneous TypeScript interface declarations."`; - -exports[`RN Codegen TypeScript Parser Fails with error message TWO_NATIVE_MODULES_EXPORTED_WITH_DEFAULT 1`] = `"Module NativeSampleTurboModule: No TypeScript interfaces extending TurboModule were detected in this NativeModule spec."`; - -exports[`RN Codegen TypeScript Parser can generate fixture ANDROID_ONLY_NATIVE_MODULE 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [] - }, - 'moduleNames': [ - 'SampleTurboModuleAndroid' - ], - 'excludedPlatforms': [ - 'iOS' - ] - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture CXX_ONLY_NATIVE_MODULE 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getCallback', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - }, - 'params': [] - }, - 'params': [] - } - }, - { - 'name': 'getMixed', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'MixedTypeAnnotation' - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'MixedTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'getEnums', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'StringTypeAnnotation' - }, - 'params': [ - { - 'name': 'quality', - 'optional': false, - 'typeAnnotation': { - 'type': 'EnumDeclaration', - 'memberType': 'StringTypeAnnotation' - } - }, - { - 'name': 'resolution', - 'optional': true, - 'typeAnnotation': { - 'type': 'EnumDeclaration', - 'memberType': 'NumberTypeAnnotation' - } - }, - { - 'name': 'floppy', - 'optional': false, - 'typeAnnotation': { - 'type': 'EnumDeclaration', - 'memberType': 'NumberTypeAnnotation' - } - }, - { - 'name': 'stringOptions', - 'optional': false, - 'typeAnnotation': { - 'type': 'EnumDeclaration', - 'memberType': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'getMap', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'b', - 'optional': false, - 'typeAnnotation': { - 'type': 'GenericObjectTypeAnnotation' - } - } - ] - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'a', - 'optional': false, - 'typeAnnotation': { - 'type': 'GenericObjectTypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'getAnotherMap', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'key', - 'optional': false, - 'typeAnnotation': { - 'type': 'GenericObjectTypeAnnotation' - } - } - ] - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'key', - 'optional': false, - 'typeAnnotation': { - 'type': 'GenericObjectTypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'getUnion', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'UnionTypeAnnotation', - 'memberType': 'ObjectTypeAnnotation' - }, - 'params': [ - { - 'name': 'chooseInt', - 'optional': false, - 'typeAnnotation': { - 'type': 'UnionTypeAnnotation', - 'memberType': 'NumberTypeAnnotation' - } - }, - { - 'name': 'chooseFloat', - 'optional': false, - 'typeAnnotation': { - 'type': 'UnionTypeAnnotation', - 'memberType': 'NumberTypeAnnotation' - } - }, - { - 'name': 'chooseObject', - 'optional': false, - 'typeAnnotation': { - 'type': 'UnionTypeAnnotation', - 'memberType': 'ObjectTypeAnnotation' - } - }, - { - 'name': 'chooseString', - 'optional': false, - 'typeAnnotation': { - 'type': 'UnionTypeAnnotation', - 'memberType': 'StringTypeAnnotation' - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModuleCxx' - ], - 'excludedPlatforms': [ - 'iOS', - 'android' - ] - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture EMPTY_NATIVE_MODULE 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture IOS_ONLY_NATIVE_MODULE 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getEnums', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'StringTypeAnnotation' - }, - 'params': [ - { - 'name': 'quality', - 'optional': false, - 'typeAnnotation': { - 'type': 'EnumDeclaration', - 'memberType': 'StringTypeAnnotation' - } - }, - { - 'name': 'resolution', - 'optional': true, - 'typeAnnotation': { - 'type': 'EnumDeclaration', - 'memberType': 'NumberTypeAnnotation' - } - }, - { - 'name': 'floppy', - 'optional': false, - 'typeAnnotation': { - 'type': 'EnumDeclaration', - 'memberType': 'NumberTypeAnnotation' - } - }, - { - 'name': 'stringOptions', - 'optional': false, - 'typeAnnotation': { - 'type': 'EnumDeclaration', - 'memberType': 'StringTypeAnnotation' - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModuleIOS' - ], - 'excludedPlatforms': [ - 'android' - ] - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_ALIASES 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': { - 'ObjectAlias': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'x', - 'optional': false, - 'typeAnnotation': { - 'type': 'NumberTypeAnnotation' - } - }, - { - 'name': 'y', - 'optional': false, - 'typeAnnotation': { - 'type': 'NumberTypeAnnotation' - } - }, - { - 'name': 'label', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'truthy', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - 'spec': { - 'properties': [ - { - 'name': 'getNumber', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'NumberTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'getVoid', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - }, - 'params': [] - } - }, - { - 'name': 'getArray', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'a', - 'optional': false, - 'typeAnnotation': { - 'type': 'NumberTypeAnnotation' - } - } - ] - }, - 'params': [ - { - 'name': 'a', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'NumberTypeAnnotation' - } - } - } - ] - } - }, - { - 'name': 'getStringFromAlias', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'StringTypeAnnotation' - }, - 'params': [ - { - 'name': 'a', - 'optional': false, - 'typeAnnotation': { - 'type': 'TypeAliasTypeAnnotation', - 'name': 'ObjectAlias' - } - } - ] - } - }, - { - 'name': 'getStringFromNullableAlias', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'StringTypeAnnotation' - }, - 'params': [ - { - 'name': 'a', - 'optional': false, - 'typeAnnotation': { - 'type': 'NullableTypeAnnotation', - 'typeAnnotation': { - 'type': 'TypeAliasTypeAnnotation', - 'name': 'ObjectAlias' - } - } - } - ] - } - }, - { - 'name': 'getStringFromReadOnlyAlias', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'StringTypeAnnotation' - }, - 'params': [ - { - 'name': 'a', - 'optional': false, - 'typeAnnotation': { - 'type': 'TypeAliasTypeAnnotation', - 'name': 'ObjectAlias' - } - } - ] - } - }, - { - 'name': 'getStringFromNullableReadOnlyAlias', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'StringTypeAnnotation' - }, - 'params': [ - { - 'name': 'a', - 'optional': false, - 'typeAnnotation': { - 'type': 'NullableTypeAnnotation', - 'typeAnnotation': { - 'type': 'TypeAliasTypeAnnotation', - 'name': 'ObjectAlias' - } - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_ARRAY_WITH_ALIAS 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getArray', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_ARRAY_WITH_UNION_AND_TOUPLE 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getArray', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ArrayTypeAnnotation' - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation' - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_ARRAY2_WITH_ALIAS 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getArray', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_ARRAY2_WITH_UNION_AND_TOUPLE 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getArray', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ArrayTypeAnnotation' - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation' - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_BASIC_ARRAY 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getArray', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - } - ] - } - }, - { - 'name': 'getArray', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_BASIC_ARRAY2 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getArray', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - } - ] - } - }, - { - 'name': 'getArray', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_BASIC_PARAM_TYPES 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'passBool', - 'optional': true, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'passNumber', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'NumberTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'passString', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - }, - { - 'name': 'passStringish', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_CALLBACK 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getValueWithCallback', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - }, - 'params': [ - { - 'name': 'callback', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - }, - 'params': [ - { - 'name': 'value', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'arr', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - } - } - ] - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_COMPLEX_ARRAY 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getArray', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - } - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - } - } - } - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_COMPLEX_ARRAY2 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getArray', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - } - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'StringTypeAnnotation' - } - } - } - } - } - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_COMPLEX_OBJECTS 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getObject', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'const1', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'const1', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - } - ] - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'const1', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'const1', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - } - ] - } - } - ] - } - }, - { - 'name': 'getReadOnlyObject', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'const1', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'const1', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - } - ] - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'const1', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'const1', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - } - ] - } - } - ] - } - }, - { - 'name': 'getObject2', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'GenericObjectTypeAnnotation' - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'a', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - } - } - ] - } - }, - { - 'name': 'getObjectInArray', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ArrayTypeAnnotation', - 'elementType': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'const1', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'const1', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - } - ] - } - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'const1', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'const1', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - } - ] - } - } - ] - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_COMPLEX_OBJECTS_WITH_NULLABLE_KEY 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getConstants', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'isTesting', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'reactNativeVersion', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'major', - 'optional': false, - 'typeAnnotation': { - 'type': 'NumberTypeAnnotation' - } - }, - { - 'name': 'minor', - 'optional': false, - 'typeAnnotation': { - 'type': 'NumberTypeAnnotation' - } - }, - { - 'name': 'patch', - 'optional': true, - 'typeAnnotation': { - 'type': 'NumberTypeAnnotation' - } - }, - { - 'name': 'prerelease', - 'optional': false, - 'typeAnnotation': { - 'type': 'NullableTypeAnnotation', - 'typeAnnotation': { - 'type': 'NumberTypeAnnotation' - } - } - } - ] - } - }, - { - 'name': 'forceTouchAvailable', - 'optional': false, - 'typeAnnotation': { - 'type': 'BooleanTypeAnnotation' - } - }, - { - 'name': 'osVersion', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'systemName', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - }, - { - 'name': 'interfaceIdiom', - 'optional': false, - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - ] - }, - 'params': [] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_FLOAT_AND_INT32 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getInt', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'Int32TypeAnnotation' - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'Int32TypeAnnotation' - } - } - ] - } - }, - { - 'name': 'getFloat', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'FloatTypeAnnotation' - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'FloatTypeAnnotation' - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_NESTED_ALIASES 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': { - 'Bar': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'z', - 'optional': false, - 'typeAnnotation': { - 'type': 'NumberTypeAnnotation' - } - } - ] - }, - 'Foo': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'bar1', - 'optional': false, - 'typeAnnotation': { - 'type': 'TypeAliasTypeAnnotation', - 'name': 'Bar' - } - }, - { - 'name': 'bar2', - 'optional': false, - 'typeAnnotation': { - 'type': 'TypeAliasTypeAnnotation', - 'name': 'Bar' - } - } - ] - } - }, - 'spec': { - 'properties': [ - { - 'name': 'foo1', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'TypeAliasTypeAnnotation', - 'name': 'Foo' - }, - 'params': [ - { - 'name': 'x', - 'optional': false, - 'typeAnnotation': { - 'type': 'TypeAliasTypeAnnotation', - 'name': 'Foo' - } - } - ] - } - }, - { - 'name': 'foo2', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - }, - 'params': [ - { - 'name': 'x', - 'optional': false, - 'typeAnnotation': { - 'type': 'TypeAliasTypeAnnotation', - 'name': 'Foo' - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_NULLABLE_PARAM 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'voidFunc', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'VoidTypeAnnotation' - }, - 'params': [ - { - 'name': 'arg', - 'optional': false, - 'typeAnnotation': { - 'type': 'NullableTypeAnnotation', - 'typeAnnotation': { - 'type': 'StringTypeAnnotation' - } - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_OBJECT_WITH_OBJECT_DEFINED_IN_FILE_AS_PROPERTY 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': { - 'DisplayMetricsAndroid': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'width', - 'optional': false, - 'typeAnnotation': { - 'type': 'NumberTypeAnnotation' - } - } - ] - } - }, - 'spec': { - 'properties': [ - { - 'name': 'getConstants', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'Dimensions', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'windowPhysicalPixels', - 'optional': false, - 'typeAnnotation': { - 'type': 'TypeAliasTypeAnnotation', - 'name': 'DisplayMetricsAndroid' - } - } - ] - } - } - ] - }, - 'params': [] - } - }, - { - 'name': 'getConstants2', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'Dimensions', - 'optional': false, - 'typeAnnotation': { - 'type': 'ObjectTypeAnnotation', - 'properties': [ - { - 'name': 'windowPhysicalPixels', - 'optional': false, - 'typeAnnotation': { - 'type': 'TypeAliasTypeAnnotation', - 'name': 'DisplayMetricsAndroid' - } - } - ] - } - } - ] - }, - 'params': [] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_PROMISE 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getValueWithPromise', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'PromiseTypeAnnotation' - }, - 'params': [] - } - }, - { - 'name': 'getValueWithPromiseDefinedSomewhereElse', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'PromiseTypeAnnotation' - }, - 'params': [] - } - }, - { - 'name': 'getValueWithPromiseObjDefinedSomewhereElse', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'PromiseTypeAnnotation' - }, - 'params': [] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_ROOT_TAG 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getRootTag', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'ReservedTypeAnnotation', - 'name': 'RootTag' - }, - 'params': [ - { - 'name': 'rootTag', - 'optional': false, - 'typeAnnotation': { - 'type': 'ReservedTypeAnnotation', - 'name': 'RootTag' - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_SIMPLE_OBJECT 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getObject', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'GenericObjectTypeAnnotation' - }, - 'params': [ - { - 'name': 'o', - 'optional': false, - 'typeAnnotation': { - 'type': 'GenericObjectTypeAnnotation' - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; - -exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_UNSAFE_OBJECT 1`] = ` -"{ - 'modules': { - 'NativeSampleTurboModule': { - 'type': 'NativeModule', - 'aliases': {}, - 'spec': { - 'properties': [ - { - 'name': 'getUnsafeObject', - 'optional': false, - 'typeAnnotation': { - 'type': 'FunctionTypeAnnotation', - 'returnTypeAnnotation': { - 'type': 'GenericObjectTypeAnnotation' - }, - 'params': [ - { - 'name': 'o', - 'optional': false, - 'typeAnnotation': { - 'type': 'GenericObjectTypeAnnotation' - } - } - ] - } - } - ] - }, - 'moduleNames': [ - 'SampleTurboModule' - ] - } - } -}" -`; diff --git a/packages/react-native-codegen/src/parsers/typescript/modules/__tests__/typescript-module-parser-e2e-test.js b/packages/react-native-codegen/src/parsers/typescript/modules/__tests__/typescript-module-parser-e2e-test.js deleted file mode 100644 index 92858546206b..000000000000 --- a/packages/react-native-codegen/src/parsers/typescript/modules/__tests__/typescript-module-parser-e2e-test.js +++ /dev/null @@ -1,1238 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -import type { - NativeModuleReturnTypeAnnotation, - NativeModuleBaseTypeAnnotation, - NativeModuleSchema, - NativeModuleParamTypeAnnotation, -} from '../../../../CodegenSchema'; - -const {parseString} = require('../../index.js'); -const {unwrapNullable} = require('../../../parsers-commons'); -const { - UnsupportedGenericParserError, - UnsupportedTypeAnnotationParserError, - UnnamedFunctionParamParserError, - MissingTypeParameterGenericParserError, -} = require('../../../errors'); -const invariant = require('invariant'); - -type PrimitiveTypeAnnotationType = - | 'StringTypeAnnotation' - | 'NumberTypeAnnotation' - | 'Int32TypeAnnotation' - | 'DoubleTypeAnnotation' - | 'FloatTypeAnnotation' - | 'BooleanTypeAnnotation'; - -const PRIMITIVES: $ReadOnlyArray<[string, PrimitiveTypeAnnotationType]> = [ - ['string', 'StringTypeAnnotation'], - ['number', 'NumberTypeAnnotation'], - ['Int32', 'Int32TypeAnnotation'], - ['Double', 'DoubleTypeAnnotation'], - ['Float', 'FloatTypeAnnotation'], - ['boolean', 'BooleanTypeAnnotation'], -]; - -const RESERVED_FUNCTION_VALUE_TYPE_NAME: $ReadOnlyArray<'RootTag'> = [ - 'RootTag', -]; - -const MODULE_NAME = 'NativeFoo'; - -const TYPE_ALIAS_DECLARATIONS = ` -type Animal = { - name: string; -}; - -type AnimalPointer = Animal; -`; - -function expectAnimalTypeAliasToExist(module: NativeModuleSchema) { - const animalAlias = module.aliases.Animal; - - expect(animalAlias).not.toBe(null); - invariant(animalAlias != null, ''); - expect(animalAlias.type).toBe('ObjectTypeAnnotation'); - expect(animalAlias.properties.length).toBe(1); - expect(animalAlias.properties[0].name).toBe('name'); - expect(animalAlias.properties[0].optional).toBe(false); - - const [typeAnnotation, nullable] = unwrapNullable( - animalAlias.properties[0].typeAnnotation, - ); - - expect(typeAnnotation.type).toBe('StringTypeAnnotation'); - expect(nullable).toBe(false); -} - -describe('TypeScript Module Parser', () => { - describe('Parameter Parsing', () => { - it("should fail parsing when a method has an parameter of type 'any'", () => { - const parser = () => - parseModule(` - import type {TurboModule} from 'RCTExport'; - import * as TurboModuleRegistry from 'TurboModuleRegistry'; - export interface Spec extends TurboModule { - useArg(arg: any): void; - } - export default TurboModuleRegistry.get('Foo'); - `); - - expect(parser).toThrow(UnsupportedTypeAnnotationParserError); - }); - - it('should fail parsing when a function param type is unamed', () => { - const parser = () => - parseModule(` - import type {TurboModule} from 'RCTExport'; - import * as TurboModuleRegistry from 'TurboModuleRegistry'; - export interface Spec extends TurboModule { - useArg(boolean): void; - } - export default TurboModuleRegistry.get('Foo'); - `); - - expect(parser).toThrow(UnnamedFunctionParamParserError); - }); - - [ - {nullable: false, optional: false}, - {nullable: false, optional: true}, - {nullable: true, optional: false}, - {nullable: true, optional: true}, - ].forEach(({nullable, optional}) => { - const PARAM_TYPE_DESCRIPTION = - nullable && optional - ? 'a nullable and optional' - : nullable - ? 'a nullable' - : optional - ? 'an optional' - : 'a required'; - - function annotateArg(paramName: string, paramType: string) { - if (nullable && optional) { - return `${paramName}?: ${paramType} | null | void`; - } - if (nullable) { - return `${paramName}: ${paramType} | null | void`; - } - if (optional) { - return `${paramName}?: ${paramType}`; - } - return `${paramName}: ${paramType}`; - } - - function parseParamType( - paramName: string, - paramType: string, - ): [NativeModuleParamTypeAnnotation, NativeModuleSchema] { - const module = parseModule(` - import type {TurboModule} from 'RCTExport'; - import * as TurboModuleRegistry from 'TurboModuleRegistry'; - - ${TYPE_ALIAS_DECLARATIONS} - - export interface Spec extends TurboModule { - useArg(${annotateArg(paramName, paramType)}): void; - } - export default TurboModuleRegistry.get('Foo'); - `); - - expect(module.spec.properties[0]).not.toBe(null); - const param = unwrapNullable( - module.spec.properties[0].typeAnnotation, - )[0].params[0]; - expect(param).not.toBe(null); - expect(param.name).toBe(paramName); - expect(param.optional).toBe(optional); - const [paramTypeAnnotation, isParamTypeAnnotationNullable] = - unwrapNullable(param.typeAnnotation); - expect(isParamTypeAnnotationNullable).toBe(nullable); - - return [paramTypeAnnotation, module]; - } - - describe( - (nullable && optional - ? 'Nullable and Optional' - : nullable - ? 'Nullable' - : optional - ? 'Optional' - : 'Required') + ' Parameter', - () => { - it(`should not parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of type 'Function'`, () => { - expect(() => parseParamType('arg', 'Function')).toThrow( - UnsupportedGenericParserError, - ); - }); - - describe('Primitive types', () => { - PRIMITIVES.forEach(([FLOW_TYPE, PARSED_TYPE_NAME]) => { - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} primitive parameter of type '${FLOW_TYPE}'`, () => { - const [paramTypeAnnotation] = parseParamType('arg', FLOW_TYPE); - expect(paramTypeAnnotation.type).toBe(PARSED_TYPE_NAME); - }); - }); - }); - - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of type 'Object'`, () => { - const [paramTypeAnnotation] = parseParamType('arg', 'Object'); - expect(paramTypeAnnotation.type).toBe( - 'GenericObjectTypeAnnotation', - ); - }); - - describe('Reserved Types', () => { - RESERVED_FUNCTION_VALUE_TYPE_NAME.forEach(FLOW_TYPE => { - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of reserved type '${FLOW_TYPE}'`, () => { - const [paramTypeAnnotation] = parseParamType('arg', FLOW_TYPE); - - expect(paramTypeAnnotation.type).toBe('ReservedTypeAnnotation'); - invariant( - paramTypeAnnotation.type === 'ReservedTypeAnnotation', - 'Param must be a Reserved type', - ); - - expect(paramTypeAnnotation.name).toBe(FLOW_TYPE); - }); - }); - }); - - describe('Array Types', () => { - it(`should not parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of type 'Array'`, () => { - expect(() => parseParamType('arg', 'Array')).toThrow( - MissingTypeParameterGenericParserError, - ); - }); - - function parseParamArrayElementType( - paramName: string, - paramType: string, - ): [NativeModuleBaseTypeAnnotation, NativeModuleSchema] { - const [paramTypeAnnotation, module] = parseParamType( - paramName, - `Array<${paramType}>`, - ); - - expect(paramTypeAnnotation.type).toBe('ArrayTypeAnnotation'); - invariant(paramTypeAnnotation.type === 'ArrayTypeAnnotation', ''); - - expect(paramTypeAnnotation.elementType).not.toBe(null); - invariant(paramTypeAnnotation.elementType != null, ''); - const [elementType, isElementTypeNullable] = - unwrapNullable( - paramTypeAnnotation.elementType, - ); - expect(isElementTypeNullable).toBe(false); - return [elementType, module]; - } - - // TODO: Do we support nullable element types? - - describe('Primitive Element Types', () => { - PRIMITIVES.forEach(([FLOW_TYPE, PARSED_TYPE_NAME]) => { - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of type 'Array<${FLOW_TYPE}>'`, () => { - const [elementType] = parseParamArrayElementType( - 'arg', - FLOW_TYPE, - ); - expect(elementType.type).toBe(PARSED_TYPE_NAME); - }); - }); - }); - - describe('Reserved Element Types', () => { - RESERVED_FUNCTION_VALUE_TYPE_NAME.forEach(FLOW_TYPE => { - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of type 'Array<${FLOW_TYPE}>'`, () => { - const [elementType] = parseParamArrayElementType( - 'arg', - FLOW_TYPE, - ); - expect(elementType.type).toBe('ReservedTypeAnnotation'); - invariant(elementType.type === 'ReservedTypeAnnotation', ''); - - expect(elementType.name).toBe(FLOW_TYPE); - }); - }); - }); - - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of type 'Array'`, () => { - const [elementType] = parseParamArrayElementType('arg', 'Object'); - expect(elementType.type).toBe('GenericObjectTypeAnnotation'); - }); - - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of some array of an alias`, () => { - const [elementType, module] = parseParamArrayElementType( - 'arg', - 'Animal', - ); - expect(elementType.type).toBe('TypeAliasTypeAnnotation'); - invariant(elementType.type === 'TypeAliasTypeAnnotation', ''); - - expect(elementType.name).toBe('Animal'); - expectAnimalTypeAliasToExist(module); - }); - - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of type 'Array<{foo: string | null | void}>'`, () => { - const [elementType] = parseParamArrayElementType( - 'arg', - '{foo: string | null | void}', - ); - expect(elementType).not.toBe(null); - - expect(elementType.type).toBe('ObjectTypeAnnotation'); - invariant(elementType.type === 'ObjectTypeAnnotation', ''); - - const {properties} = elementType; - invariant(properties != null, ''); - - expect(properties).not.toBe(null); - expect(properties[0]).not.toBe(null); - expect(properties[0].name).toBe('foo'); - expect(properties[0].typeAnnotation).not.toBe(null); - - const [typeAnnotation, isPropertyNullable] = unwrapNullable( - properties[0].typeAnnotation, - ); - - expect(typeAnnotation.type).toBe('StringTypeAnnotation'); - expect(isPropertyNullable).toBe(true); - expect(properties[0].optional).toBe(false); - }); - }); - - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of some type alias`, () => { - const [paramTypeAnnotation, module] = parseParamType( - 'arg', - 'Animal', - ); - expect(paramTypeAnnotation.type).toBe('TypeAliasTypeAnnotation'); - invariant( - paramTypeAnnotation.type === 'TypeAliasTypeAnnotation', - '', - ); - - expect(paramTypeAnnotation.name).toBe('Animal'); - expectAnimalTypeAliasToExist(module); - }); - - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of some type alias that points to another type alias`, () => { - const [paramTypeAnnotation, module] = parseParamType( - 'arg', - 'AnimalPointer', - ); - expect(paramTypeAnnotation.type).toBe('TypeAliasTypeAnnotation'); - invariant( - paramTypeAnnotation.type === 'TypeAliasTypeAnnotation', - '', - ); - - expect(paramTypeAnnotation.name).toBe('Animal'); - expectAnimalTypeAliasToExist(module); - }); - - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of some type alias that points to another nullable type alias`, () => { - const module = parseModule(` - import type {TurboModule} from 'RCTExport'; - import * as TurboModuleRegistry from 'TurboModuleRegistry'; - - type Animal = { - name: string, - } | null | void; - - type AnimalPointer = Animal; - - export interface Spec extends TurboModule { - useArg(${annotateArg('arg', 'AnimalPointer')}): void; - } - export default TurboModuleRegistry.get('Foo'); - `); - - expect(module.spec.properties[0]).not.toBe(null); - const param = unwrapNullable( - module.spec.properties[0].typeAnnotation, - )[0].params[0]; - expect(param.name).toBe('arg'); - expect(param.optional).toBe(optional); - - // The TypeAliasAnnotation is called Animal, and is nullable - const [paramTypeAnnotation, isParamTypeAnnotationNullable] = - unwrapNullable(param.typeAnnotation); - expect(paramTypeAnnotation.type).toBe('TypeAliasTypeAnnotation'); - invariant( - paramTypeAnnotation.type === 'TypeAliasTypeAnnotation', - '', - ); - expect(paramTypeAnnotation.name).toBe('Animal'); - expect(isParamTypeAnnotationNullable).toBe(true); - - // The Animal type alias RHS is valid, and non-null - expectAnimalTypeAliasToExist(module); - }); - - [ - {nullable: false, optional: false}, - {nullable: false, optional: true}, - {nullable: true, optional: false}, - {nullable: true, optional: true}, - ].forEach(({nullable: isPropNullable, optional: isPropOptional}) => { - const PROP_TYPE_DESCRIPTION = - isPropNullable && isPropOptional - ? 'a nullable and optional' - : isPropNullable - ? 'a nullable' - : isPropOptional - ? 'an optional' - : 'a required'; - - function annotateProp(propName: string, propType: string) { - if (isPropNullable && isPropOptional) { - return `${propName}?: ${propType} | null | void`; - } - if (isPropNullable) { - return `${propName}: ${propType} | null | void`; - } - if (isPropOptional) { - return `${propName}?: ${propType}`; - } - return `${propName}: ${propType}`; - } - - function parseParamTypeObjectLiteralProp( - propName: string, - propType: string, - ): [ - $ReadOnly<{ - name: string, - optional: boolean, - typeAnnotation: NativeModuleBaseTypeAnnotation, - }>, - NativeModuleSchema, - ] { - const [paramTypeAnnotation, module] = parseParamType( - 'arg', - `{${annotateProp(propName, propType)}}`, - ); - - expect(paramTypeAnnotation.type).toBe('ObjectTypeAnnotation'); - invariant( - paramTypeAnnotation.type === 'ObjectTypeAnnotation', - '', - ); - - const {properties} = paramTypeAnnotation; - - expect(properties).not.toBe(null); - invariant(properties != null, ''); - - expect(properties.length).toBe(1); - expect(properties[0].name).toBe(propName); - expect(properties[0].optional).toBe(isPropOptional); - - const [propertyTypeAnnotation, isPropertyTypeAnnotationNullable] = - unwrapNullable(properties[0].typeAnnotation); - - expect(propertyTypeAnnotation).not.toBe(null); - expect(isPropertyTypeAnnotationNullable).toBe(isPropNullable); - - return [ - { - ...properties[0], - typeAnnotation: propertyTypeAnnotation, - }, - module, - ]; - } - - describe( - (isPropNullable && isPropOptional - ? 'Nullable and Optional' - : isPropNullable - ? 'Nullable' - : isPropOptional - ? 'Optional' - : 'Required') + ' Property', - () => { - describe('Props with Primitive Types', () => { - PRIMITIVES.forEach(([FLOW_TYPE, PARSED_TYPE_NAME]) => { - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of primitive type '${FLOW_TYPE}'`, () => { - const [prop] = parseParamTypeObjectLiteralProp( - 'prop', - FLOW_TYPE, - ); - expect(prop.typeAnnotation.type).toBe(PARSED_TYPE_NAME); - }); - }); - }); - - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Object'`, () => { - const [prop] = parseParamTypeObjectLiteralProp( - 'prop', - 'Object', - ); - expect(prop.typeAnnotation.type).toBe( - 'GenericObjectTypeAnnotation', - ); - }); - - describe('Props with Reserved Types', () => { - RESERVED_FUNCTION_VALUE_TYPE_NAME.forEach(FLOW_TYPE => { - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of reserved type '${FLOW_TYPE}'`, () => { - const [prop] = parseParamTypeObjectLiteralProp( - 'prop', - FLOW_TYPE, - ); - expect(prop.typeAnnotation.type).toBe( - 'ReservedTypeAnnotation', - ); - invariant( - prop.typeAnnotation.type === 'ReservedTypeAnnotation', - '', - ); - - expect(prop.typeAnnotation.name).toBe(FLOW_TYPE); - }); - }); - }); - - describe('Props with Array Types', () => { - it(`should not parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Array`, () => { - expect(() => - parseParamTypeObjectLiteralProp('prop', 'Array'), - ).toThrow(MissingTypeParameterGenericParserError); - }); - - function parseArrayElementType( - propName: string, - arrayElementType: string, - ): [NativeModuleBaseTypeAnnotation, NativeModuleSchema] { - const [property, module] = parseParamTypeObjectLiteralProp( - 'propName', - `Array<${arrayElementType}>`, - ); - expect(property.typeAnnotation.type).toBe( - 'ArrayTypeAnnotation', - ); - invariant( - property.typeAnnotation.type === 'ArrayTypeAnnotation', - '', - ); - - const {elementType: nullableElementType} = - property.typeAnnotation; - expect(nullableElementType).not.toBe(null); - invariant(nullableElementType != null, ''); - - const [elementType, isElementTypeNullable] = - unwrapNullable( - nullableElementType, - ); - - expect(isElementTypeNullable).toBe(false); - - return [elementType, module]; - } - - PRIMITIVES.forEach(([FLOW_TYPE, PARSED_TYPE_NAME]) => { - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Array<${FLOW_TYPE}>'`, () => { - const [elementType] = parseArrayElementType( - 'prop', - FLOW_TYPE, - ); - - expect(elementType.type).toBe(PARSED_TYPE_NAME); - }); - }); - - RESERVED_FUNCTION_VALUE_TYPE_NAME.forEach(FLOW_TYPE => { - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Array<${FLOW_TYPE}>'`, () => { - const [elementType] = parseArrayElementType( - 'prop', - FLOW_TYPE, - ); - - expect(elementType.type).toBe('ReservedTypeAnnotation'); - invariant( - elementType.type === 'ReservedTypeAnnotation', - '', - ); - expect(elementType.name).toBe(FLOW_TYPE); - }); - }); - - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Array'`, () => { - const [elementType] = parseArrayElementType( - 'prop', - 'Object', - ); - expect(elementType.type).toBe( - 'GenericObjectTypeAnnotation', - ); - }); - - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type of some array of an alias`, () => { - const [elementType, module] = parseArrayElementType( - 'prop', - 'Animal', - ); - - expect(elementType.type).toBe('TypeAliasTypeAnnotation'); - invariant( - elementType.type === 'TypeAliasTypeAnnotation', - '', - ); - - expect(elementType.name).toBe('Animal'); - expectAnimalTypeAliasToExist(module); - }); - - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of 'Array<{foo: string | null | void}>'`, () => { - const [elementType] = parseArrayElementType( - 'prop', - '{foo: string | null | void}', - ); - - expect(elementType.type).toBe('ObjectTypeAnnotation'); - invariant(elementType.type === 'ObjectTypeAnnotation', ''); - - const {properties} = elementType; - expect(properties).not.toBe(null); - invariant(properties != null, ''); - - expect(properties[0]).not.toBe(null); - expect(properties[0].name).toBe('foo'); - expect(properties[0].typeAnnotation).not.toBe(null); - - const [ - propertyTypeAnnotation, - isPropertyTypeAnnotationNullable, - ] = unwrapNullable(properties[0].typeAnnotation); - - expect(propertyTypeAnnotation.type).toBe( - 'StringTypeAnnotation', - ); - expect(isPropertyTypeAnnotationNullable).toBe(true); - expect(properties[0].optional).toBe(false); - }); - }); - - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type '{foo: string | null | void}'`, () => { - const [property] = parseParamTypeObjectLiteralProp( - 'prop', - '{foo: string | null | void}', - ); - - expect(property.typeAnnotation.type).toBe( - 'ObjectTypeAnnotation', - ); - invariant( - property.typeAnnotation.type === 'ObjectTypeAnnotation', - '', - ); - - const {properties} = property.typeAnnotation; - expect(properties).not.toBe(null); - invariant(properties != null, ''); - - expect(properties[0]).not.toBe(null); - expect(properties[0].name).toBe('foo'); - - const [ - propertyTypeAnnotation, - isPropertyTypeAnnotationNullable, - ] = unwrapNullable(properties[0].typeAnnotation); - - expect(propertyTypeAnnotation.type).toBe( - 'StringTypeAnnotation', - ); - expect(isPropertyTypeAnnotationNullable).toBe(true); - expect(properties[0].optional).toBe(false); - }); - - it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of some type alias`, () => { - const [property, module] = parseParamTypeObjectLiteralProp( - 'prop', - 'Animal', - ); - - expect(property.typeAnnotation.type).toBe( - 'TypeAliasTypeAnnotation', - ); - invariant( - property.typeAnnotation.type === 'TypeAliasTypeAnnotation', - '', - ); - - expect(property.typeAnnotation.name).toBe('Animal'); - expectAnimalTypeAliasToExist(module); - }); - }, - ); - }); - }, - ); - }); - }); - - describe('Return Parsing', () => { - it('should parse methods that have a return type of void', () => { - const module = parseModule(` - import type {TurboModule} from 'RCTExport'; - import * as TurboModuleRegistry from 'TurboModuleRegistry'; - export interface Spec extends TurboModule { - useArg(): void; - } - export default TurboModuleRegistry.get('Foo'); - `); - - expect(module.spec.properties[0]).not.toBe(null); - - const [functionTypeAnnotation, isFunctionTypeAnnotationNullable] = - unwrapNullable(module.spec.properties[0].typeAnnotation); - expect(isFunctionTypeAnnotationNullable).toBe(false); - - const [returnTypeAnnotation, isReturnTypeAnnotationNullable] = - unwrapNullable(functionTypeAnnotation.returnTypeAnnotation); - expect(returnTypeAnnotation.type).toBe('VoidTypeAnnotation'); - expect(isReturnTypeAnnotationNullable).toBe(false); - }); - - [true, false].forEach(IS_RETURN_TYPE_NULLABLE => { - const RETURN_TYPE_DESCRIPTION = IS_RETURN_TYPE_NULLABLE - ? 'a nullable' - : 'a non-nullable'; - const annotateRet = (retType: string) => - IS_RETURN_TYPE_NULLABLE ? `${retType} | null | void` : retType; - - function parseReturnType( - flowType: string, - ): [NativeModuleReturnTypeAnnotation, NativeModuleSchema] { - const module = parseModule(` - import type {TurboModule} from 'RCTExport'; - import * as TurboModuleRegistry from 'TurboModuleRegistry'; - - ${TYPE_ALIAS_DECLARATIONS} - - export interface Spec extends TurboModule { - useArg(): ${annotateRet(flowType)}; - } - export default TurboModuleRegistry.get('Foo'); - `); - - expect(module.spec.properties[0]).not.toBe(null); - const [functionTypeAnnotation, isFunctionTypeAnnotationNullable] = - unwrapNullable(module.spec.properties[0].typeAnnotation); - expect(isFunctionTypeAnnotationNullable).toBe(false); - - const [returnTypeAnnotation, isReturnTypeAnnotationNullable] = - unwrapNullable(functionTypeAnnotation.returnTypeAnnotation); - expect(isReturnTypeAnnotationNullable).toBe(IS_RETURN_TYPE_NULLABLE); - - return [returnTypeAnnotation, module]; - } - - describe( - IS_RETURN_TYPE_NULLABLE ? 'Nullable Returns' : 'Non-Nullable Returns', - () => { - ['Promise', 'Promise<{}>'].forEach(promiseFlowType => { - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return of type '${promiseFlowType}'`, () => { - const [returnTypeAnnotation] = parseReturnType(promiseFlowType); - expect(returnTypeAnnotation.type).toBe('PromiseTypeAnnotation'); - }); - }); - - describe('Primitive Types', () => { - PRIMITIVES.forEach(([FLOW_TYPE, PARSED_TYPE_NAME]) => { - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} primitive return of type '${FLOW_TYPE}'`, () => { - const [returnTypeAnnotation] = parseReturnType(FLOW_TYPE); - expect(returnTypeAnnotation.type).toBe(PARSED_TYPE_NAME); - }); - }); - }); - - describe('Reserved Types', () => { - RESERVED_FUNCTION_VALUE_TYPE_NAME.forEach(FLOW_TYPE => { - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} reserved return of type '${FLOW_TYPE}'`, () => { - const [returnTypeAnnotation] = parseReturnType(FLOW_TYPE); - expect(returnTypeAnnotation.type).toBe( - 'ReservedTypeAnnotation', - ); - invariant( - returnTypeAnnotation.type === 'ReservedTypeAnnotation', - '', - ); - expect(returnTypeAnnotation.name).toBe(FLOW_TYPE); - }); - }); - }); - - describe('Array Types', () => { - it(`should not parse methods that have ${RETURN_TYPE_DESCRIPTION} return of type 'Array'`, () => { - expect(() => parseReturnType('Array')).toThrow( - MissingTypeParameterGenericParserError, - ); - }); - - function parseArrayElementReturnType( - flowType: string, - ): [NativeModuleBaseTypeAnnotation, NativeModuleSchema] { - const [returnTypeAnnotation, module] = parseReturnType( - 'Array' + (flowType != null ? `<${flowType}>` : ''), - ); - expect(returnTypeAnnotation.type).toBe('ArrayTypeAnnotation'); - invariant( - returnTypeAnnotation.type === 'ArrayTypeAnnotation', - '', - ); - - const arrayTypeAnnotation = returnTypeAnnotation; - - const {elementType} = arrayTypeAnnotation; - expect(elementType).not.toBe(null); - invariant(elementType != null, ''); - - const [elementTypeAnnotation, isElementTypeAnnotation] = - unwrapNullable(elementType); - expect(isElementTypeAnnotation).toBe(false); - - return [elementTypeAnnotation, module]; - } - - // TODO: Do we support nullable element types? - - describe('Primitive Element Types', () => { - PRIMITIVES.forEach(([FLOW_TYPE, PARSED_TYPE_NAME]) => { - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return of type 'Array<${FLOW_TYPE}>'`, () => { - const [elementType] = parseArrayElementReturnType(FLOW_TYPE); - expect(elementType.type).toBe(PARSED_TYPE_NAME); - }); - }); - }); - - describe('Reserved Element Types', () => { - RESERVED_FUNCTION_VALUE_TYPE_NAME.forEach(FLOW_TYPE => { - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return of type 'Array<${FLOW_TYPE}>'`, () => { - const [elementType] = parseArrayElementReturnType(FLOW_TYPE); - expect(elementType.type).toBe('ReservedTypeAnnotation'); - invariant(elementType.type === 'ReservedTypeAnnotation', ''); - - expect(elementType.name).toBe(FLOW_TYPE); - }); - }); - }); - - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return of type 'Array'`, () => { - const [elementType] = parseArrayElementReturnType('Object'); - expect(elementType.type).toBe('GenericObjectTypeAnnotation'); - }); - - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of some array of an alias`, () => { - const [elementType, module] = - parseArrayElementReturnType('Animal'); - expect(elementType.type).toBe('TypeAliasTypeAnnotation'); - invariant(elementType.type === 'TypeAliasTypeAnnotation', ''); - expect(elementType.name).toBe('Animal'); - expectAnimalTypeAliasToExist(module); - }); - - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return of type 'Array<{foo: string | null | void}>'`, () => { - const [elementType] = parseArrayElementReturnType( - '{foo: string | null | void}', - ); - expect(elementType.type).toBe('ObjectTypeAnnotation'); - invariant(elementType.type === 'ObjectTypeAnnotation', ''); - - const {properties} = elementType; - expect(properties).not.toBe(null); - invariant(properties != null, ''); - - expect(properties[0]).not.toBe(null); - expect(properties[0].name).toBe('foo'); - expect(properties[0].typeAnnotation).not.toBe(null); - - const [propertyTypeAnnotation, isPropertyTypeAnnotationNullable] = - unwrapNullable(properties[0].typeAnnotation); - - expect(propertyTypeAnnotation.type).toBe('StringTypeAnnotation'); - expect(isPropertyTypeAnnotationNullable).toBe(true); - expect(properties[0].optional).toBe(false); - }); - }); - - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of some type alias`, () => { - const [returnTypeAnnotation, module] = parseReturnType('Animal'); - expect(returnTypeAnnotation.type).toBe('TypeAliasTypeAnnotation'); - invariant( - returnTypeAnnotation.type === 'TypeAliasTypeAnnotation', - '', - ); - expect(returnTypeAnnotation.name).toBe('Animal'); - expectAnimalTypeAliasToExist(module); - }); - - it(`should not parse methods that have ${RETURN_TYPE_DESCRIPTION} return of type 'Function'`, () => { - expect(() => parseReturnType('Function')).toThrow( - UnsupportedGenericParserError, - ); - }); - - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return of type 'Object'`, () => { - const [returnTypeAnnotation] = parseReturnType('Object'); - expect(returnTypeAnnotation.type).toBe( - 'GenericObjectTypeAnnotation', - ); - }); - - describe('Object Literals Types', () => { - // TODO: Inexact vs exact object literals? - - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an empty object literal`, () => { - const [returnTypeAnnotation] = parseReturnType('{}'); - expect(returnTypeAnnotation.type).toBe('ObjectTypeAnnotation'); - invariant( - returnTypeAnnotation.type === 'ObjectTypeAnnotation', - '', - ); - - // Validate properties of object literal - expect(returnTypeAnnotation.properties).not.toBe(null); - expect(returnTypeAnnotation.properties?.length).toBe(0); - }); - - [ - {nullable: false, optional: false}, - {nullable: false, optional: true}, - {nullable: true, optional: false}, - {nullable: true, optional: true}, - ].forEach(({nullable, optional}) => { - const PROP_TYPE_DESCRIPTION = - nullable && optional - ? 'a nullable and optional' - : nullable - ? 'a nullable' - : optional - ? 'an optional' - : 'a required'; - - function annotateProp(propName: string, propType: string) { - if (nullable && optional) { - return `${propName}?: ${propType} | null | void`; - } - if (nullable) { - return `${propName}: ${propType} | null | void`; - } - if (optional) { - return `${propName}?: ${propType}`; - } - return `${propName}: ${propType}`; - } - - function parseObjectLiteralReturnTypeProp( - propName: string, - propType: string, - ): [ - $ReadOnly<{ - name: string, - optional: boolean, - typeAnnotation: NativeModuleBaseTypeAnnotation, - }>, - NativeModuleSchema, - ] { - const [returnTypeAnnotation, module] = parseReturnType( - `{${annotateProp(propName, propType)}}`, - ); - expect(returnTypeAnnotation.type).toBe('ObjectTypeAnnotation'); - invariant( - returnTypeAnnotation.type === 'ObjectTypeAnnotation', - '', - ); - - const properties = returnTypeAnnotation.properties; - expect(properties).not.toBe(null); - invariant(properties != null, ''); - - expect(properties.length).toBe(1); - - // Validate property - const property = properties[0]; - expect(property.name).toBe(propName); - expect(property.optional).toBe(optional); - - const [ - propertyTypeAnnotation, - isPropertyTypeAnnotationNullable, - ] = unwrapNullable(property.typeAnnotation); - - expect(propertyTypeAnnotation).not.toBe(null); - expect(isPropertyTypeAnnotationNullable).toBe(nullable); - return [ - { - ...property, - typeAnnotation: propertyTypeAnnotation, - }, - module, - ]; - } - - describe( - (nullable && optional - ? 'Nullable and Optional' - : nullable - ? 'Nullable' - : optional - ? 'Optional' - : 'Required') + ' Property', - () => { - /** - * TODO: Fill out props in promise - */ - - describe('Props with Primitive Types', () => { - PRIMITIVES.forEach(([FLOW_TYPE, PARSED_TYPE_NAME]) => { - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of primitive type '${FLOW_TYPE}'`, () => { - const [property] = parseObjectLiteralReturnTypeProp( - 'prop', - FLOW_TYPE, - ); - expect(property.typeAnnotation.type).toBe( - PARSED_TYPE_NAME, - ); - }); - }); - }); - - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Object'`, () => { - const [property] = parseObjectLiteralReturnTypeProp( - 'prop', - 'Object', - ); - - expect(property.typeAnnotation.type).toBe( - 'GenericObjectTypeAnnotation', - ); - }); - - describe('Props with Reserved Types', () => { - RESERVED_FUNCTION_VALUE_TYPE_NAME.forEach(FLOW_TYPE => { - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of reserved type '${FLOW_TYPE}'`, () => { - const [property] = parseObjectLiteralReturnTypeProp( - 'prop', - FLOW_TYPE, - ); - - expect(property.typeAnnotation.type).toBe( - 'ReservedTypeAnnotation', - ); - invariant( - property.typeAnnotation.type === - 'ReservedTypeAnnotation', - '', - ); - - expect(property.typeAnnotation.name).toBe(FLOW_TYPE); - }); - }); - }); - - describe('Props with Array Types', () => { - it(`should not parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Array`, () => { - expect(() => - parseObjectLiteralReturnTypeProp('prop', 'Array'), - ).toThrow(MissingTypeParameterGenericParserError); - }); - - function parseArrayElementType( - propName: string, - arrayElementType: string, - ): [NativeModuleBaseTypeAnnotation, NativeModuleSchema] { - const [property, module] = - parseObjectLiteralReturnTypeProp( - propName, - `Array<${arrayElementType}>`, - ); - expect(property.name).toBe(propName); - expect(property.typeAnnotation.type).toBe( - 'ArrayTypeAnnotation', - ); - invariant( - property.typeAnnotation.type === 'ArrayTypeAnnotation', - '', - ); - - const {elementType: nullableElementType} = - property.typeAnnotation; - expect(nullableElementType).not.toBe(null); - invariant(nullableElementType != null, ''); - - const [elementType, isElementTypeNullable] = - unwrapNullable( - nullableElementType, - ); - expect(isElementTypeNullable).toBe(false); - - return [elementType, module]; - } - - PRIMITIVES.forEach(([FLOW_TYPE, PARSED_TYPE_NAME]) => { - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Array<${FLOW_TYPE}>'`, () => { - const [elementType] = parseArrayElementType( - 'prop', - FLOW_TYPE, - ); - expect(elementType.type).toBe(PARSED_TYPE_NAME); - }); - }); - - RESERVED_FUNCTION_VALUE_TYPE_NAME.forEach(FLOW_TYPE => { - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Array<${FLOW_TYPE}>'`, () => { - const [elementType] = parseArrayElementType( - 'prop', - FLOW_TYPE, - ); - expect(elementType.type).toBe('ReservedTypeAnnotation'); - invariant( - elementType.type === 'ReservedTypeAnnotation', - '', - ); - - expect(elementType.name).toBe(FLOW_TYPE); - }); - }); - - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Array'`, () => { - const [elementType] = parseArrayElementType( - 'prop', - 'Object', - ); - expect(elementType).not.toBe(null); - expect(elementType.type).toBe( - 'GenericObjectTypeAnnotation', - ); - }); - - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type of some array of an aliase`, () => { - const [elementType, module] = parseArrayElementType( - 'prop', - 'Animal', - ); - expect(elementType.type).toBe('TypeAliasTypeAnnotation'); - invariant( - elementType.type === 'TypeAliasTypeAnnotation', - '', - ); - expect(elementType.name).toBe('Animal'); - expectAnimalTypeAliasToExist(module); - }); - - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Array<{foo: string | null | void}>'`, () => { - const [elementType] = parseArrayElementType( - 'prop', - '{foo: string | null | void}', - ); - expect(elementType.type).toBe('ObjectTypeAnnotation'); - invariant( - elementType.type === 'ObjectTypeAnnotation', - '', - ); - - const {properties} = elementType; - invariant(properties != null, ''); - expect(properties).not.toBe(null); - expect(properties[0]).not.toBe(null); - expect(properties[0].name).toBe('foo'); - expect(properties[0].optional).toBe(false); - - const [ - propertyTypeAnnotation, - isPropertyTypeAnnotationNullable, - ] = unwrapNullable(properties[0].typeAnnotation); - - expect(propertyTypeAnnotation.type).toBe( - 'StringTypeAnnotation', - ); - expect(isPropertyTypeAnnotationNullable).toBe(true); - }); - }); - - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of '{foo: string | null | void}'`, () => { - const [property] = parseObjectLiteralReturnTypeProp( - 'prop', - '{foo: string | null | void}', - ); - - expect(property.typeAnnotation.type).toBe( - 'ObjectTypeAnnotation', - ); - invariant( - property.typeAnnotation.type === 'ObjectTypeAnnotation', - '', - ); - - const {properties} = property.typeAnnotation; - - expect(properties).not.toBe(null); - invariant(properties != null, ''); - - expect(properties[0]).not.toBe(null); - expect(properties[0].name).toBe('foo'); - expect(properties[0].optional).toBe(false); - - const [ - propertyTypeAnnotation, - isPropertyTypeAnnotationNullable, - ] = unwrapNullable(properties[0].typeAnnotation); - - expect(propertyTypeAnnotation.type).toBe( - 'StringTypeAnnotation', - ); - expect(isPropertyTypeAnnotationNullable).toBe(true); - }); - - it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of some type alias`, () => { - const [property, module] = parseObjectLiteralReturnTypeProp( - 'prop', - 'Animal', - ); - - expect(property.typeAnnotation.type).toBe( - 'TypeAliasTypeAnnotation', - ); - invariant( - property.typeAnnotation.type === - 'TypeAliasTypeAnnotation', - '', - ); - - expect(property.typeAnnotation.name).toBe('Animal'); - expectAnimalTypeAliasToExist(module); - }); - }, - ); - }); - }); - }, - ); - }); - }); -}); - -function parseModule(source: string) { - const schema = parseString(source, `${MODULE_NAME}.ts`); - const module = schema.modules.NativeFoo; - invariant( - module.type === 'NativeModule', - "'nativeModules' in Spec NativeFoo shouldn't be null", - ); - return module; -} diff --git a/packages/react-native-codegen/src/parsers/typescript/modules/__tests__/typescript-module-parser-snapshot-test.js b/packages/react-native-codegen/src/parsers/typescript/modules/__tests__/typescript-module-parser-snapshot-test.js deleted file mode 100644 index b831c0710631..000000000000 --- a/packages/react-native-codegen/src/parsers/typescript/modules/__tests__/typescript-module-parser-snapshot-test.js +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -const TypeScriptParser = require('../../index.js'); -const fixtures = require('../__test_fixtures__/fixtures.js'); -const failureFixtures = require('../__test_fixtures__/failures.js'); - -jest.mock('fs', () => ({ - readFileSync: filename => { - // Jest in the OSS does not allow to capture variables in closures. - // Therefore, we have to bring the variables inside the closure. - // see: https://github.com/facebook/jest/issues/2567 - const readFileFixtures = require('../__test_fixtures__/fixtures.js'); - const readFileFailureFixtures = require('../__test_fixtures__/failures.js'); - return readFileFixtures[filename] || readFileFailureFixtures[filename]; - }, -})); - -describe('RN Codegen TypeScript Parser', () => { - Object.keys(fixtures) - .sort() - .forEach(fixtureName => { - it(`can generate fixture ${fixtureName}`, () => { - const schema = TypeScriptParser.parseModuleFixture(fixtureName); - const serializedSchema = JSON.stringify(schema, null, 2).replace( - /"/g, - "'", - ); - - expect(serializedSchema).toMatchSnapshot(); - }); - }); - - Object.keys(failureFixtures) - .sort() - .forEach(fixtureName => { - it(`Fails with error message ${fixtureName}`, () => { - expect(() => { - TypeScriptParser.parseModuleFixture(fixtureName); - }).toThrowErrorMatchingSnapshot(); - }); - }); -}); diff --git a/packages/react-native-codegen/src/parsers/typescript/modules/index.js b/packages/react-native-codegen/src/parsers/typescript/modules/index.js deleted file mode 100644 index bc5aae5f65ec..000000000000 --- a/packages/react-native-codegen/src/parsers/typescript/modules/index.js +++ /dev/null @@ -1,706 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type { - NamedShape, - NativeModuleAliasMap, - NativeModuleArrayTypeAnnotation, - NativeModuleBaseTypeAnnotation, - NativeModuleFunctionTypeAnnotation, - NativeModuleParamTypeAnnotation, - NativeModulePropertyShape, - NativeModuleSchema, - Nullable, -} from '../../../CodegenSchema.js'; - -import type {ParserErrorCapturer, TypeDeclarationMap} from '../../utils'; -import type {NativeModuleTypeAnnotation} from '../../../CodegenSchema.js'; -const {nullGuard} = require('../../parsers-utils'); - -const { - throwIfMoreThanOneModuleRegistryCalls, - throwIfUnsupportedFunctionParamTypeAnnotationParserError, -} = require('../../error-utils'); -const {visit, isModuleRegistryCall} = require('../../utils'); -const {resolveTypeAnnotation, getTypes} = require('../utils.js'); -const { - unwrapNullable, - wrapNullable, - assertGenericTypeAnnotationHasExactlyOneTypeParameter, - emitMixedTypeAnnotation, - emitUnionTypeAnnotation, - translateDefault, -} = require('../../parsers-commons'); -const { - emitBoolean, - emitDouble, - emitFloat, - emitFunction, - emitNumber, - emitInt32, - emitObject, - emitPromise, - emitRootTag, - emitVoid, - emitString, - emitStringish, - typeAliasResolution, -} = require('../../parsers-primitives'); -const { - UnnamedFunctionParamParserError, - UnsupportedArrayElementTypeAnnotationParserError, - UnsupportedGenericParserError, - UnsupportedTypeAnnotationParserError, - UnsupportedObjectPropertyTypeAnnotationParserError, - IncorrectModuleRegistryCallArgumentTypeParserError, -} = require('../../errors.js'); - -const {verifyPlatforms} = require('../../utils'); - -const { - throwIfUntypedModule, - throwIfPropertyValueTypeIsUnsupported, - throwIfModuleTypeIsUnsupported, - throwIfUnusedModuleInterfaceParserError, - throwIfModuleInterfaceNotFound, - throwIfModuleInterfaceIsMisnamed, - throwIfWrongNumberOfCallExpressionArgs, - throwIfMoreThanOneModuleInterfaceParserError, - throwIfIncorrectModuleRegistryCallTypeParameterParserError, - throwIfUnsupportedFunctionReturnTypeAnnotationParserError, -} = require('../../error-utils'); - -const {TypeScriptParser} = require('../parser'); -const {getKeyName} = require('../../parsers-commons'); - -const language = 'TypeScript'; -const parser = new TypeScriptParser(); - -function translateArrayTypeAnnotation( - hasteModuleName: string, - types: TypeDeclarationMap, - aliasMap: {...NativeModuleAliasMap}, - cxxOnly: boolean, - tsArrayType: 'Array' | 'ReadonlyArray', - tsElementType: $FlowFixMe, - nullable: boolean, -): Nullable { - try { - /** - * TODO(T72031674): Migrate all our NativeModule specs to not use - * invalid Array ElementTypes. Then, make the elementType a required - * parameter. - */ - const [elementType, isElementTypeNullable] = unwrapNullable( - translateTypeAnnotation( - hasteModuleName, - tsElementType, - types, - aliasMap, - /** - * TODO(T72031674): Ensure that all ParsingErrors that are thrown - * while parsing the array element don't get captured and collected. - * Why? If we detect any parsing error while parsing the element, - * we should default it to null down the line, here. This is - * the correct behaviour until we migrate all our NativeModule specs - * to be parseable. - */ - nullGuard, - cxxOnly, - ), - ); - - if (elementType.type === 'VoidTypeAnnotation') { - throw new UnsupportedArrayElementTypeAnnotationParserError( - hasteModuleName, - tsElementType, - tsArrayType, - 'void', - language, - ); - } - - if (elementType.type === 'PromiseTypeAnnotation') { - throw new UnsupportedArrayElementTypeAnnotationParserError( - hasteModuleName, - tsElementType, - tsArrayType, - 'Promise', - language, - ); - } - - if (elementType.type === 'FunctionTypeAnnotation') { - throw new UnsupportedArrayElementTypeAnnotationParserError( - hasteModuleName, - tsElementType, - tsArrayType, - 'FunctionTypeAnnotation', - language, - ); - } - - const finalTypeAnnotation: NativeModuleArrayTypeAnnotation< - Nullable, - > = { - type: 'ArrayTypeAnnotation', - elementType: wrapNullable(isElementTypeNullable, elementType), - }; - - return wrapNullable(nullable, finalTypeAnnotation); - } catch (ex) { - return wrapNullable(nullable, { - type: 'ArrayTypeAnnotation', - }); - } -} - -function translateTypeAnnotation( - hasteModuleName: string, - /** - * TODO(T108222691): Use flow-types for @babel/parser - */ - typeScriptTypeAnnotation: $FlowFixMe, - types: TypeDeclarationMap, - aliasMap: {...NativeModuleAliasMap}, - tryParse: ParserErrorCapturer, - cxxOnly: boolean, -): Nullable { - const {nullable, typeAnnotation, typeAliasResolutionStatus} = - resolveTypeAnnotation(typeScriptTypeAnnotation, types); - - switch (typeAnnotation.type) { - case 'TSArrayType': { - return translateArrayTypeAnnotation( - hasteModuleName, - types, - aliasMap, - cxxOnly, - 'Array', - typeAnnotation.elementType, - nullable, - ); - } - case 'TSTypeOperator': { - if ( - typeAnnotation.operator === 'readonly' && - typeAnnotation.typeAnnotation.type === 'TSArrayType' - ) { - return translateArrayTypeAnnotation( - hasteModuleName, - types, - aliasMap, - cxxOnly, - 'ReadonlyArray', - typeAnnotation.typeAnnotation.elementType, - nullable, - ); - } else { - throw new UnsupportedGenericParserError( - hasteModuleName, - typeAnnotation, - parser, - ); - } - } - case 'TSTypeReference': { - switch (typeAnnotation.typeName.name) { - case 'RootTag': { - return emitRootTag(nullable); - } - case 'Promise': { - return emitPromise( - hasteModuleName, - typeAnnotation, - language, - nullable, - ); - } - case 'Array': - case 'ReadonlyArray': { - assertGenericTypeAnnotationHasExactlyOneTypeParameter( - hasteModuleName, - typeAnnotation, - language, - ); - - return translateArrayTypeAnnotation( - hasteModuleName, - types, - aliasMap, - cxxOnly, - typeAnnotation.type, - typeAnnotation.typeParameters.params[0], - nullable, - ); - } - case 'Stringish': { - return emitStringish(nullable); - } - case 'Int32': { - return emitInt32(nullable); - } - case 'Double': { - return emitDouble(nullable); - } - case 'Float': { - return emitFloat(nullable); - } - case 'UnsafeObject': - case 'Object': { - return emitObject(nullable); - } - default: { - return translateDefault( - hasteModuleName, - typeAnnotation, - types, - nullable, - parser, - ); - } - } - } - case 'TSTypeLiteral': { - const objectTypeAnnotation = { - type: 'ObjectTypeAnnotation', - // $FlowFixMe[missing-type-arg] - properties: (typeAnnotation.members: Array<$FlowFixMe>) - .map>>( - property => { - return tryParse(() => { - if ( - property.type !== 'TSPropertySignature' && - property.type !== 'TSIndexSignature' - ) { - throw new UnsupportedObjectPropertyTypeAnnotationParserError( - hasteModuleName, - property, - property.type, - language, - ); - } - - const {optional = false} = property; - const name = getKeyName(property, hasteModuleName, language); - if (property.type === 'TSIndexSignature') { - return { - name, - optional, - typeAnnotation: emitObject(nullable), - }; - } - const [propertyTypeAnnotation, isPropertyNullable] = - unwrapNullable( - translateTypeAnnotation( - hasteModuleName, - property.typeAnnotation.typeAnnotation, - types, - aliasMap, - tryParse, - cxxOnly, - ), - ); - - if ( - propertyTypeAnnotation.type === 'FunctionTypeAnnotation' || - propertyTypeAnnotation.type === 'PromiseTypeAnnotation' || - propertyTypeAnnotation.type === 'VoidTypeAnnotation' - ) { - throwIfPropertyValueTypeIsUnsupported( - hasteModuleName, - property.typeAnnotation.typeAnnotation, - property.key, - propertyTypeAnnotation.type, - language, - ); - } else { - return { - name, - optional, - typeAnnotation: wrapNullable( - isPropertyNullable, - propertyTypeAnnotation, - ), - }; - } - }); - }, - ) - .filter(Boolean), - }; - - return typeAliasResolution( - typeAliasResolutionStatus, - objectTypeAnnotation, - aliasMap, - nullable, - ); - } - case 'TSBooleanKeyword': { - return emitBoolean(nullable); - } - case 'TSNumberKeyword': { - return emitNumber(nullable); - } - case 'TSVoidKeyword': { - return emitVoid(nullable); - } - case 'TSStringKeyword': { - return emitString(nullable); - } - case 'TSFunctionType': { - const translateFunctionTypeAnnotationValue: NativeModuleFunctionTypeAnnotation = - translateFunctionTypeAnnotation( - hasteModuleName, - typeAnnotation, - types, - aliasMap, - tryParse, - cxxOnly, - ); - - return emitFunction(nullable, translateFunctionTypeAnnotationValue); - } - case 'TSUnionType': { - if (cxxOnly) { - return emitUnionTypeAnnotation( - nullable, - hasteModuleName, - typeAnnotation, - language, - ); - } - // Fallthrough - } - case 'TSUnknownKeyword': { - if (cxxOnly) { - return emitMixedTypeAnnotation(nullable); - } - // Fallthrough - } - default: { - throw new UnsupportedTypeAnnotationParserError( - hasteModuleName, - typeAnnotation, - language, - ); - } - } -} - -function translateFunctionTypeAnnotation( - hasteModuleName: string, - // TODO(T108222691): Use flow-types for @babel/parser - typescriptFunctionTypeAnnotation: $FlowFixMe, - types: TypeDeclarationMap, - aliasMap: {...NativeModuleAliasMap}, - tryParse: ParserErrorCapturer, - cxxOnly: boolean, -): NativeModuleFunctionTypeAnnotation { - type Param = NamedShape>; - const params: Array = []; - - for (const typeScriptParam of (typescriptFunctionTypeAnnotation.parameters: $ReadOnlyArray<$FlowFixMe>)) { - const parsedParam = tryParse(() => { - if (typeScriptParam.typeAnnotation == null) { - throw new UnnamedFunctionParamParserError( - typeScriptParam, - hasteModuleName, - language, - ); - } - - const paramName = typeScriptParam.name; - const [paramTypeAnnotation, isParamTypeAnnotationNullable] = - unwrapNullable( - translateTypeAnnotation( - hasteModuleName, - typeScriptParam.typeAnnotation.typeAnnotation, - types, - aliasMap, - tryParse, - cxxOnly, - ), - ); - - if ( - paramTypeAnnotation.type === 'VoidTypeAnnotation' || - paramTypeAnnotation.type === 'PromiseTypeAnnotation' - ) { - return throwIfUnsupportedFunctionParamTypeAnnotationParserError( - hasteModuleName, - typeScriptParam.typeAnnotation, - paramName, - paramTypeAnnotation.type, - ); - } - - return { - name: typeScriptParam.name, - optional: Boolean(typeScriptParam.optional), - typeAnnotation: wrapNullable( - isParamTypeAnnotationNullable, - paramTypeAnnotation, - ), - }; - }); - - if (parsedParam != null) { - params.push(parsedParam); - } - } - - const [returnTypeAnnotation, isReturnTypeAnnotationNullable] = unwrapNullable( - translateTypeAnnotation( - hasteModuleName, - typescriptFunctionTypeAnnotation.typeAnnotation.typeAnnotation, - types, - aliasMap, - tryParse, - cxxOnly, - ), - ); - - throwIfUnsupportedFunctionReturnTypeAnnotationParserError( - hasteModuleName, - typescriptFunctionTypeAnnotation, - 'FunctionTypeAnnotation', - language, - cxxOnly, - returnTypeAnnotation.type, - ); - - return { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: wrapNullable( - isReturnTypeAnnotationNullable, - returnTypeAnnotation, - ), - params, - }; -} - -function buildPropertySchema( - hasteModuleName: string, - // TODO(T108222691): Use flow-types for @babel/parser - property: $FlowFixMe, - types: TypeDeclarationMap, - aliasMap: {...NativeModuleAliasMap}, - tryParse: ParserErrorCapturer, - cxxOnly: boolean, -): NativeModulePropertyShape { - let nullable = false; - let {key} = property; - let value = - property.type === 'TSMethodSignature' ? property : property.typeAnnotation; - - const methodName: string = key.name; - - ({nullable, typeAnnotation: value} = resolveTypeAnnotation(value, types)); - throwIfModuleTypeIsUnsupported( - hasteModuleName, - property.value, - property.key.name, - value.type, - language, - ); - - return { - name: methodName, - optional: Boolean(property.optional), - typeAnnotation: wrapNullable( - nullable, - translateFunctionTypeAnnotation( - hasteModuleName, - value, - types, - aliasMap, - tryParse, - cxxOnly, - ), - ), - }; -} - -function isModuleInterface(node: $FlowFixMe) { - return ( - node.type === 'TSInterfaceDeclaration' && - node.extends.length === 1 && - node.extends[0].type === 'TSExpressionWithTypeArguments' && - node.extends[0].expression.name === 'TurboModule' - ); -} - -function buildModuleSchema( - hasteModuleName: string, - /** - * TODO(T108222691): Use flow-types for @babel/parser - */ - ast: $FlowFixMe, - tryParse: ParserErrorCapturer, -): NativeModuleSchema { - const types = getTypes(ast); - const moduleSpecs = (Object.values(types): $ReadOnlyArray<$FlowFixMe>).filter( - isModuleInterface, - ); - - throwIfModuleInterfaceNotFound( - moduleSpecs.length, - hasteModuleName, - ast, - language, - ); - - throwIfMoreThanOneModuleInterfaceParserError( - hasteModuleName, - moduleSpecs, - language, - ); - - const [moduleSpec] = moduleSpecs; - - throwIfModuleInterfaceIsMisnamed(hasteModuleName, moduleSpec.id, language); - - // Parse Module Names - const moduleName = tryParse((): string => { - const callExpressions = []; - visit(ast, { - CallExpression(node) { - if (isModuleRegistryCall(node)) { - callExpressions.push(node); - } - }, - }); - - throwIfUnusedModuleInterfaceParserError( - hasteModuleName, - moduleSpec, - callExpressions, - language, - ); - - throwIfMoreThanOneModuleRegistryCalls( - hasteModuleName, - callExpressions, - callExpressions.length, - language, - ); - - const [callExpression] = callExpressions; - const {typeParameters} = callExpression; - const methodName = callExpression.callee.property.name; - - throwIfWrongNumberOfCallExpressionArgs( - hasteModuleName, - callExpression, - methodName, - callExpression.arguments.length, - language, - ); - - if (callExpression.arguments[0].type !== 'StringLiteral') { - const {type} = callExpression.arguments[0]; - throw new IncorrectModuleRegistryCallArgumentTypeParserError( - hasteModuleName, - callExpression.arguments[0], - methodName, - type, - language, - ); - } - - const $moduleName = callExpression.arguments[0].value; - - throwIfUntypedModule( - typeParameters, - hasteModuleName, - callExpression, - methodName, - $moduleName, - language, - ); - - throwIfIncorrectModuleRegistryCallTypeParameterParserError( - hasteModuleName, - typeParameters, - methodName, - $moduleName, - language, - ); - - return $moduleName; - }); - - const moduleNames = moduleName == null ? [] : [moduleName]; - - // Some module names use platform suffix to indicate platform-exclusive modules. - // Eventually this should be made explicit in the Flow type itself. - // Also check the hasteModuleName for platform suffix. - // Note: this shape is consistent with ComponentSchema. - const {cxxOnly, excludedPlatforms} = verifyPlatforms( - hasteModuleName, - moduleNames, - ); - - // $FlowFixMe[missing-type-arg] - return (moduleSpec.body.body: $ReadOnlyArray<$FlowFixMe>) - .filter( - property => - property.type === 'TSMethodSignature' || - property.type === 'TSPropertySignature', - ) - .map(property => { - const aliasMap: {...NativeModuleAliasMap} = {}; - - return tryParse(() => ({ - aliasMap: aliasMap, - propertyShape: buildPropertySchema( - hasteModuleName, - property, - types, - aliasMap, - tryParse, - cxxOnly, - ), - })); - }) - .filter(Boolean) - .reduce( - (moduleSchema: NativeModuleSchema, {aliasMap, propertyShape}) => { - return { - type: 'NativeModule', - aliases: {...moduleSchema.aliases, ...aliasMap}, - spec: { - properties: [...moduleSchema.spec.properties, propertyShape], - }, - moduleNames: moduleSchema.moduleNames, - excludedPlatforms: moduleSchema.excludedPlatforms, - }; - }, - { - type: 'NativeModule', - aliases: {}, - spec: {properties: []}, - moduleNames: moduleNames, - excludedPlatforms: - excludedPlatforms.length !== 0 ? [...excludedPlatforms] : undefined, - }, - ); -} - -module.exports = { - buildModuleSchema, -}; diff --git a/packages/react-native-codegen/src/parsers/typescript/parseTopLevelType.js b/packages/react-native-codegen/src/parsers/typescript/parseTopLevelType.js deleted file mode 100644 index 8ec8580e66c9..000000000000 --- a/packages/react-native-codegen/src/parsers/typescript/parseTopLevelType.js +++ /dev/null @@ -1,189 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {TypeDeclarationMap} from '../utils'; - -export type LegalDefaultValues = string | number | boolean | null; - -type TopLevelTypeInternal = { - unions: Array<$FlowFixMe>, - optional: boolean, - defaultValue?: LegalDefaultValues, -}; - -export type TopLevelType = { - type: $FlowFixMe, - optional: boolean, - defaultValue?: LegalDefaultValues, -}; - -function getValueFromTypes( - value: $FlowFixMe, - types: TypeDeclarationMap, -): $FlowFixMe { - switch (value.type) { - case 'TSTypeReference': - if (types[value.typeName.name]) { - return getValueFromTypes(types[value.typeName.name], types); - } else { - return value; - } - case 'TSTypeAliasDeclaration': - return getValueFromTypes(value.typeAnnotation, types); - default: - return value; - } -} - -function isNull(t: $FlowFixMe) { - return t.type === 'TSNullKeyword' || t.type === 'TSUndefinedKeyword'; -} - -function isNullOrVoid(t: $FlowFixMe) { - return isNull(t) || t.type === 'TSVoidKeyword'; -} - -function couldBeNumericLiteral(type: string) { - return type === 'Literal' || type === 'NumericLiteral'; -} - -function couldBeSimpleLiteral(type: string) { - return ( - couldBeNumericLiteral(type) || - type === 'StringLiteral' || - type === 'BooleanLiteral' - ); -} - -function evaluateLiteral( - literalNode: $FlowFixMe, -): string | number | boolean | null { - const valueType = literalNode.type; - if (valueType === 'TSLiteralType') { - const literal = literalNode.literal; - if (couldBeSimpleLiteral(literal.type)) { - if ( - typeof literal.value === 'string' || - typeof literal.value === 'number' || - typeof literal.value === 'boolean' - ) { - return literal.value; - } - } else if ( - literal.type === 'UnaryExpression' && - literal.operator === '-' && - couldBeNumericLiteral(literal.argument.type) && - typeof literal.argument.value === 'number' - ) { - return -literal.argument.value; - } - } else if (isNull(literalNode)) { - return null; - } - - throw new Error( - 'The default value in WithDefault must be string, number, boolean or null .', - ); -} - -function handleUnionAndParen( - type: $FlowFixMe, - result: TopLevelTypeInternal, - knownTypes?: TypeDeclarationMap, -): void { - switch (type.type) { - case 'TSParenthesizedType': { - handleUnionAndParen(type.typeAnnotation, result, knownTypes); - break; - } - case 'TSUnionType': { - // the order is important - // result.optional must be set first - for (const t of type.types) { - if (isNullOrVoid(t)) { - result.optional = true; - } - } - for (const t of type.types) { - if (!isNullOrVoid(t)) { - handleUnionAndParen(t, result, knownTypes); - } - } - break; - } - case 'TSTypeReference': - if (type.typeName.name === 'Readonly') { - handleUnionAndParen(type.typeParameters.params[0], result, knownTypes); - } else if (type.typeName.name === 'WithDefault') { - if (result.optional) { - throw new Error( - 'WithDefault<> is optional and does not need to be marked as optional. Please remove the union of undefined and/or null', - ); - } - if (type.typeParameters.params.length !== 2) { - throw new Error( - 'WithDefault requires two parameters: type and default value.', - ); - } - if (result.defaultValue !== undefined) { - throw new Error( - 'Multiple WithDefault is not allowed nested or in a union type.', - ); - } - result.optional = true; - result.defaultValue = evaluateLiteral(type.typeParameters.params[1]); - handleUnionAndParen(type.typeParameters.params[0], result, knownTypes); - } else if (!knownTypes) { - result.unions.push(type); - } else { - const resolvedType = getValueFromTypes(type, knownTypes); - if ( - resolvedType.type === 'TSTypeReference' && - resolvedType.typeName.name === type.typeName.name - ) { - result.unions.push(type); - } else { - handleUnionAndParen(resolvedType, result, knownTypes); - } - } - break; - default: - result.unions.push(type); - } -} - -function parseTopLevelType( - type: $FlowFixMe, - knownTypes?: TypeDeclarationMap, -): TopLevelType { - let result: TopLevelTypeInternal = {unions: [], optional: false}; - handleUnionAndParen(type, result, knownTypes); - if (result.unions.length === 0) { - throw new Error('Union type could not be just null or undefined.'); - } else if (result.unions.length === 1) { - return { - type: result.unions[0], - optional: result.optional, - defaultValue: result.defaultValue, - }; - } else { - return { - type: {type: 'TSUnionType', types: result.unions}, - optional: result.optional, - defaultValue: result.defaultValue, - }; - } -} - -module.exports = { - parseTopLevelType, -}; diff --git a/packages/react-native-codegen/src/parsers/typescript/parser.js b/packages/react-native-codegen/src/parsers/typescript/parser.js deleted file mode 100644 index 3bcf2cdb6415..000000000000 --- a/packages/react-native-codegen/src/parsers/typescript/parser.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type {ParserType} from '../errors'; -import type {Parser} from '../parser'; - -class TypeScriptParser implements Parser { - getMaybeEnumMemberType(maybeEnumDeclaration: $FlowFixMe): string { - if (maybeEnumDeclaration.members[0].initializer) { - return maybeEnumDeclaration.members[0].initializer.type - .replace('NumericLiteral', 'NumberTypeAnnotation') - .replace('StringLiteral', 'StringTypeAnnotation'); - } - - return 'StringTypeAnnotation'; - } - - isEnumDeclaration(maybeEnumDeclaration: $FlowFixMe): boolean { - return maybeEnumDeclaration.type === 'TSEnumDeclaration'; - } - - language(): ParserType { - return 'TypeScript'; - } - - nameForGenericTypeAnnotation(typeAnnotation: $FlowFixMe): string { - return typeAnnotation.typeName.name; - } -} -module.exports = { - TypeScriptParser, -}; diff --git a/packages/react-native-codegen/src/parsers/typescript/utils.js b/packages/react-native-codegen/src/parsers/typescript/utils.js deleted file mode 100644 index 73728847e12b..000000000000 --- a/packages/react-native-codegen/src/parsers/typescript/utils.js +++ /dev/null @@ -1,115 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -'use strict'; - -import type {TypeAliasResolutionStatus, TypeDeclarationMap} from '../utils'; - -const {parseTopLevelType} = require('./parseTopLevelType'); - -/** - * TODO(T108222691): Use flow-types for @babel/parser - */ - -function getTypes(ast: $FlowFixMe): TypeDeclarationMap { - return ast.body.reduce((types, node) => { - switch (node.type) { - case 'ExportNamedDeclaration': { - if (node.declaration) { - switch (node.declaration.type) { - case 'TSTypeAliasDeclaration': - case 'TSInterfaceDeclaration': - case 'TSEnumDeclaration': { - types[node.declaration.id.name] = node.declaration; - break; - } - } - } - break; - } - case 'TSTypeAliasDeclaration': - case 'TSInterfaceDeclaration': - case 'TSEnumDeclaration': { - types[node.id.name] = node; - break; - } - } - return types; - }, {}); -} - -// $FlowFixMe[unclear-type] Use flow-types for @babel/parser -export type ASTNode = Object; - -const invariant = require('invariant'); - -function resolveTypeAnnotation( - // TODO(T108222691): Use flow-types for @babel/parser - typeAnnotation: $FlowFixMe, - types: TypeDeclarationMap, -): { - nullable: boolean, - typeAnnotation: $FlowFixMe, - typeAliasResolutionStatus: TypeAliasResolutionStatus, -} { - invariant( - typeAnnotation != null, - 'resolveTypeAnnotation(): typeAnnotation cannot be null', - ); - - let node = - typeAnnotation.type === 'TSTypeAnnotation' - ? typeAnnotation.typeAnnotation - : typeAnnotation; - let nullable = false; - let typeAliasResolutionStatus: TypeAliasResolutionStatus = { - successful: false, - }; - - for (;;) { - const topLevelType = parseTopLevelType(node); - nullable = nullable || topLevelType.optional; - node = topLevelType.type; - - if (node.type === 'TSTypeReference') { - typeAliasResolutionStatus = { - successful: true, - aliasName: node.typeName.name, - }; - const resolvedTypeAnnotation = types[node.typeName.name]; - if ( - resolvedTypeAnnotation == null || - resolvedTypeAnnotation.type === 'TSEnumDeclaration' - ) { - break; - } - - invariant( - resolvedTypeAnnotation.type === 'TSTypeAliasDeclaration', - `GenericTypeAnnotation '${node.typeName.name}' must resolve to a TSTypeAliasDeclaration. Instead, it resolved to a '${resolvedTypeAnnotation.type}'`, - ); - - node = resolvedTypeAnnotation.typeAnnotation; - } else { - break; - } - } - - return { - nullable: nullable, - typeAnnotation: node, - typeAliasResolutionStatus, - }; -} - -module.exports = { - resolveTypeAnnotation, - getTypes, -}; diff --git a/packages/react-native-codegen/src/parsers/utils.js b/packages/react-native-codegen/src/parsers/utils.js deleted file mode 100644 index ede91c81c2d7..000000000000 --- a/packages/react-native-codegen/src/parsers/utils.js +++ /dev/null @@ -1,266 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -'use strict'; - -import type {ComponentSchemaBuilderConfig} from './flow/components/schema'; -import type {NativeModuleSchema, SchemaType} from '../CodegenSchema'; -const {ParserError} = require('./errors'); -const {wrapModuleSchema} = require('./parsers-commons'); - -const fs = require('fs'); -const path = require('path'); -const invariant = require('invariant'); - -export type TypeDeclarationMap = {[declarationName: string]: $FlowFixMe}; - -export type TypeAliasResolutionStatus = - | $ReadOnly<{ - successful: true, - aliasName: string, - }> - | $ReadOnly<{ - successful: false, - }>; - -function extractNativeModuleName(filename: string): string { - // this should drop everything after the file name. For Example it will drop: - // .android.js, .android.ts, .android.tsx, .ios.js, .ios.ts, .ios.tsx, .js, .ts, .tsx - return path.basename(filename).split('.')[0]; -} - -export type ParserErrorCapturer = (fn: () => T) => ?T; - -function createParserErrorCapturer(): [ - Array, - ParserErrorCapturer, -] { - const errors = []; - function guard(fn: () => T): ?T { - try { - return fn(); - } catch (error) { - if (!(error instanceof ParserError)) { - throw error; - } - errors.push(error); - - return null; - } - } - - return [errors, guard]; -} - -function verifyPlatforms( - hasteModuleName: string, - moduleNames: string[], -): $ReadOnly<{ - cxxOnly: boolean, - excludedPlatforms: Array<'iOS' | 'android'>, -}> { - let cxxOnly = false; - const excludedPlatforms = new Set<'iOS' | 'android'>(); - const namesToValidate = [...moduleNames, hasteModuleName]; - - namesToValidate.forEach(name => { - if (name.endsWith('Android')) { - excludedPlatforms.add('iOS'); - return; - } - - if (name.endsWith('IOS')) { - excludedPlatforms.add('android'); - return; - } - - if (name.endsWith('Cxx')) { - cxxOnly = true; - excludedPlatforms.add('iOS'); - excludedPlatforms.add('android'); - return; - } - }); - - return { - cxxOnly, - excludedPlatforms: Array.from(excludedPlatforms), - }; -} - -function parseFile( - filename: string, - callback: (contents: string, filename: string) => SchemaType, -): SchemaType { - const contents = fs.readFileSync(filename, 'utf8'); - - return callback(contents, filename); -} - -// TODO(T108222691): Use flow-types for @babel/parser -function visit( - astNode: $FlowFixMe, - visitor: { - [type: string]: (node: $FlowFixMe) => void, - }, -) { - const queue = [astNode]; - while (queue.length !== 0) { - let item = queue.shift(); - - if (!(typeof item === 'object' && item != null)) { - continue; - } - - if ( - typeof item.type === 'string' && - typeof visitor[item.type] === 'function' - ) { - // Don't visit any children - visitor[item.type](item); - } else if (Array.isArray(item)) { - queue.push(...item); - } else { - queue.push(...Object.values(item)); - } - } -} - -function buildSchemaFromConfigType( - configType: 'module' | 'component' | 'none', - filename: ?string, - ast: $FlowFixMe, - wrapComponentSchema: (config: ComponentSchemaBuilderConfig) => SchemaType, - buildComponentSchema: (ast: $FlowFixMe) => ComponentSchemaBuilderConfig, - buildModuleSchema: ( - hasteModuleName: string, - ast: $FlowFixMe, - tryParse: ParserErrorCapturer, - ) => NativeModuleSchema, -): SchemaType { - switch (configType) { - case 'component': { - return wrapComponentSchema(buildComponentSchema(ast)); - } - case 'module': { - if (filename === undefined || filename === null) { - throw new Error('Filepath expected while parasing a module'); - } - const nativeModuleName = extractNativeModuleName(filename); - - const [parsingErrors, tryParse] = createParserErrorCapturer(); - - const schema = tryParse(() => - buildModuleSchema(nativeModuleName, ast, tryParse), - ); - - if (parsingErrors.length > 0) { - /** - * TODO(T77968131): We have two options: - * - Throw the first error, but indicate there are more then one errors. - * - Display all errors, nicely formatted. - * - * For the time being, we're just throw the first error. - **/ - - throw parsingErrors[0]; - } - - invariant( - schema != null, - 'When there are no parsing errors, the schema should not be null', - ); - - return wrapModuleSchema(schema, nativeModuleName); - } - default: - return {modules: {}}; - } -} - -function getConfigType( - // TODO(T71778680): Flow-type this node. - ast: $FlowFixMe, - Visitor: ({isComponent: boolean, isModule: boolean}) => { - [type: string]: (node: $FlowFixMe) => void, - }, -): 'module' | 'component' | 'none' { - let infoMap = { - isComponent: false, - isModule: false, - }; - - visit(ast, Visitor(infoMap)); - - const {isModule, isComponent} = infoMap; - if (isModule && isComponent) { - throw new Error( - 'Found type extending "TurboModule" and exported "codegenNativeComponent" declaration in one file. Split them into separated files.', - ); - } - - if (isModule) { - return 'module'; - } else if (isComponent) { - return 'component'; - } else { - return 'none'; - } -} - -// TODO(T71778680): Flow-type ASTNodes. -function isModuleRegistryCall(node: $FlowFixMe): boolean { - if (node.type !== 'CallExpression') { - return false; - } - - const callExpression = node; - - if (callExpression.callee.type !== 'MemberExpression') { - return false; - } - - const memberExpression = callExpression.callee; - if ( - !( - memberExpression.object.type === 'Identifier' && - memberExpression.object.name === 'TurboModuleRegistry' - ) - ) { - return false; - } - - if ( - !( - memberExpression.property.type === 'Identifier' && - (memberExpression.property.name === 'get' || - memberExpression.property.name === 'getEnforcing') - ) - ) { - return false; - } - - if (memberExpression.computed) { - return false; - } - - return true; -} - -module.exports = { - getConfigType, - extractNativeModuleName, - createParserErrorCapturer, - verifyPlatforms, - parseFile, - visit, - buildSchemaFromConfigType, - isModuleRegistryCall, -}; diff --git a/packages/react-native-gradle-plugin/BUCK b/packages/react-native-gradle-plugin/BUCK deleted file mode 100644 index 8fd38289431b..000000000000 --- a/packages/react-native-gradle-plugin/BUCK +++ /dev/null @@ -1,23 +0,0 @@ -load("@fbsource//tools/build_defs/third_party:yarn_defs.bzl", "yarn_workspace") - -yarn_workspace( - name = "yarn-workspace", - srcs = glob( - ["**/*.js"], - exclude = [ - "**/__fixtures__/**", - "**/__flowtests__/**", - "**/__mocks__/**", - "**/__server_snapshot_tests__/**", - "**/__tests__/**", - "**/node_modules/**", - "**/node_modules/.bin/**", - "**/.*", - "**/.*/**", - "**/.*/.*", - "**/*.xcodeproj/**", - "**/*.xcworkspace/**", - ], - ), - visibility = ["PUBLIC"], -) diff --git a/packages/react-native-gradle-plugin/README.md b/packages/react-native-gradle-plugin/README.md deleted file mode 100644 index dbe677a5740c..000000000000 --- a/packages/react-native-gradle-plugin/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# react-native-gradle-plugin - -[![Version][version-badge]][package] - -A Gradle Plugin used to support development of React Native applications for Android. - -## Installation - -``` -yarn add react-native-gradle-plugin -``` - -*Note: We're using `yarn` to install deps. Feel free to change commands to use `npm` 3+ and `npx` if you like* - -[version-badge]: https://img.shields.io/npm/v/react-native-gradle-plugin?style=flat-square -[package]: https://www.npmjs.com/package/react-native-gradle-plugin diff --git a/packages/react-native-gradle-plugin/build.gradle.kts b/packages/react-native-gradle-plugin/build.gradle.kts deleted file mode 100644 index 5ea92ee71b41..000000000000 --- a/packages/react-native-gradle-plugin/build.gradle.kts +++ /dev/null @@ -1,68 +0,0 @@ -/* - * 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. - */ - -import org.gradle.api.internal.classpath.ModuleRegistry -import org.gradle.api.tasks.testing.logging.TestExceptionFormat -import org.gradle.configurationcache.extensions.serviceOf -import org.jetbrains.kotlin.gradle.tasks.KotlinCompile - -plugins { - kotlin("jvm") version "1.6.10" - id("java-gradle-plugin") -} - -repositories { - google() - mavenCentral() -} - -gradlePlugin { - plugins { - create("react") { - id = "com.facebook.react" - implementationClass = "com.facebook.react.ReactPlugin" - } - } -} - -group = "com.facebook.react" - -dependencies { - implementation(gradleApi()) - implementation("com.android.tools.build:gradle:7.3.1") - implementation("com.google.code.gson:gson:2.8.9") - implementation("com.google.guava:guava:31.0.1-jre") - implementation("com.squareup:javapoet:1.13.0") - - testImplementation("junit:junit:4.13.2") - - testRuntimeOnly( - files( - serviceOf() - .getModule("gradle-tooling-api-builders") - .classpath - .asFiles - .first())) -} - -java { - sourceCompatibility = JavaVersion.VERSION_11 - targetCompatibility = JavaVersion.VERSION_11 -} - -tasks.withType { - kotlinOptions { jvmTarget = JavaVersion.VERSION_11.majorVersion } -} - -tasks.withType().configureEach { - testLogging { - exceptionFormat = TestExceptionFormat.FULL - showExceptions = true - showCauses = true - showStackTraces = true - } -} diff --git a/packages/react-native-gradle-plugin/gradle/wrapper/gradle-wrapper.jar b/packages/react-native-gradle-plugin/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 41d9927a4d4f..000000000000 Binary files a/packages/react-native-gradle-plugin/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/packages/react-native-gradle-plugin/gradle/wrapper/gradle-wrapper.properties b/packages/react-native-gradle-plugin/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 8fad3f5a98bf..000000000000 --- a/packages/react-native-gradle-plugin/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-all.zip -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/packages/react-native-gradle-plugin/gradlew b/packages/react-native-gradle-plugin/gradlew deleted file mode 100755 index 1b6c787337ff..000000000000 --- a/packages/react-native-gradle-plugin/gradlew +++ /dev/null @@ -1,234 +0,0 @@ -#!/bin/sh - -# -# Copyright © 2015-2021 the original authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -############################################################################## -# -# Gradle start up script for POSIX generated by Gradle. -# -# Important for running: -# -# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is -# noncompliant, but you have some other compliant shell such as ksh or -# bash, then to run this script, type that shell name before the whole -# command line, like: -# -# ksh Gradle -# -# Busybox and similar reduced shells will NOT work, because this script -# requires all of these POSIX shell features: -# * functions; -# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», -# «${var#prefix}», «${var%suffix}», and «$( cmd )»; -# * compound commands having a testable exit status, especially «case»; -# * various built-in commands including «command», «set», and «ulimit». -# -# Important for patching: -# -# (2) This script targets any POSIX shell, so it avoids extensions provided -# by Bash, Ksh, etc; in particular arrays are avoided. -# -# The "traditional" practice of packing multiple parameters into a -# space-separated string is a well documented source of bugs and security -# problems, so this is (mostly) avoided, by progressively accumulating -# options in "$@", and eventually passing that to Java. -# -# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, -# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; -# see the in-line comments for details. -# -# There are tweaks for specific operating systems such as AIX, CygWin, -# Darwin, MinGW, and NonStop. -# -# (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt -# within the Gradle project. -# -# You can find Gradle at https://github.com/gradle/gradle/. -# -############################################################################## - -# Attempt to set APP_HOME - -# Resolve links: $0 may be a link -app_path=$0 - -# Need this for daisy-chained symlinks. -while - APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path - [ -h "$app_path" ] -do - ls=$( ls -ld "$app_path" ) - link=${ls#*' -> '} - case $link in #( - /*) app_path=$link ;; #( - *) app_path=$APP_HOME$link ;; - esac -done - -APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit - -APP_NAME="Gradle" -APP_BASE_NAME=${0##*/} - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD=maximum - -warn () { - echo "$*" -} >&2 - -die () { - echo - echo "$*" - echo - exit 1 -} >&2 - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "$( uname )" in #( - CYGWIN* ) cygwin=true ;; #( - Darwin* ) darwin=true ;; #( - MSYS* | MINGW* ) msys=true ;; #( - NONSTOP* ) nonstop=true ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD=$JAVA_HOME/jre/sh/java - else - JAVACMD=$JAVA_HOME/bin/java - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD=java - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then - case $MAX_FD in #( - max*) - MAX_FD=$( ulimit -H -n ) || - warn "Could not query maximum file descriptor limit" - esac - case $MAX_FD in #( - '' | soft) :;; #( - *) - ulimit -n "$MAX_FD" || - warn "Could not set maximum file descriptor limit to $MAX_FD" - esac -fi - -# Collect all arguments for the java command, stacking in reverse order: -# * args from the command line -# * the main class name -# * -classpath -# * -D...appname settings -# * --module-path (only if needed) -# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. - -# For Cygwin or MSYS, switch paths to Windows format before running java -if "$cygwin" || "$msys" ; then - APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) - CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) - - JAVACMD=$( cygpath --unix "$JAVACMD" ) - - # Now convert the arguments - kludge to limit ourselves to /bin/sh - for arg do - if - case $arg in #( - -*) false ;; # don't mess with options #( - /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath - [ -e "$t" ] ;; #( - *) false ;; - esac - then - arg=$( cygpath --path --ignore --mixed "$arg" ) - fi - # Roll the args list around exactly as many times as the number of - # args, so each arg winds up back in the position where it started, but - # possibly modified. - # - # NB: a `for` loop captures its iteration list before it begins, so - # changing the positional parameters here affects neither the number of - # iterations, nor the values presented in `arg`. - shift # remove old arg - set -- "$@" "$arg" # push replacement arg - done -fi - -# Collect all arguments for the java command; -# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of -# shell script including quotes and variable substitutions, so put them in -# double quotes to make sure that they get re-expanded; and -# * put everything else in single quotes, so that it's not re-expanded. - -set -- \ - "-Dorg.gradle.appname=$APP_BASE_NAME" \ - -classpath "$CLASSPATH" \ - org.gradle.wrapper.GradleWrapperMain \ - "$@" - -# Use "xargs" to parse quoted args. -# -# With -n1 it outputs one arg per line, with the quotes and backslashes removed. -# -# In Bash we could simply go: -# -# readarray ARGS < <( xargs -n1 <<<"$var" ) && -# set -- "${ARGS[@]}" "$@" -# -# but POSIX shell has neither arrays nor command substitution, so instead we -# post-process each arg (as a line of input to sed) to backslash-escape any -# character that might be a shell metacharacter, then use eval to reverse -# that process (while maintaining the separation between arguments), and wrap -# the whole thing up as a single "set" statement. -# -# This will of course break if any of these variables contains a newline or -# an unmatched quote. -# - -eval "set -- $( - printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | - xargs -n1 | - sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | - tr '\n' ' ' - )" '"$@"' - -exec "$JAVACMD" "$@" diff --git a/packages/react-native-gradle-plugin/gradlew.bat b/packages/react-native-gradle-plugin/gradlew.bat deleted file mode 100644 index ac1b06f93825..000000000000 --- a/packages/react-native-gradle-plugin/gradlew.bat +++ /dev/null @@ -1,89 +0,0 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/packages/react-native-gradle-plugin/package.json b/packages/react-native-gradle-plugin/package.json deleted file mode 100644 index 235bfe988d4e..000000000000 --- a/packages/react-native-gradle-plugin/package.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "react-native-gradle-plugin", - "version": "0.71.19", - "description": "⚛️ Gradle Plugin for React Native", - "homepage": "https://github.com/facebook/react-native/tree/HEAD/packages/react-native-gradle-plugin", - "repository": { - "type": "git", - "url": "git@github.com:facebook/react-native.git", - "directory": "packages/react-native-gradle-plugin" - }, - "scripts": { - "build": "./gradlew build", - "clean": "./gradlew clean", - "test": "./gradlew check" - }, - "license": "MIT", - "files": [ - "settings.gradle.kts", - "build.gradle.kts", - "gradle", - "gradlew", - "gradlew.bat", - "src/main", - "README.md" - ], - "dependencies": {}, - "devDependencies": {} -} diff --git a/packages/react-native-gradle-plugin/settings.gradle.kts b/packages/react-native-gradle-plugin/settings.gradle.kts deleted file mode 100644 index 8daf82d475af..000000000000 --- a/packages/react-native-gradle-plugin/settings.gradle.kts +++ /dev/null @@ -1,16 +0,0 @@ -/* - * 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. - */ - -pluginManagement { - repositories { - mavenCentral() - google() - gradlePluginPortal() - } -} - -rootProject.name = "react-native-gradle-plugin" diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactExtension.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactExtension.kt deleted file mode 100644 index 9738124c7946..000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactExtension.kt +++ /dev/null @@ -1,151 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react - -import com.facebook.react.utils.projectPathToLibraryName -import javax.inject.Inject -import org.gradle.api.Project -import org.gradle.api.file.DirectoryProperty -import org.gradle.api.file.RegularFileProperty -import org.gradle.api.provider.ListProperty -import org.gradle.api.provider.Property - -abstract class ReactExtension @Inject constructor(project: Project) { - - private val objects = project.objects - - /** - * The path to the root of your project. This is the path to where the `package.json` lives. All - * the CLI commands will be invoked from this folder as working directory. - * - * Default: ${rootProject.dir}/../ - */ - val root: DirectoryProperty = - objects.directoryProperty().convention(project.rootProject.layout.projectDirectory.dir("../")) - - /** - * The path to the react-native NPM package folder. - * - * Default: ${rootProject.dir}/../node_modules/react-native-codegen - */ - val reactNativeDir: DirectoryProperty = - objects.directoryProperty().convention(root.dir("node_modules/react-native")) - - /** - * The path to the JS entry file. If not specified, the plugin will try to resolve it using a list - * of known locations (e.g. `index.android.js`, `index.js`, etc.). - */ - val entryFile: RegularFileProperty = objects.fileProperty() - - /** - * The reference to the React Native CLI. If not specified, the plugin will try to resolve it - * looking for `react-native` CLI inside `node_modules` in [root]. - */ - val cliFile: RegularFileProperty = - objects.fileProperty().convention(reactNativeDir.file("cli.js")) - - /** - * The path to the Node executable and extra args. By default it assumes that you have `node` - * installed and configured in your $PATH. Default: ["node"] - */ - val nodeExecutableAndArgs: ListProperty = - objects.listProperty(String::class.java).convention(listOf("node")) - - /** The command to use to invoke bundle. Default is `bundle` and will be invoked on [root]. */ - val bundleCommand: Property = objects.property(String::class.java).convention("bundle") - - /** - * Custom configuration file for the [bundleCommand]. If provided, it will be passed over with a - * `--config` flag to the bundle command. - */ - val bundleConfig: RegularFileProperty = objects.fileProperty() - - /** - * The Bundle Asset name. This name will be used also for deriving other bundle outputs such as - * the packager source map, the compiler source map and the output source map file. - * - * Default: index.android.bundle - */ - val bundleAssetName: Property = - objects.property(String::class.java).convention("index.android.bundle") - - /** - * Toggles the .so Cleanup step. If enabled, we will clean up all the unnecessary files before the - * bundle task. If disabled, the developers will have to manually cleanup the files. Default: true - */ - val enableSoCleanup: Property = objects.property(Boolean::class.java).convention(true) - - /** Extra args that will be passed to the [bundleCommand] Default: [] */ - val extraPackagerArgs: ListProperty = - objects.listProperty(String::class.java).convention(emptyList()) - - /** - * Allows to specify the debuggable variants (by default just 'debug'). Variants in this list - * will: - * - Not be bundled (the bundle file will not be created and won't be copied over). - * - Have the Hermes Debug flags set. That's useful if you have another variant (say `canary`) - * where you want dev mode to be enabled. Default: ['debug'] - */ - val debuggableVariants: ListProperty = - objects.listProperty(String::class.java).convention(listOf("debug")) - - /** Hermes Config */ - - /** - * The command to use to invoke hermesc (the hermes compiler). Default is "", the plugin will - * autodetect it. - */ - val hermesCommand: Property = objects.property(String::class.java).convention("") - - /** - * Whether to enable Hermes only on certain variants. If specified as a non-empty list, hermesc - * and the .so cleanup for Hermes will be executed only for variants in this list. An empty list - * assumes you're either using Hermes for all variants or not (see [enableHermes]). - * - * Default: [] - */ - val enableHermesOnlyInVariants: ListProperty = - objects.listProperty(String::class.java).convention(emptyList()) - - /** Flags to pass to Hermesc. Default: ["-O", "-output-source-map"] */ - val hermesFlags: ListProperty = - objects.listProperty(String::class.java).convention(listOf("-O", "-output-source-map")) - - /** Codegen Config */ - - /** - * The path to the react-native-codegen NPM package folder. - * - * Default: ${rootProject.dir}/../node_modules/react-native-codegen - */ - val codegenDir: DirectoryProperty = - objects.directoryProperty().convention(root.dir("node_modules/react-native-codegen")) - - /** - * The root directory for all JS files for the app. - * - * Default: the parent folder of the `/android` folder. - */ - val jsRootDir: DirectoryProperty = objects.directoryProperty() - - /** - * The library name that will be used for the codegen artifacts. - * - * Default: Spec (e.g. for :example:project it will be - * ExampleProjectSpec). - */ - val libraryName: Property = - objects.property(String::class.java).convention(projectPathToLibraryName(project.path)) - - /** - * Java package name to use for any codegen artifacts produced during build time. Default: - * com.facebook.fbreact.specs - */ - val codegenJavaPackageName: Property = - objects.property(String::class.java).convention("com.facebook.fbreact.specs") -} diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactPlugin.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactPlugin.kt deleted file mode 100644 index 25ee481d3d9f..000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactPlugin.kt +++ /dev/null @@ -1,212 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react - -import com.android.build.api.variant.AndroidComponentsExtension -import com.android.build.gradle.AppExtension -import com.android.build.gradle.internal.tasks.factory.dependsOn -import com.facebook.react.internal.PrivateReactExtension -import com.facebook.react.tasks.BuildCodegenCLITask -import com.facebook.react.tasks.GenerateCodegenArtifactsTask -import com.facebook.react.tasks.GenerateCodegenSchemaTask -import com.facebook.react.utils.AgpConfiguratorUtils.configureBuildConfigFields -import com.facebook.react.utils.AgpConfiguratorUtils.configureDevPorts -import com.facebook.react.utils.BackwardCompatUtils.configureBackwardCompatibilityReactMap -import com.facebook.react.utils.DependencyUtils.configureDependencies -import com.facebook.react.utils.DependencyUtils.configureRepositories -import com.facebook.react.utils.DependencyUtils.readVersionAndGroupStrings -import com.facebook.react.utils.JsonUtils -import com.facebook.react.utils.NdkConfiguratorUtils.configureReactNativeNdk -import com.facebook.react.utils.ProjectUtils.needsCodegenFromPackageJson -import com.facebook.react.utils.findPackageJsonFile -import java.io.File -import kotlin.system.exitProcess -import org.gradle.api.Plugin -import org.gradle.api.Project -import org.gradle.api.Task -import org.gradle.internal.jvm.Jvm - -class ReactPlugin : Plugin { - override fun apply(project: Project) { - checkJvmVersion(project) - val extension = project.extensions.create("react", ReactExtension::class.java, project) - - // We register a private extension on the rootProject so that project wide configs - // like codegen config can be propagated from app project to libraries. - val rootExtension = - project.rootProject.extensions.findByType(PrivateReactExtension::class.java) - ?: project.rootProject.extensions.create( - "privateReact", PrivateReactExtension::class.java, project) - - // App Only Configuration - project.pluginManager.withPlugin("com.android.application") { - // We wire the root extension with the values coming from the app (either user populated or - // defaults). - rootExtension.root.set(extension.root) - rootExtension.reactNativeDir.set(extension.reactNativeDir) - rootExtension.codegenDir.set(extension.codegenDir) - rootExtension.nodeExecutableAndArgs.set(extension.nodeExecutableAndArgs) - - project.afterEvaluate { - val reactNativeDir = extension.reactNativeDir.get().asFile - val propertiesFile = File(reactNativeDir, "ReactAndroid/gradle.properties") - val versionAndGroupStrings = readVersionAndGroupStrings(propertiesFile) - val versionString = versionAndGroupStrings.first - val groupString = versionAndGroupStrings.second - configureDependencies(project, versionString, groupString) - configureRepositories(project, reactNativeDir) - } - - configureReactNativeNdk(project, extension) - configureBuildConfigFields(project) - configureDevPorts(project) - configureBackwardCompatibilityReactMap(project) - - project.extensions.getByType(AndroidComponentsExtension::class.java).apply { - onVariants(selector().all()) { variant -> - project.configureReactTasks(variant = variant, config = extension) - } - } - - // This is a legacy AGP api. Needed as AGP 7.3 is not consuming generated resources correctly. - // Can be removed as we bump to AGP 7.4 stable. - // This registers the $buildDir/generated/res/react/ folder as a - // res folder to be consumed with the old AGP Apis which are not broken. - project.extensions.getByType(AppExtension::class.java).apply { - this.applicationVariants.all { variant -> - val isDebuggableVariant = - extension.debuggableVariants.get().any { it.equals(variant.name, ignoreCase = true) } - val targetName = variant.name.replaceFirstChar { it.uppercase() } - val bundleTaskName = "createBundle${targetName}JsAndAssets" - if (!isDebuggableVariant) { - variant.registerGeneratedResFolders( - project.layout.buildDirectory.files("generated/res/react/${variant.name}")) - variant.mergeResourcesProvider.get().dependsOn(bundleTaskName) - } - } - } - configureCodegen(project, extension, rootExtension, isLibrary = false) - } - - // Library Only Configuration - project.pluginManager.withPlugin("com.android.library") { - configureCodegen(project, extension, rootExtension, isLibrary = true) - } - } - - private fun checkJvmVersion(project: Project) { - val jvmVersion = Jvm.current()?.javaVersion?.majorVersion - if ((jvmVersion?.toIntOrNull() ?: 0) <= 8) { - project.logger.error( - """ - - ******************************************************************************** - - ERROR: requires JDK11 or higher. - Incompatible major version detected: '$jvmVersion' - - ******************************************************************************** - - """ - .trimIndent()) - exitProcess(1) - } - } - - /** This function sets up `react-native-codegen` in our Gradle plugin. */ - @Suppress("UnstableApiUsage") - private fun configureCodegen( - project: Project, - localExtension: ReactExtension, - rootExtension: PrivateReactExtension, - isLibrary: Boolean - ) { - // First, we set up the output dir for the codegen. - val generatedSrcDir = File(project.buildDir, "generated/source/codegen") - - // We specify the default value (convention) for jsRootDir. - // It's the root folder for apps (so ../../ from the Gradle project) - // and the package folder for library (so ../ from the Gradle project) - if (isLibrary) { - localExtension.jsRootDir.convention(project.layout.projectDirectory.dir("../")) - } else { - localExtension.jsRootDir.convention(localExtension.root) - } - - val buildCodegenTask = - project.tasks.register("buildCodegenCLI", BuildCodegenCLITask::class.java) { - it.codegenDir.set(rootExtension.codegenDir) - val bashWindowsHome = project.findProperty("REACT_WINDOWS_BASH") as String? - it.bashWindowsHome.set(bashWindowsHome) - - // Please note that appNeedsCodegen is triggering a read of the package.json at - // configuration time as we need to feed the onlyIf condition of this task. - // Therefore, the appNeedsCodegen needs to be invoked inside this lambda. - val needsCodegenFromPackageJson = project.needsCodegenFromPackageJson(rootExtension.root) - it.onlyIf { isLibrary || needsCodegenFromPackageJson } - } - - // We create the task to produce schema from JS files. - val generateCodegenSchemaTask = - project.tasks.register( - "generateCodegenSchemaFromJavaScript", GenerateCodegenSchemaTask::class.java) { it -> - it.dependsOn(buildCodegenTask) - it.nodeExecutableAndArgs.set(rootExtension.nodeExecutableAndArgs) - it.codegenDir.set(rootExtension.codegenDir) - it.generatedSrcDir.set(generatedSrcDir) - - // We're reading the package.json at configuration time to properly feed - // the `jsRootDir` @Input property of this task & the onlyIf. Therefore, the - // parsePackageJson should be invoked inside this lambda. - val packageJson = findPackageJsonFile(project, rootExtension.root) - val parsedPackageJson = packageJson?.let { JsonUtils.fromCodegenJson(it) } - - val jsSrcsDirInPackageJson = parsedPackageJson?.codegenConfig?.jsSrcsDir - if (jsSrcsDirInPackageJson != null) { - it.jsRootDir.set(File(packageJson.parentFile, jsSrcsDirInPackageJson)) - } else { - it.jsRootDir.set(localExtension.jsRootDir) - } - val needsCodegenFromPackageJson = - project.needsCodegenFromPackageJson(rootExtension.root) - it.onlyIf { isLibrary || needsCodegenFromPackageJson } - } - - // We create the task to generate Java code from schema. - val generateCodegenArtifactsTask = - project.tasks.register( - "generateCodegenArtifactsFromSchema", GenerateCodegenArtifactsTask::class.java) { - it.dependsOn(generateCodegenSchemaTask) - it.reactNativeDir.set(rootExtension.reactNativeDir) - it.nodeExecutableAndArgs.set(rootExtension.nodeExecutableAndArgs) - it.generatedSrcDir.set(generatedSrcDir) - it.packageJsonFile.set(findPackageJsonFile(project, rootExtension.root)) - it.codegenJavaPackageName.set(localExtension.codegenJavaPackageName) - it.libraryName.set(localExtension.libraryName) - - // Please note that appNeedsCodegen is triggering a read of the package.json at - // configuration time as we need to feed the onlyIf condition of this task. - // Therefore, the appNeedsCodegen needs to be invoked inside this lambda. - val needsCodegenFromPackageJson = - project.needsCodegenFromPackageJson(rootExtension.root) - it.onlyIf { isLibrary || needsCodegenFromPackageJson } - } - - // We update the android configuration to include the generated sources. - // This equivalent to this DSL: - // - // android { sourceSets { main { java { srcDirs += "$generatedSrcDir/java" } } } } - project.extensions.getByType(AndroidComponentsExtension::class.java).finalizeDsl { ext -> - ext.sourceSets.getByName("main").java.srcDir(File(generatedSrcDir, "java")) - } - - // `preBuild` is one of the base tasks automatically registered by AGP. - // This will invoke the codegen before compiling the entire project. - project.tasks.named("preBuild", Task::class.java).dependsOn(generateCodegenArtifactsTask) - } -} diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/TaskConfiguration.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/TaskConfiguration.kt deleted file mode 100644 index c7db4db88341..000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/TaskConfiguration.kt +++ /dev/null @@ -1,81 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react - -import com.android.build.api.variant.Variant -import com.facebook.react.tasks.BundleHermesCTask -import com.facebook.react.utils.NdkConfiguratorUtils.configureJsEnginePackagingOptions -import com.facebook.react.utils.NdkConfiguratorUtils.configureNewArchPackagingOptions -import com.facebook.react.utils.ProjectUtils.isHermesEnabled -import com.facebook.react.utils.detectedCliFile -import com.facebook.react.utils.detectedEntryFile -import java.io.File -import org.gradle.api.Project - -@Suppress("SpreadOperator", "UnstableApiUsage") -internal fun Project.configureReactTasks(variant: Variant, config: ReactExtension) { - val targetName = variant.name.replaceFirstChar { it.uppercase() } - val targetPath = variant.name - - // Resources: generated/assets/react//index.android.bundle - val resourcesDir = File(buildDir, "generated/res/react/$targetPath") - // Bundle: generated/assets/react//index.android.bundle - val jsBundleDir = File(buildDir, "generated/assets/react/$targetPath") - // Sourcemap: generated/sourcemaps/react//index.android.bundle.map - val jsSourceMapsDir = File(buildDir, "generated/sourcemaps/react/$targetPath") - // Intermediate packager: - // intermediates/sourcemaps/react//index.android.bundle.packager.map - // Intermediate compiler: - // intermediates/sourcemaps/react//index.android.bundle.compiler.map - val jsIntermediateSourceMapsDir = File(buildDir, "intermediates/sourcemaps/react/$targetPath") - - // The location of the cli.js file for React Native - val cliFile = detectedCliFile(config) - - val isHermesEnabledInProject = project.isHermesEnabled - val isHermesEnabledInThisVariant = - if (config.enableHermesOnlyInVariants.get().isNotEmpty()) { - config.enableHermesOnlyInVariants.get().contains(variant.name) && isHermesEnabledInProject - } else { - isHermesEnabledInProject - } - val isDebuggableVariant = - config.debuggableVariants.get().any { it.equals(variant.name, ignoreCase = true) } - - configureNewArchPackagingOptions(project, variant) - configureJsEnginePackagingOptions(config, variant, isHermesEnabledInThisVariant) - - if (!isDebuggableVariant) { - val entryFileEnvVariable = System.getenv("ENTRY_FILE") - val bundleTask = - tasks.register("createBundle${targetName}JsAndAssets", BundleHermesCTask::class.java) { - it.root.set(config.root) - it.nodeExecutableAndArgs.set(config.nodeExecutableAndArgs) - it.cliFile.set(cliFile) - it.bundleCommand.set(config.bundleCommand) - it.entryFile.set(detectedEntryFile(config, entryFileEnvVariable)) - it.extraPackagerArgs.set(config.extraPackagerArgs) - it.bundleConfig.set(config.bundleConfig) - it.bundleAssetName.set(config.bundleAssetName) - it.jsBundleDir.set(jsBundleDir) - it.resourcesDir.set(resourcesDir) - it.hermesEnabled.set(isHermesEnabledInThisVariant) - it.minifyEnabled.set(!isHermesEnabledInThisVariant) - it.devEnabled.set(false) - it.jsIntermediateSourceMapsDir.set(jsIntermediateSourceMapsDir) - it.jsSourceMapsDir.set(jsSourceMapsDir) - it.hermesCommand.set(config.hermesCommand) - it.hermesFlags.set(config.hermesFlags) - it.reactNativeDir.set(config.reactNativeDir) - } - // Currently broken inside AGP 7.3 We need to wait for a release of AGP 7.4 in order to use - // the addGeneratedSourceDirectory API. - // variant.sources.res?.addGeneratedSourceDirectory(bundleTask, BundleHermesCTask::resourcesDir) - variant.sources.assets?.addGeneratedSourceDirectory(bundleTask, BundleHermesCTask::jsBundleDir) - } -} diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/internal/PrivateReactExtension.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/internal/PrivateReactExtension.kt deleted file mode 100644 index 011640ba086d..000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/internal/PrivateReactExtension.kt +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.internal - -import javax.inject.Inject -import org.gradle.api.Project -import org.gradle.api.file.DirectoryProperty -import org.gradle.api.provider.ListProperty - -/** - * A private extension we set on the rootProject to make easier to share values at execution time - * between app project and library project. - * - * Specifically, the [codegenDir], [reactNativeDir] and other properties should be provided by apps - * (for setups like a monorepo which are app specific) and libraries should honor those values. - * - * Users are not supposed to access directly this extension from their build.gradle file. - */ -abstract class PrivateReactExtension @Inject constructor(project: Project) { - - private val objects = project.objects - - val root: DirectoryProperty = - objects - .directoryProperty() - .convention( - // This is the default for the project root if the users hasn't specified anything. - // If the project is called "react-native-github" - // - We're inside the Github Repo -> root is defined by RN Tester (so no default - // needed) - // - We're inside an includedBuild as we're performing a build from source - // (then we're inside `node_modules/react-native`, so default should be ../../) - // If the project is called in any other name - // - We're inside a user project, so inside the ./android folder. Default should be - // ../ - // User can always override this default by setting a `root =` inside the template. - if (project.rootProject.name == "react-native-github") { - project.rootProject.layout.projectDirectory.dir("../../") - } else { - project.rootProject.layout.projectDirectory.dir("../") - }) - - val reactNativeDir: DirectoryProperty = - objects.directoryProperty().convention(root.dir("node_modules/react-native")) - - val nodeExecutableAndArgs: ListProperty = - objects.listProperty(String::class.java).convention(listOf("node")) - - val codegenDir: DirectoryProperty = - objects.directoryProperty().convention(root.dir("node_modules/react-native-codegen")) -} diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/model/ModelCodegenConfig.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/model/ModelCodegenConfig.kt deleted file mode 100644 index 26d7f08d95d3..000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/model/ModelCodegenConfig.kt +++ /dev/null @@ -1,15 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.model - -data class ModelCodegenConfig( - val name: String?, - val type: String?, - val jsSrcsDir: String?, - val android: ModelCodegenConfigAndroid? -) diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/model/ModelCodegenConfigAndroid.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/model/ModelCodegenConfigAndroid.kt deleted file mode 100644 index 7619098a8dbc..000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/model/ModelCodegenConfigAndroid.kt +++ /dev/null @@ -1,10 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.model - -data class ModelCodegenConfigAndroid(val javaPackageName: String?) diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/model/ModelPackageJson.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/model/ModelPackageJson.kt deleted file mode 100644 index 96e2bd22d704..000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/model/ModelPackageJson.kt +++ /dev/null @@ -1,10 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.model - -data class ModelPackageJson(val codegenConfig: ModelCodegenConfig?) diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/BuildCodegenCLITask.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/BuildCodegenCLITask.kt deleted file mode 100644 index 9bc1ddba1734..000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/BuildCodegenCLITask.kt +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.tasks - -import com.facebook.react.utils.Os.unixifyPath -import com.facebook.react.utils.windowsAwareBashCommandLine -import org.gradle.api.file.DirectoryProperty -import org.gradle.api.file.FileCollection -import org.gradle.api.provider.Property -import org.gradle.api.tasks.* - -/** - * A Task that will call the `scripts/oss/build.sh` script to trigger the creation of the codegen - * lib artifacts. - * - * NOTE: This task is required when using react-native-codegen from source, instead of npm. - */ -abstract class BuildCodegenCLITask : Exec() { - - @get:Internal abstract val codegenDir: DirectoryProperty - - @get:Internal abstract val bashWindowsHome: Property - - @get:InputFiles - val input: FileCollection by lazy { - codegenDir.get().files("scripts", "src", "package.json", ".babelrc", ".prettierrc") - } - - @get:OutputDirectories - val output: FileCollection by lazy { codegenDir.get().files("lib", "node_modules") } - - init { - // We need this condition as we want a single instance of BuildCodegenCLITask to execute - // per project. Therefore we can safely skip the task if the lib/cli/ folder is available. - onlyIf { - val cliDir = codegenDir.file("lib/cli/").get().asFile - !cliDir.exists() || cliDir.listFiles()?.size == 0 - } - } - - override fun exec() { - commandLine( - windowsAwareBashCommandLine( - codegenDir.asFile.get().canonicalPath.unixifyPath().plus(BUILD_SCRIPT_PATH), - bashWindowsHome = bashWindowsHome.orNull, - )) - super.exec() - } - - companion object { - private const val BUILD_SCRIPT_PATH = "/scripts/oss/build.sh" - } -} diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/BundleHermesCTask.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/BundleHermesCTask.kt deleted file mode 100644 index 2eb989143b80..000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/BundleHermesCTask.kt +++ /dev/null @@ -1,196 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.tasks - -import com.facebook.react.utils.Os.cliPath -import com.facebook.react.utils.detectOSAwareHermesCommand -import com.facebook.react.utils.moveTo -import com.facebook.react.utils.windowsAwareCommandLine -import java.io.File -import org.gradle.api.DefaultTask -import org.gradle.api.file.ConfigurableFileTree -import org.gradle.api.file.DirectoryProperty -import org.gradle.api.file.RegularFileProperty -import org.gradle.api.provider.ListProperty -import org.gradle.api.provider.Property -import org.gradle.api.tasks.* - -abstract class BundleHermesCTask : DefaultTask() { - - init { - group = "react" - } - - @get:Internal abstract val root: DirectoryProperty - - @get:InputFiles - val sources: ConfigurableFileTree = - project.fileTree(root) { - it.include("**/*.js") - it.include("**/*.jsx") - it.include("**/*.ts") - it.include("**/*.tsx") - it.exclude("**/android/**/*") - it.exclude("**/ios/**/*") - it.exclude("**/build/**/*") - it.exclude("**/node_modules/**/*") - } - - @get:Input abstract val nodeExecutableAndArgs: ListProperty - - @get:InputFile abstract val cliFile: RegularFileProperty - - @get:Internal abstract val reactNativeDir: DirectoryProperty - - @get:Input abstract val bundleCommand: Property - - @get:InputFile abstract val entryFile: RegularFileProperty - - @get:InputFile @get:Optional abstract val bundleConfig: RegularFileProperty - - @get:Input abstract val bundleAssetName: Property - - @get:Input abstract val minifyEnabled: Property - - @get:Input abstract val hermesEnabled: Property - - @get:Input abstract val devEnabled: Property - - @get:Input abstract val extraPackagerArgs: ListProperty - - @get:Input abstract val hermesCommand: Property - - @get:Input abstract val hermesFlags: ListProperty - - @get:OutputDirectory abstract val jsBundleDir: DirectoryProperty - - @get:OutputDirectory abstract val resourcesDir: DirectoryProperty - - @get:OutputDirectory abstract val jsIntermediateSourceMapsDir: RegularFileProperty - - @get:OutputDirectory abstract val jsSourceMapsDir: DirectoryProperty - - @TaskAction - fun run() { - jsBundleDir.get().asFile.mkdirs() - resourcesDir.get().asFile.mkdirs() - jsIntermediateSourceMapsDir.get().asFile.mkdirs() - jsSourceMapsDir.get().asFile.mkdirs() - val bundleAssetFilename = bundleAssetName.get() - - val bundleFile = File(jsBundleDir.get().asFile, bundleAssetFilename) - val packagerSourceMap = resolvePackagerSourceMapFile(bundleAssetFilename) - - val bundleCommand = getBundleCommand(bundleFile, packagerSourceMap) - runCommand(bundleCommand) - - if (hermesEnabled.get()) { - val detectedHermesCommand = detectOSAwareHermesCommand(root.get().asFile, hermesCommand.get()) - val bytecodeFile = File("${bundleFile}.hbc") - val outputSourceMap = resolveOutputSourceMap(bundleAssetFilename) - val compilerSourceMap = resolveCompilerSourceMap(bundleAssetFilename) - - val hermesCommand = getHermescCommand(detectedHermesCommand, bytecodeFile, bundleFile) - runCommand(hermesCommand) - bytecodeFile.moveTo(bundleFile) - - if (hermesFlags.get().contains("-output-source-map")) { - val hermesTempSourceMapFile = File("$bytecodeFile.map") - hermesTempSourceMapFile.moveTo(compilerSourceMap) - - val reactNativeDir = reactNativeDir.get().asFile - val composeScriptFile = File(reactNativeDir, "scripts/compose-source-maps.js") - val composeSourceMapsCommand = - getComposeSourceMapsCommand( - composeScriptFile, packagerSourceMap, compilerSourceMap, outputSourceMap) - runCommand(composeSourceMapsCommand) - } - } - } - - internal fun resolvePackagerSourceMapFile(bundleAssetName: String) = - if (hermesEnabled.get()) { - File(jsIntermediateSourceMapsDir.get().asFile, "$bundleAssetName.packager.map") - } else { - resolveOutputSourceMap(bundleAssetName) - } - - internal fun resolveOutputSourceMap(bundleAssetName: String) = - File(jsSourceMapsDir.get().asFile, "$bundleAssetName.map") - - internal fun resolveCompilerSourceMap(bundleAssetName: String) = - File(jsIntermediateSourceMapsDir.get().asFile, "$bundleAssetName.compiler.map") - - private fun runCommand(command: List) { - project.exec { - it.workingDir(root.get().asFile) - it.commandLine(command) - } - } - - internal fun getBundleCommand(bundleFile: File, sourceMapFile: File): List = - windowsAwareCommandLine( - buildList { - val rootFile = root.get().asFile - addAll(nodeExecutableAndArgs.get()) - add(cliFile.get().asFile.cliPath(rootFile)) - add(bundleCommand.get()) - add("--platform") - add("android") - add("--dev") - add(devEnabled.get().toString()) - add("--reset-cache") - add("--entry-file") - add(entryFile.get().asFile.cliPath(rootFile)) - add("--bundle-output") - add(bundleFile.cliPath(rootFile)) - add("--assets-dest") - add(resourcesDir.get().asFile.cliPath(rootFile)) - add("--sourcemap-output") - add(sourceMapFile.cliPath(rootFile)) - if (bundleConfig.isPresent) { - add("--config") - add(bundleConfig.get().asFile.cliPath(rootFile)) - } - add("--minify") - add(minifyEnabled.get().toString()) - addAll(extraPackagerArgs.get()) - add("--verbose") - }) - - internal fun getHermescCommand( - hermesCommand: String, - bytecodeFile: File, - bundleFile: File - ): List { - val rootFile = root.get().asFile - return windowsAwareCommandLine( - hermesCommand, - "-emit-binary", - "-out", - bytecodeFile.cliPath(rootFile), - bundleFile.cliPath(rootFile), - *hermesFlags.get().toTypedArray()) - } - - internal fun getComposeSourceMapsCommand( - composeScript: File, - packagerSourceMap: File, - compilerSourceMap: File, - outputSourceMap: File - ): List { - val rootFile = root.get().asFile - return windowsAwareCommandLine( - *nodeExecutableAndArgs.get().toTypedArray(), - composeScript.cliPath(rootFile), - packagerSourceMap.cliPath(rootFile), - compilerSourceMap.cliPath(rootFile), - "-o", - outputSourceMap.cliPath(rootFile)) - } -} diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/GenerateCodegenArtifactsTask.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/GenerateCodegenArtifactsTask.kt deleted file mode 100644 index 30f92ff7d474..000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/GenerateCodegenArtifactsTask.kt +++ /dev/null @@ -1,83 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.tasks - -import com.facebook.react.utils.JsonUtils -import com.facebook.react.utils.Os.cliPath -import com.facebook.react.utils.windowsAwareCommandLine -import org.gradle.api.file.Directory -import org.gradle.api.file.DirectoryProperty -import org.gradle.api.file.RegularFile -import org.gradle.api.file.RegularFileProperty -import org.gradle.api.provider.ListProperty -import org.gradle.api.provider.Property -import org.gradle.api.provider.Provider -import org.gradle.api.tasks.Exec -import org.gradle.api.tasks.Input -import org.gradle.api.tasks.InputFile -import org.gradle.api.tasks.Internal -import org.gradle.api.tasks.OutputDirectory - -abstract class GenerateCodegenArtifactsTask : Exec() { - - @get:Internal abstract val reactNativeDir: DirectoryProperty - - @get:Internal abstract val generatedSrcDir: DirectoryProperty - - @get:InputFile abstract val packageJsonFile: RegularFileProperty - - @get:Input abstract val nodeExecutableAndArgs: ListProperty - - @get:Input abstract val codegenJavaPackageName: Property - - @get:Input abstract val libraryName: Property - - @get:InputFile - val generatedSchemaFile: Provider = generatedSrcDir.file("schema.json") - - @get:OutputDirectory val generatedJavaFiles: Provider = generatedSrcDir.dir("java") - - @get:OutputDirectory val generatedJniFiles: Provider = generatedSrcDir.dir("jni") - - override fun exec() { - val (resolvedLibraryName, resolvedCodegenJavaPackageName) = resolveTaskParameters() - setupCommandLine(resolvedLibraryName, resolvedCodegenJavaPackageName) - super.exec() - } - - internal fun resolveTaskParameters(): Pair { - val parsedPackageJson = - if (packageJsonFile.isPresent && packageJsonFile.get().asFile.exists()) { - JsonUtils.fromCodegenJson(packageJsonFile.get().asFile) - } else { - null - } - val resolvedLibraryName = parsedPackageJson?.codegenConfig?.name ?: libraryName.get() - val resolvedCodegenJavaPackageName = - parsedPackageJson?.codegenConfig?.android?.javaPackageName ?: codegenJavaPackageName.get() - return resolvedLibraryName to resolvedCodegenJavaPackageName - } - - internal fun setupCommandLine(libraryName: String, codegenJavaPackageName: String) { - val workingDir = project.projectDir - commandLine( - windowsAwareCommandLine( - *nodeExecutableAndArgs.get().toTypedArray(), - reactNativeDir.file("scripts/generate-specs-cli.js").get().asFile.cliPath(workingDir), - "--platform", - "android", - "--schemaPath", - generatedSchemaFile.get().asFile.cliPath(workingDir), - "--outputDir", - generatedSrcDir.get().asFile.cliPath(workingDir), - "--libraryName", - libraryName, - "--javaPackageName", - codegenJavaPackageName)) - } -} diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/GenerateCodegenSchemaTask.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/GenerateCodegenSchemaTask.kt deleted file mode 100644 index 3f724eb5ff22..000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/GenerateCodegenSchemaTask.kt +++ /dev/null @@ -1,82 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.tasks - -import com.facebook.react.utils.Os.cliPath -import com.facebook.react.utils.windowsAwareCommandLine -import org.gradle.api.file.DirectoryProperty -import org.gradle.api.file.RegularFile -import org.gradle.api.provider.ListProperty -import org.gradle.api.provider.Provider -import org.gradle.api.tasks.* - -/** - * A task that will collect all the *.js files inside the provided [jsRootDir] and will run the - * `combine-js-to-schema-cli.js` on top of it (from `react-native-codegen`). The output is a - * `schema.json` file that contains an intermediate representation of the code to be generated. - */ -abstract class GenerateCodegenSchemaTask : Exec() { - - @get:Internal abstract val jsRootDir: DirectoryProperty - - @get:Internal abstract val codegenDir: DirectoryProperty - - @get:Internal abstract val generatedSrcDir: DirectoryProperty - - @get:Input abstract val nodeExecutableAndArgs: ListProperty - - @get:InputFiles - val jsInputFiles = - project.fileTree(jsRootDir) { - it.include("**/*.js") - it.include("**/*.ts") - // Those are known build paths where the source map or other - // .js files could be stored/generated. We want to make sure we don't pick them up - // for execution avoidance. - it.exclude("**/generated/source/codegen/**/*") - it.exclude("**/build/ASSETS/**/*") - it.exclude("**/build/RES/**/*") - it.exclude("**/build/generated/assets/react/**/*") - it.exclude("**/build/generated/res/react/**/*") - it.exclude("**/build/generated/sourcemaps/react/**/*") - it.exclude("**/build/intermediates/sourcemaps/react/**/*") - } - - @get:OutputFile - val generatedSchemaFile: Provider = generatedSrcDir.file("schema.json") - - override fun exec() { - wipeOutputDir() - setupCommandLine() - super.exec() - } - - internal fun wipeOutputDir() { - generatedSrcDir.asFile.get().apply { - deleteRecursively() - mkdirs() - } - } - - internal fun setupCommandLine() { - val workingDir = project.projectDir - commandLine( - windowsAwareCommandLine( - *nodeExecutableAndArgs.get().toTypedArray(), - codegenDir - .file("lib/cli/combine/combine-js-to-schema-cli.js") - .get() - .asFile - .cliPath(workingDir), - "--platform", - "android", - generatedSchemaFile.get().asFile.cliPath(workingDir), - jsRootDir.asFile.get().cliPath(workingDir), - )) - } -} diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/internal/PrepareBoostTask.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/internal/PrepareBoostTask.kt deleted file mode 100644 index ee680337af49..000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/internal/PrepareBoostTask.kt +++ /dev/null @@ -1,46 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.tasks.internal - -import java.io.File -import org.gradle.api.DefaultTask -import org.gradle.api.file.ConfigurableFileCollection -import org.gradle.api.file.DirectoryProperty -import org.gradle.api.provider.Property -import org.gradle.api.tasks.* - -/** - * A task that takes care of extracting Boost from a source folder/zip and preparing it to be - * consumed by the NDK - */ -abstract class PrepareBoostTask : DefaultTask() { - - @get:InputFiles abstract val boostPath: ConfigurableFileCollection - - @get:Input abstract val boostVersion: Property - - @get:OutputDirectory abstract val outputDir: DirectoryProperty - - @TaskAction - fun taskAction() { - project.copy { it -> - it.from(boostPath) - it.from(project.file("src/main/jni/third-party/boost")) - it.include( - "CMakeLists.txt", - "boost_${boostVersion.get()}/boost/**/*.hpp", - "boost/boost/**/*.hpp", - "asm/**/*.S") - it.includeEmptyDirs = false - it.into(outputDir) - } - File(outputDir.asFile.get(), "boost").apply { - renameTo(File(this.parentFile, "boost_${boostVersion.get()}")) - } - } -} diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/internal/PrepareGlogTask.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/internal/PrepareGlogTask.kt deleted file mode 100644 index fcbd204517c8..000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/internal/PrepareGlogTask.kt +++ /dev/null @@ -1,79 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.tasks.internal - -import java.io.File -import org.apache.tools.ant.filters.ReplaceTokens -import org.gradle.api.DefaultTask -import org.gradle.api.file.ConfigurableFileCollection -import org.gradle.api.file.DirectoryProperty -import org.gradle.api.file.DuplicatesStrategy -import org.gradle.api.provider.Property -import org.gradle.api.tasks.* - -/** - * A task that takes care of extracting Glog from a source folder/zip and preparing it to be - * consumed by the NDK. This task will also take care of applying the mapping for Glog parameters. - */ -abstract class PrepareGlogTask : DefaultTask() { - - @get:InputFiles abstract val glogPath: ConfigurableFileCollection - - @get:Input abstract val glogVersion: Property - - @get:OutputDirectory abstract val outputDir: DirectoryProperty - - @TaskAction - fun taskAction() { - project.copy { - it.from(glogPath) - it.from(project.file("src/main/jni/third-party/glog/")) - it.include("glog-${glogVersion.get()}/src/**/*", "CMakeLists.txt", "config.h") - it.duplicatesStrategy = DuplicatesStrategy.WARN - it.includeEmptyDirs = false - it.filesMatching("**/*.h.in") { matchedFile -> - matchedFile.filter( - mapOf( - "tokens" to - mapOf( - "ac_cv_have_unistd_h" to "1", - "ac_cv_have_stdint_h" to "1", - "ac_cv_have_systypes_h" to "1", - "ac_cv_have_inttypes_h" to "1", - "ac_cv_have_libgflags" to "0", - "ac_google_start_namespace" to "namespace google {", - "ac_cv_have_uint16_t" to "1", - "ac_cv_have_u_int16_t" to "1", - "ac_cv_have___uint16" to "0", - "ac_google_end_namespace" to "}", - "ac_cv_have___builtin_expect" to "1", - "ac_google_namespace" to "google", - "ac_cv___attribute___noinline" to "__attribute__ ((noinline))", - "ac_cv___attribute___noreturn" to "__attribute__ ((noreturn))", - "ac_cv___attribute___printf_4_5" to - "__attribute__((__format__ (__printf__, 4, 5)))")), - ReplaceTokens::class.java) - matchedFile.path = (matchedFile.name.removeSuffix(".in")) - } - it.into(outputDir) - } - val exportedDir = File(outputDir.asFile.get(), "exported/glog/").apply { mkdirs() } - project.copy { - it.from(outputDir) - it.include( - "stl_logging.h", - "logging.h", - "raw_logging.h", - "vlog_is_on.h", - "**/src/glog/log_severity.h") - it.eachFile { file -> file.path = file.name } - it.includeEmptyDirs = false - it.into(exportedDir) - } - } -} diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/internal/PrepareJSCTask.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/internal/PrepareJSCTask.kt deleted file mode 100644 index 9b6913df88fa..000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/internal/PrepareJSCTask.kt +++ /dev/null @@ -1,50 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.tasks.internal - -import java.io.File -import org.gradle.api.DefaultTask -import org.gradle.api.file.DirectoryProperty -import org.gradle.api.provider.Property -import org.gradle.api.tasks.* - -/** - * A task that takes care of unbundling JSC and preparing it for be consumed by the Android NDK. - * Specifically it will unbundle shared libs, headers and will copy over the Makefile from - * `src/main/jni/third-party/jsc/` - */ -abstract class PrepareJSCTask : DefaultTask() { - - @get:Input abstract val jscPackagePath: Property - - @get:OutputDirectory abstract val outputDir: DirectoryProperty - - @TaskAction - fun taskAction() { - if (!jscPackagePath.isPresent || jscPackagePath.orNull == null) { - error("Could not find the jsc-android npm package") - } - val jscDist = File(jscPackagePath.get(), "dist") - if (!jscDist.exists()) { - error("The jsc-android npm package is missing its \"dist\" directory") - } - val jscAAR = - project.fileTree(jscDist).matching { it.include("**/android-jsc/**/*.aar") }.singleFile - val soFiles = project.zipTree(jscAAR).matching { it.include("**/*.so") } - val headerFiles = project.fileTree(jscDist).matching { it.include("**/include/*.h") } - - project.copy { it -> - it.from(soFiles) - it.from(headerFiles) - it.from(project.file("src/main/jni/third-party/jsc/CMakeLists.txt")) - it.filesMatching("**/*.h") { it.path = "JavaScriptCore/${it.name}" } - it.includeEmptyDirs = false - it.into(outputDir) - } - } -} diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/internal/PrepareLibeventTask.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/internal/PrepareLibeventTask.kt deleted file mode 100644 index fb00626557f3..000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/internal/PrepareLibeventTask.kt +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.tasks.internal - -import java.io.File -import org.gradle.api.DefaultTask -import org.gradle.api.file.ConfigurableFileCollection -import org.gradle.api.file.DirectoryProperty -import org.gradle.api.provider.Property -import org.gradle.api.tasks.* - -/** - * A task that takes care of extracting Libevent from a source folder/zip and preparing it to be - * consumed by the NDK. - */ -abstract class PrepareLibeventTask : DefaultTask() { - - @get:InputFiles abstract val libeventPath: ConfigurableFileCollection - - @get:Input abstract val libeventVersion: Property - - @get:OutputDirectory abstract val outputDir: DirectoryProperty - - @TaskAction - fun taskAction() { - project.copy { it -> - it.from(libeventPath) - it.from(project.file("src/main/jni/third-party/libevent/")) - it.include( - "libevent-${libeventVersion.get()}-stable/*.c", - "libevent-${libeventVersion.get()}-stable/*.h", - "libevent-${libeventVersion.get()}-stable/include/**/*", - "evconfig-private.h", - "event-config.h", - "CMakeLists.txt") - it.eachFile { it.path = it.path.removePrefix("libevent-${libeventVersion.get()}-stable/") } - it.includeEmptyDirs = false - it.into(outputDir) - } - File(outputDir.asFile.get(), "event-config.h").apply { - val destination = - File(this.parentFile, "include/event2/event-config.h").apply { parentFile.mkdirs() } - renameTo(destination) - } - } -} diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/internal/PreparePrefabHeadersTask.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/internal/PreparePrefabHeadersTask.kt deleted file mode 100644 index f3b55e091104..000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/internal/PreparePrefabHeadersTask.kt +++ /dev/null @@ -1,62 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.tasks.internal - -import com.facebook.react.tasks.internal.utils.PrefabPreprocessingEntry -import java.io.File -import javax.inject.Inject -import org.gradle.api.DefaultTask -import org.gradle.api.file.DirectoryProperty -import org.gradle.api.file.FileSystemOperations -import org.gradle.api.file.RegularFile -import org.gradle.api.provider.ListProperty -import org.gradle.api.tasks.Input -import org.gradle.api.tasks.OutputDirectory -import org.gradle.api.tasks.TaskAction - -/** - * A task that takes care of copying headers and filtering them so that can be consumed by the - * Prefab protocol. This task handles also the header prefixes. - * - * It currently filters out some of the Boost headers as they're not used by React Native and are - * resulting in bigger .aar (250Mb+). - * - * You should provide in input a list fo [PrefabPreprocessingEntry] that will be used by this task - * to do the necessary copy operations. - */ -abstract class PreparePrefabHeadersTask : DefaultTask() { - - @get:Input abstract val input: ListProperty - - @get:OutputDirectory abstract val outputDir: DirectoryProperty - - @get:Inject abstract val fs: FileSystemOperations - - @TaskAction - fun taskAction() { - input.get().forEach { (libraryName, pathToPrefixCouples) -> - val outputFolder: RegularFile = outputDir.file(libraryName).get() - pathToPrefixCouples.forEach { (headerPath, headerPrefix) -> - fs.copy { - it.from(headerPath) - it.include("**/*.h") - it.exclude("**/*.cpp") - it.exclude("**/*.txt") - // We don't want to copy all the boost headers as they are 250Mb+ - it.include("boost/config.hpp") - it.include("boost/config/**/*.hpp") - it.include("boost/core/*.hpp") - it.include("boost/detail/workaround.hpp") - it.include("boost/operators.hpp") - it.include("boost/preprocessor/**/*.hpp") - it.into(File(outputFolder.asFile, headerPrefix)) - } - } - } - } -} diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/internal/utils/PrefabPreprocessingEntry.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/internal/utils/PrefabPreprocessingEntry.kt deleted file mode 100644 index 943bba3eaaca..000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/internal/utils/PrefabPreprocessingEntry.kt +++ /dev/null @@ -1,27 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.tasks.internal.utils - -import java.io.Serializable - -/** - * This data class represents an entry that can be consumed by the [PreparePrefabHeadersTask]. - * @param libraryName The name of the library that you're preparing for Prefab - * @param pathToPrefixCouples A list of pairs Path to Header prefix. You can use this list to supply - * a list of paths that you want to be considered for prefab. Each path can specify an header prefix - * that will be used by prefab to re-created the header layout. - */ -data class PrefabPreprocessingEntry( - val libraryName: String, - val pathToPrefixCouples: List>, -) : Serializable { - constructor( - libraryName: String, - pathToPrefixCouple: Pair - ) : this(libraryName, listOf(pathToPrefixCouple)) -} diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/AgpConfiguratorUtils.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/AgpConfiguratorUtils.kt deleted file mode 100644 index 3bf008535f7e..000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/AgpConfiguratorUtils.kt +++ /dev/null @@ -1,54 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.utils - -import com.android.build.api.variant.AndroidComponentsExtension -import com.facebook.react.utils.ProjectUtils.isHermesEnabled -import com.facebook.react.utils.ProjectUtils.isNewArchEnabled -import org.gradle.api.Action -import org.gradle.api.Project -import org.gradle.api.plugins.AppliedPlugin - -@Suppress("UnstableApiUsage") -internal object AgpConfiguratorUtils { - - fun configureBuildConfigFields(project: Project) { - val action = - Action { - project.extensions.getByType(AndroidComponentsExtension::class.java).finalizeDsl { ext -> - ext.defaultConfig.buildConfigField( - "boolean", "IS_NEW_ARCHITECTURE_ENABLED", project.isNewArchEnabled.toString()) - ext.defaultConfig.buildConfigField( - "boolean", "IS_HERMES_ENABLED", project.isHermesEnabled.toString()) - } - } - project.pluginManager.withPlugin("com.android.application", action) - project.pluginManager.withPlugin("com.android.library", action) - } - - fun configureDevPorts(project: Project) { - val devServerPort = - project.properties["reactNativeDevServerPort"]?.toString() ?: DEFAULT_DEV_SERVER_PORT - val inspectorProxyPort = - project.properties["reactNativeInspectorProxyPort"]?.toString() ?: devServerPort - - val action = - Action { - project.extensions.getByType(AndroidComponentsExtension::class.java).finalizeDsl { ext -> - ext.defaultConfig.resValue("integer", "react_native_dev_server_port", devServerPort) - ext.defaultConfig.resValue( - "integer", "react_native_inspector_proxy_port", inspectorProxyPort) - } - } - - project.pluginManager.withPlugin("com.android.application", action) - project.pluginManager.withPlugin("com.android.library", action) - } -} - -const val DEFAULT_DEV_SERVER_PORT = "8081" diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/BackwardCompatUtils.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/BackwardCompatUtils.kt deleted file mode 100644 index 5c39266900f6..000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/BackwardCompatUtils.kt +++ /dev/null @@ -1,48 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.utils - -import java.util.* -import org.gradle.api.Project - -internal object BackwardCompatUtils { - - fun configureBackwardCompatibilityReactMap(project: Project) { - if (project.extensions.extraProperties.has("react")) { - @Suppress("UNCHECKED_CAST") - val reactMap = - project.extensions.extraProperties.get("react") as? Map ?: mapOf() - if (reactMap.isNotEmpty()) { - project.logger.error( - """ - ******************************************************************************** - - ERROR: Using old project.ext.react configuration. - We identified that your project is using a old configuration block as: - - project.ext.react = [ - // ... - ] - - You should migrate to the new configuration: - - react { - // ... - } - You can find documentation inside `android/app/build.gradle` on how to use it. - - ******************************************************************************** - """ - .trimIndent()) - } - } - - // We set an empty react[] map so if a library is reading it, they will find empty values. - project.extensions.extraProperties.set("react", mapOf()) - } -} diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/DependencyUtils.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/DependencyUtils.kt deleted file mode 100644 index d74a7d102089..000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/DependencyUtils.kt +++ /dev/null @@ -1,109 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.utils - -import java.io.File -import java.net.URI -import java.util.* -import org.gradle.api.Project -import org.gradle.api.artifacts.repositories.MavenArtifactRepository - -internal const val DEFAULT_GROUP_STRING = "com.facebook.react" - -internal object DependencyUtils { - - /** - * This method takes care of configuring the repositories{} block for both the app and all the 3rd - * party libraries which are auto-linked. - */ - fun configureRepositories(project: Project, reactNativeDir: File) { - project.rootProject.allprojects { eachProject -> - with(eachProject) { - if (hasProperty("REACT_NATIVE_MAVEN_LOCAL_REPO")) { - val mavenLocalRepoPath = property("REACT_NATIVE_MAVEN_LOCAL_REPO") as String - mavenRepoFromURI(File(mavenLocalRepoPath).toURI()) - } - // We add the snapshot for users on nightlies. - mavenRepoFromUrl("https://oss.sonatype.org/content/repositories/snapshots/") - repositories.mavenCentral() - // Android JSC is installed from npm - mavenRepoFromURI(File(reactNativeDir, "../jsc-android/dist").toURI()) - repositories.google() - mavenRepoFromUrl("https://www.jitpack.io") - } - } - } - - /** - * This method takes care of configuring the resolution strategy for both the app and all the 3rd - * party libraries which are auto-linked. Specifically it takes care of: - * - Forcing the react-android/hermes-android version to the one specified in the package.json - * - Substituting `react-native` with `react-android` and `hermes-engine` with `hermes-android`. - */ - fun configureDependencies( - project: Project, - versionString: String, - groupString: String = DEFAULT_GROUP_STRING - ) { - if (versionString.isBlank()) return - project.rootProject.allprojects { eachProject -> - eachProject.configurations.all { configuration -> - // Here we set a dependencySubstitution for both react-native and hermes-engine as those - // coordinates are voided due to https://github.com/facebook/react-native/issues/35210 - // This allows users to import libraries that are still using - // implementation("com.facebook.react:react-native:+") and resolve the right dependency. - configuration.resolutionStrategy.dependencySubstitution { - it.substitute(it.module("com.facebook.react:react-native")) - .using(it.module("${groupString}:react-android:${versionString}")) - .because( - "The react-native artifact was deprecated in favor of react-android due to https://github.com/facebook/react-native/issues/35210.") - it.substitute(it.module("com.facebook.react:hermes-engine")) - .using(it.module("${groupString}:hermes-android:${versionString}")) - .because( - "The hermes-engine artifact was deprecated in favor of hermes-android due to https://github.com/facebook/react-native/issues/35210.") - if (groupString != DEFAULT_GROUP_STRING) { - it.substitute(it.module("com.facebook.react:react-android")) - .using(it.module("${groupString}:react-android:${versionString}")) - .because( - "The react-android dependency was modified to use the correct Maven group.") - it.substitute(it.module("com.facebook.react:hermes-android")) - .using(it.module("${groupString}:hermes-android:${versionString}")) - .because( - "The hermes-android dependency was modified to use the correct Maven group.") - } - } - configuration.resolutionStrategy.force( - "${groupString}:react-android:${versionString}", - "${groupString}:hermes-android:${versionString}", - ) - } - } - } - - fun readVersionAndGroupStrings(propertiesFile: File): Pair { - val reactAndroidProperties = Properties() - propertiesFile.inputStream().use { reactAndroidProperties.load(it) } - val versionStringFromFile = reactAndroidProperties["VERSION_NAME"] as? String ?: "" - // If on a nightly, we need to fetch the -SNAPSHOT artifact from Sonatype. - val versionString = - if (versionStringFromFile.startsWith("0.0.0")) { - "$versionStringFromFile-SNAPSHOT" - } else { - versionStringFromFile - } - // Returns Maven group for repos using different group for Maven artifacts - val groupString = reactAndroidProperties["GROUP"] as? String ?: DEFAULT_GROUP_STRING - return Pair(versionString, groupString) - } - - fun Project.mavenRepoFromUrl(url: String): MavenArtifactRepository = - project.repositories.maven { it.url = URI.create(url) } - - fun Project.mavenRepoFromURI(uri: URI): MavenArtifactRepository = - project.repositories.maven { it.url = uri } -} diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/FileUtils.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/FileUtils.kt deleted file mode 100644 index 28774b823595..000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/FileUtils.kt +++ /dev/null @@ -1,20 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.utils - -import java.io.File - -internal fun File.moveTo(destination: File) { - copyTo(destination, overwrite = true) - delete() -} - -internal fun File.recreateDir() { - deleteRecursively() - mkdirs() -} diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/JsonUtils.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/JsonUtils.kt deleted file mode 100644 index 4fa27510f484..000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/JsonUtils.kt +++ /dev/null @@ -1,21 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.utils - -import com.facebook.react.model.ModelPackageJson -import com.google.gson.Gson -import java.io.File - -object JsonUtils { - private val gsonConverter = Gson() - - fun fromCodegenJson(input: File): ModelPackageJson? = - input.bufferedReader().use { - runCatching { gsonConverter.fromJson(it, ModelPackageJson::class.java) }.getOrNull() - } -} diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/NdkConfiguratorUtils.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/NdkConfiguratorUtils.kt deleted file mode 100644 index 74b85fa0d65a..000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/NdkConfiguratorUtils.kt +++ /dev/null @@ -1,147 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.utils - -import com.android.build.api.variant.AndroidComponentsExtension -import com.android.build.api.variant.Variant -import com.facebook.react.ReactExtension -import com.facebook.react.utils.ProjectUtils.getReactNativeArchitectures -import com.facebook.react.utils.ProjectUtils.isNewArchEnabled -import java.io.File -import org.gradle.api.Project - -internal object NdkConfiguratorUtils { - @Suppress("UnstableApiUsage") - fun configureReactNativeNdk(project: Project, extension: ReactExtension) { - project.pluginManager.withPlugin("com.android.application") { - project.extensions.getByType(AndroidComponentsExtension::class.java).finalizeDsl { ext -> - if (!project.isNewArchEnabled) { - // For Old Arch, we don't need to setup the NDK - return@finalizeDsl - } - // We enable prefab so users can consume .so/headers from ReactAndroid and hermes-engine - // .aar - ext.buildFeatures.prefab = true - - // If the user has not provided a CmakeLists.txt path, let's provide - // the default one from the framework - if (ext.externalNativeBuild.cmake.path == null) { - ext.externalNativeBuild.cmake.path = - File( - extension.reactNativeDir.get().asFile, - "ReactAndroid/cmake-utils/default-app-setup/CMakeLists.txt") - } - - // Parameters should be provided in an additive manner (do not override what - // the user provided, but allow for sensible defaults). - val cmakeArgs = ext.defaultConfig.externalNativeBuild.cmake.arguments - if ("-DPROJECT_BUILD_DIR" !in cmakeArgs) { - cmakeArgs.add("-DPROJECT_BUILD_DIR=${project.buildDir}") - } - if ("-DREACT_ANDROID_DIR" !in cmakeArgs) { - cmakeArgs.add( - "-DREACT_ANDROID_DIR=${extension.reactNativeDir.file("ReactAndroid").get().asFile}") - } - if ("-DANDROID_STL" !in cmakeArgs) { - cmakeArgs.add("-DANDROID_STL=c++_shared") - } - - val architectures = project.getReactNativeArchitectures() - // abiFilters are split ABI are not compatible each other, so we set the abiFilters - // only if the user hasn't enabled the split abi feature. - if (architectures.isNotEmpty() && !ext.splits.abi.isEnable) { - ext.defaultConfig.ndk.abiFilters.addAll(architectures) - } - } - } - } - - /** - * This method is used to configure the .so Packaging Options for the given variant. It will make - * sure we specify the correct .pickFirsts for all the .so files we are producing or that we're - * aware of as some of our dependencies are pulling them in. - */ - fun configureNewArchPackagingOptions( - project: Project, - variant: Variant, - ) { - if (!project.isNewArchEnabled) { - // For Old Arch, we set a pickFirst only on libraries that we know are - // clashing with our direct dependencies (FBJNI, Flipper and Hermes). - variant.packaging.jniLibs.pickFirsts.addAll( - listOf( - "**/libfbjni.so", - "**/libc++_shared.so", - )) - } else { - // We set some packagingOptions { pickFirst ... } for our users for libraries we own. - variant.packaging.jniLibs.pickFirsts.addAll( - listOf( - // This is the .so provided by FBJNI via prefab - "**/libfbjni.so", - // Those are prefab libraries we distribute via ReactAndroid - // Due to a bug in AGP, they fire a warning on console as both the JNI - // and the prefab .so files gets considered. See more on: - "**/libfabricjni.so", - "**/libfolly_runtime.so", - "**/libglog.so", - "**/libjsi.so", - "**/libreact_codegen_rncore.so", - "**/libreact_debug.so", - "**/libreact_nativemodule_core.so", - "**/libreact_newarchdefaults.so", - "**/libreact_render_componentregistry.so", - "**/libreact_render_core.so", - "**/libreact_render_debug.so", - "**/libreact_render_graphics.so", - "**/libreact_render_imagemanager.so", - "**/libreact_render_mapbuffer.so", - "**/librrc_image.so", - "**/librrc_view.so", - "**/libruntimeexecutor.so", - "**/libturbomodulejsijni.so", - "**/libyoga.so", - // AGP will give priority of libc++_shared coming from App modules. - "**/libc++_shared.so", - )) - } - } - - /** - * This method is used to configure the .so Cleanup for the given variant. It takes care of - * cleaning up the .so files that are not needed for Hermes or JSC, given a specific variant. - */ - fun configureJsEnginePackagingOptions( - config: ReactExtension, - variant: Variant, - hermesEnabled: Boolean, - ) { - if (config.enableSoCleanup.get()) { - val (excludes, includes) = getPackagingOptionsForVariant(hermesEnabled) - variant.packaging.jniLibs.excludes.addAll(excludes) - variant.packaging.jniLibs.pickFirsts.addAll(includes) - } - } - - fun getPackagingOptionsForVariant(hermesEnabled: Boolean): Pair, List> { - val excludes = mutableListOf() - val includes = mutableListOf() - if (hermesEnabled) { - excludes.add("**/libjsc.so") - excludes.add("**/libjscexecutor.so") - includes.add("**/libhermes.so") - includes.add("**/libhermes_executor.so") - } else { - excludes.add("**/libhermes.so") - excludes.add("**/libhermes_executor.so") - includes.add("**/libjsc.so") - includes.add("**/libjscexecutor.so") - } - return excludes to includes - } -} diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/Os.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/Os.kt deleted file mode 100644 index 4ca00699b841..000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/Os.kt +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.utils - -import java.io.File - -internal object Os { - - fun isWindows(): Boolean = - System.getProperty("os.name")?.lowercase()?.contains("windows") ?: false - - fun isMac(): Boolean = System.getProperty("os.name")?.lowercase()?.contains("mac") ?: false - - fun isLinuxAmd64(): Boolean { - val osNameMatch = System.getProperty("os.name")?.lowercase()?.contains("linux") ?: false - val archMatch = System.getProperty("os.arch")?.lowercase()?.contains("amd64") ?: false - return osNameMatch && archMatch - } - - fun String.unixifyPath() = - this.replace('\\', '/').replace(":", "").let { - if (!it.startsWith("/")) { - "/$it" - } else { - it - } - } - - /** - * As Gradle doesn't support well path with spaces on Windows, we need to return relative path on - * Win. On Linux & Mac we'll default to return absolute path. - */ - fun File.cliPath(base: File): String = - if (isWindows()) { - this.relativeTo(base).path - } else { - this.absolutePath - } -} diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/PathUtils.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/PathUtils.kt deleted file mode 100644 index 2f874947d87c..000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/PathUtils.kt +++ /dev/null @@ -1,231 +0,0 @@ -/* - * 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. - */ - -@file:JvmName("PathUtils") - -package com.facebook.react.utils - -import com.facebook.react.ReactExtension -import com.facebook.react.model.ModelPackageJson -import com.facebook.react.utils.Os.cliPath -import java.io.File -import org.gradle.api.Project -import org.gradle.api.file.DirectoryProperty - -/** - * Computes the entry file for React Native. The Algo follows this order: - * 1. The file pointed by the ENTRY_FILE env variable, if set. - * 2. The file provided by the `entryFile` config in the `reactApp` Gradle extension - * 3. The `index.android.js` file, if available. - * 4. Fallback to the `index.js` file. - * - * @param config The [ReactExtension] configured for this project - */ -internal fun detectedEntryFile(config: ReactExtension, envVariableOverride: String? = null): File = - detectEntryFile( - entryFile = config.entryFile.orNull?.asFile, - reactRoot = config.root.get().asFile, - envVariableOverride = envVariableOverride) - -/** - * Computes the CLI file for React Native. The Algo follows this order: - * 1. The path provided by the `cliFile` config in the `react {}` Gradle extension - * 2. The output of `node --print "require.resolve('react-native/cli');"` if not failing. - * 3. The `node_modules/react-native/cli.js` file if exists - * 4. Fails otherwise - */ -internal fun detectedCliFile(config: ReactExtension): File = - detectCliFile( - reactNativeRoot = config.root.get().asFile, - preconfiguredCliFile = config.cliFile.asFile.orNull) - -/** - * Computes the `hermesc` command location. The Algo follows this order: - * 1. The path provided by the `hermesCommand` config in the `react` Gradle extension - * 2. The file located in `node_modules/react-native/sdks/hermes/build/bin/hermesc`. This will be - * used if the user is building Hermes from source. - * 3. The file located in `node_modules/react-native/sdks/hermesc/%OS-BIN%/hermesc` where `%OS-BIN%` - * is substituted with the correct OS arch. This will be used if the user is using a precompiled - * hermes-engine package. - * 4. Fails otherwise - */ -internal fun detectedHermesCommand(config: ReactExtension): String = - detectOSAwareHermesCommand(config.root.get().asFile, config.hermesCommand.get()) - -private fun detectEntryFile( - entryFile: File?, - reactRoot: File, - envVariableOverride: String? = null -): File = - when { - envVariableOverride != null -> File(reactRoot, envVariableOverride) - entryFile != null -> entryFile - File(reactRoot, "index.android.js").exists() -> File(reactRoot, "index.android.js") - else -> File(reactRoot, "index.js") - } - -private fun detectCliFile(reactNativeRoot: File, preconfiguredCliFile: File?): File { - // 1. preconfigured path - if (preconfiguredCliFile != null) { - if (preconfiguredCliFile.exists()) { - return preconfiguredCliFile - } - } - - // 2. node module path - val nodeProcess = - Runtime.getRuntime() - .exec( - arrayOf("node", "--print", "require.resolve('react-native/cli');"), - emptyArray(), - reactNativeRoot) - - val nodeProcessOutput = nodeProcess.inputStream.use { it.bufferedReader().readText().trim() } - - if (nodeProcessOutput.isNotEmpty()) { - val nodeModuleCliJs = File(nodeProcessOutput) - if (nodeModuleCliJs.exists()) { - return nodeModuleCliJs - } - } - - // 3. cli.js in the root folder - val rootCliJs = File(reactNativeRoot, "node_modules/react-native/cli.js") - if (rootCliJs.exists()) { - return rootCliJs - } - - error( - """ - Couldn't determine CLI location! - - Please set `react { cliFile = file(...) }` inside your - build.gradle to the path of the react-native cli.js file. - This file typically resides in `node_modules/react-native/cli.js` - """ - .trimIndent()) -} - -/** - * Computes the `hermesc` command location. The Algo follows this order: - * 1. The path provided by the `hermesCommand` config in the `react` Gradle extension - * 2. The file located in `node_modules/react-native/sdks/hermes/build/bin/hermesc`. This will be - * used if the user is building Hermes from source. - * 3. The file located in `node_modules/react-native/sdks/hermesc/%OS-BIN%/hermesc` where `%OS-BIN%` - * is substituted with the correct OS arch. This will be used if the user is using a precompiled - * hermes-engine package. - * 4. Fails otherwise - */ -internal fun detectOSAwareHermesCommand(projectRoot: File, hermesCommand: String): String { - // 1. If the project specifies a Hermes command, don't second guess it. - if (hermesCommand.isNotBlank()) { - val osSpecificHermesCommand = - if ("%OS-BIN%" in hermesCommand) { - hermesCommand.replace("%OS-BIN%", getHermesOSBin()) - } else { - hermesCommand - } - return osSpecificHermesCommand - // Execution on Windows fails with / as separator - .replace('/', File.separatorChar) - } - - // 2. If the project is building hermes-engine from source, use hermesc from there - val builtHermesc = - getBuiltHermescFile(projectRoot, System.getenv("REACT_NATIVE_OVERRIDE_HERMES_DIR")) - if (builtHermesc.exists()) { - return builtHermesc.cliPath(projectRoot) - } - - // 3. If the react-native contains a pre-built hermesc, use it. - val prebuiltHermesPath = - HERMESC_IN_REACT_NATIVE_DIR.plus(getHermesCBin()) - .replace("%OS-BIN%", getHermesOSBin()) - // Execution on Windows fails with / as separator - .replace('/', File.separatorChar) - - val prebuiltHermes = File(projectRoot, prebuiltHermesPath) - if (prebuiltHermes.exists()) { - return prebuiltHermes.cliPath(projectRoot) - } - - error( - "Couldn't determine Hermesc location. " + - "Please set `react.hermesCommand` to the path of the hermesc binary file. " + - "node_modules/react-native/sdks/hermesc/%OS-BIN%/hermesc") -} - -/** - * Gets the location where Hermesc should be. If nothing is specified, built hermesc is assumed to - * be inside [HERMESC_BUILT_FROM_SOURCE_DIR]. Otherwise user can specify an override with - * [pathOverride], which is assumed to be an absolute path where Hermes source code is - * provided/built. - * - * @param projectRoot The root of the Project. - */ -internal fun getBuiltHermescFile(projectRoot: File, pathOverride: String?) = - if (!pathOverride.isNullOrBlank()) { - File(pathOverride, "build/bin/${getHermesCBin()}") - } else { - File(projectRoot, HERMESC_BUILT_FROM_SOURCE_DIR.plus(getHermesCBin())) - } - -internal fun getHermesCBin() = if (Os.isWindows()) "hermesc.exe" else "hermesc" - -internal fun getHermesOSBin(): String { - if (Os.isWindows()) return "win64-bin" - if (Os.isMac()) return "osx-bin" - if (Os.isLinuxAmd64()) return "linux64-bin" - error( - "OS not recognized. Please set project.react.hermesCommand " + - "to the path of a working Hermes compiler.") -} - -internal fun projectPathToLibraryName(projectPath: String): String = - projectPath - .split(':', '-', '_', '.') - .joinToString("") { token -> token.replaceFirstChar { it.uppercase() } } - .plus("Spec") - -/** - * Function to look for the relevant `package.json`. We first look in the parent folder of this - * Gradle module (generally the case for library projects) or we fallback to looking into the `root` - * folder of a React Native project (generally the case for app projects). - */ -internal fun findPackageJsonFile(project: Project, rootProperty: DirectoryProperty): File? { - val inParent = project.file("../package.json") - if (inParent.exists()) { - return inParent - } - - val fromExtension = rootProperty.file("package.json").orNull?.asFile - if (fromExtension?.exists() == true) { - return fromExtension - } - - return null -} - -/** - * Function to look for the `package.json` and parse it. It returns a [ModelPackageJson] if found or - * null others. - * - * Please note that this function access the [DirectoryProperty] parameter and calls .get() on them, - * so calling this during apply() of the ReactPlugin is not recommended. It should be invoked inside - * lazy lambdas or at execution time. - */ -internal fun readPackageJsonFile( - project: Project, - rootProperty: DirectoryProperty -): ModelPackageJson? { - val packageJson = findPackageJsonFile(project, rootProperty) - return packageJson?.let { JsonUtils.fromCodegenJson(it) } -} - -private const val HERMESC_IN_REACT_NATIVE_DIR = "node_modules/react-native/sdks/hermesc/%OS-BIN%/" -private const val HERMESC_BUILT_FROM_SOURCE_DIR = - "node_modules/react-native/ReactAndroid/hermes-engine/build/hermes/bin/" diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/ProjectUtils.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/ProjectUtils.kt deleted file mode 100644 index e941da78b564..000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/ProjectUtils.kt +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.utils - -import com.facebook.react.model.ModelPackageJson -import org.gradle.api.Project -import org.gradle.api.file.DirectoryProperty - -internal object ProjectUtils { - internal val Project.isNewArchEnabled: Boolean - get() = - project.hasProperty("newArchEnabled") && - project.property("newArchEnabled").toString().toBoolean() - - const val HERMES_FALLBACK = true - - internal val Project.isHermesEnabled: Boolean - get() = - if (project.hasProperty("hermesEnabled")) { - project.property("hermesEnabled").toString().lowercase().toBooleanStrictOrNull() ?: true - } else if (project.extensions.extraProperties.has("react")) { - @Suppress("UNCHECKED_CAST") - val reactMap = project.extensions.extraProperties.get("react") as? Map - when (val enableHermesKey = reactMap?.get("enableHermes")) { - is Boolean -> enableHermesKey - is String -> enableHermesKey.lowercase().toBooleanStrictOrNull() ?: true - else -> HERMES_FALLBACK - } - } else { - HERMES_FALLBACK - } - - internal fun Project.needsCodegenFromPackageJson(rootProperty: DirectoryProperty): Boolean { - val parsedPackageJson = readPackageJsonFile(this, rootProperty) - return needsCodegenFromPackageJson(parsedPackageJson) - } - - internal fun Project.needsCodegenFromPackageJson(model: ModelPackageJson?): Boolean { - return model?.codegenConfig != null - } - - internal fun Project.getReactNativeArchitectures(): List { - val architectures = mutableListOf() - if (project.hasProperty("reactNativeArchitectures")) { - val architecturesString = project.property("reactNativeArchitectures").toString() - architectures.addAll(architecturesString.split(",").filter { it.isNotBlank() }) - } - return architectures - } -} diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/TaskUtils.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/TaskUtils.kt deleted file mode 100644 index df99d06e47bc..000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/TaskUtils.kt +++ /dev/null @@ -1,28 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.utils - -internal fun windowsAwareCommandLine(vararg args: Any): List = - windowsAwareCommandLine(args.toList()) - -internal fun windowsAwareCommandLine(args: List): List = - if (Os.isWindows()) { - listOf("cmd", "/c") + args - } else { - args - } - -internal fun windowsAwareBashCommandLine( - vararg args: String, - bashWindowsHome: String? = null -): List = - if (Os.isWindows()) { - listOf(bashWindowsHome ?: "bash", "-c") + args - } else { - args.toList() - } diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/TestReactExtension.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/TestReactExtension.kt deleted file mode 100644 index afc9ff358ea9..000000000000 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/TestReactExtension.kt +++ /dev/null @@ -1,12 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react - -import org.gradle.api.Project - -class TestReactExtension(project: Project) : ReactExtension(project) diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/BuildCodegenCLITaskTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/BuildCodegenCLITaskTest.kt deleted file mode 100644 index 33db1357ebdf..000000000000 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/BuildCodegenCLITaskTest.kt +++ /dev/null @@ -1,75 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.tasks - -import com.facebook.react.tests.createTestTask -import java.io.File -import org.gradle.api.tasks.* -import org.junit.Assert.* -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TemporaryFolder - -class BuildCodegenCLITaskTest { - - @get:Rule val tempFolder = TemporaryFolder() - - @Test - fun buildCodegenCli_input_isSetCorrectly() { - val task = createTestTask { it.codegenDir.set(tempFolder.root) } - - assertTrue(task.input.contains(File(tempFolder.root, "scripts"))) - assertTrue(task.input.contains(File(tempFolder.root, "src"))) - assertTrue(task.input.contains(File(tempFolder.root, "package.json"))) - assertTrue(task.input.contains(File(tempFolder.root, ".babelrc"))) - assertTrue(task.input.contains(File(tempFolder.root, ".prettierrc"))) - } - - @Test - fun buildCodegenCli_output_isSetCorrectly() { - val task = createTestTask { it.codegenDir.set(tempFolder.root) } - - assertTrue(task.output.contains(File(tempFolder.root, "lib"))) - assertTrue(task.output.contains(File(tempFolder.root, "node_modules"))) - } - - @Test - fun buildCodegenCli_bashWindowsHome_isSetCorrectly() { - val bashPath = tempFolder.newFile("bash").absolutePath - val task = createTestTask { it.bashWindowsHome.set(bashPath) } - - assertEquals(bashPath, task.bashWindowsHome.get()) - } - - @Test - fun buildCodegenCli_onlyIf_withMissingDirectory_isSatisfied() { - File(tempFolder.root, "lib/cli/").apply { mkdirs() } - val task = createTestTask { it.codegenDir.set(tempFolder.root) } - - assertTrue(task.onlyIf.isSatisfiedBy(task)) - } - - @Test - fun buildCodegenCli_onlyIf_withEmptyDirectory_isSatisfied() { - File(tempFolder.root, "lib/cli/").apply { mkdirs() } - val task = createTestTask { it.codegenDir.set(tempFolder.root) } - - assertTrue(task.onlyIf.isSatisfiedBy(task)) - } - - @Test - fun buildCodegenCli_onlyIf_withExistingDirtyDirectory_isNotSatisfied() { - File(tempFolder.root, "lib/cli/a-file").apply { - parentFile.mkdirs() - writeText("¯\\_(ツ)_/¯") - } - val task = createTestTask { it.codegenDir.set(tempFolder.root) } - - assertFalse(task.onlyIf.isSatisfiedBy(task)) - } -} diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/BundleHermesCTaskTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/BundleHermesCTaskTest.kt deleted file mode 100644 index 3e07a78b36e1..000000000000 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/BundleHermesCTaskTest.kt +++ /dev/null @@ -1,432 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.tasks - -import com.facebook.react.tests.OS -import com.facebook.react.tests.OsRule -import com.facebook.react.tests.WithOs -import com.facebook.react.tests.createTestTask -import java.io.File -import org.junit.Assert.* -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TemporaryFolder - -class BundleHermesCTaskTest { - - @get:Rule val tempFolder = TemporaryFolder() - - @get:Rule val osRule = OsRule() - - @Test - fun bundleTask_groupIsSetCorrectly() { - val task = createTestTask {} - assertEquals("react", task.group) - } - - @Test - fun bundleTask_inputFiles_areSetCorrectly() { - val rootDir = - tempFolder.newFolder("js").apply { - File(this, "file.js").createNewFile() - File(this, "file.jsx").createNewFile() - File(this, "file.ts").createNewFile() - File(this, "file.tsx").createNewFile() - } - - val task = createTestTask { it.root.set(rootDir) } - - assertEquals(4, task.sources.files.size) - assertEquals( - setOf( - File(rootDir, "file.js"), - File(rootDir, "file.jsx"), - File(rootDir, "file.ts"), - File(rootDir, "file.tsx")), - task.sources.files) - } - - @Test - fun bundleTask_inputFilesInExcludedPath_areExcluded() { - fun File.createFileAndPath() { - parentFile.mkdirs() - createNewFile() - } - - val rootDir = - tempFolder.newFolder("js").apply { - File(this, "afolder/includedfile.js").createFileAndPath() - // Those files should be excluded due to their filepath - File(this, "android/excludedfile.js").createFileAndPath() - File(this, "ios/excludedfile.js").createFileAndPath() - File(this, "build/excludedfile.js").createFileAndPath() - File(this, "node_modules/react-native/excludedfile.js").createFileAndPath() - } - - val task = createTestTask { it.root.set(rootDir) } - - assertEquals( - setOf( - "**/android/**/*", - "**/ios/**/*", - "**/build/**/*", - "**/node_modules/**/*", - ), - task.sources.excludes) - assertEquals(1, task.sources.files.size) - assertEquals(setOf(File(rootDir, "afolder/includedfile.js")), task.sources.files) - } - - @Test - fun bundleTask_staticInputs_areSetCorrectly() { - val task = - createTestTask { - it.nodeExecutableAndArgs.set(listOf("node", "arg1", "arg2")) - it.bundleCommand.set("bundle") - it.bundleAssetName.set("myassetname") - it.minifyEnabled.set(true) - it.hermesEnabled.set(true) - it.devEnabled.set(true) - it.extraPackagerArgs.set(listOf("extra", "arg")) - it.hermesCommand.set("./my-hermesc") - it.hermesFlags.set(listOf("flag1", "flag2")) - } - - assertEquals(listOf("node", "arg1", "arg2"), task.nodeExecutableAndArgs.get()) - assertEquals("bundle", task.bundleCommand.get()) - assertEquals("myassetname", task.bundleAssetName.get()) - assertTrue(task.minifyEnabled.get()) - assertTrue(task.hermesEnabled.get()) - assertTrue(task.devEnabled.get()) - assertEquals(listOf("extra", "arg"), task.extraPackagerArgs.get()) - assertEquals("./my-hermesc", task.hermesCommand.get()) - assertEquals(listOf("flag1", "flag2"), task.hermesFlags.get()) - } - - @Test - fun bundleTask_filesInput_areSetCorrectly() { - val entryFile = tempFolder.newFile("entry.js") - val cliFile = tempFolder.newFile("cli.js") - val jsBundleDir = tempFolder.newFolder("jsbundle") - val resourcesDir = tempFolder.newFolder("resources") - val jsIntermediateSourceMapsDir = tempFolder.newFolder("jsIntermediateSourceMaps") - val jsSourceMapsDir = tempFolder.newFolder("jsSourceMaps") - val bundleConfig = tempFolder.newFile("bundle.config") - val reactNativeDir = tempFolder.newFolder("node_modules/react-native") - - val task = - createTestTask { - it.entryFile.set(entryFile) - it.cliFile.set(cliFile) - it.jsBundleDir.set(jsBundleDir) - it.resourcesDir.set(resourcesDir) - it.jsIntermediateSourceMapsDir.set(jsIntermediateSourceMapsDir) - it.jsSourceMapsDir.set(jsSourceMapsDir) - it.bundleConfig.set(bundleConfig) - it.reactNativeDir.set(reactNativeDir) - } - - assertEquals(entryFile, task.entryFile.get().asFile) - assertEquals(cliFile, task.cliFile.get().asFile) - assertEquals(jsBundleDir, task.jsBundleDir.get().asFile) - assertEquals(resourcesDir, task.resourcesDir.get().asFile) - assertEquals(jsIntermediateSourceMapsDir, task.jsIntermediateSourceMapsDir.get().asFile) - assertEquals(jsSourceMapsDir, task.jsSourceMapsDir.get().asFile) - assertEquals(bundleConfig, task.bundleConfig.get().asFile) - assertEquals(reactNativeDir, task.reactNativeDir.get().asFile) - } - - @Test - fun resolvePackagerSourceMapFile_withHermesEnabled_returnsCorrectFile() { - val jsIntermediateSourceMapsDir = tempFolder.newFolder("jsIntermediateSourceMaps") - val bundleAssetName = "myassetname" - val task = - createTestTask { - it.jsIntermediateSourceMapsDir.set(jsIntermediateSourceMapsDir) - it.hermesEnabled.set(true) - it.bundleAssetName.set(bundleAssetName) - } - - assertEquals( - File(jsIntermediateSourceMapsDir, "myassetname.packager.map"), - task.resolvePackagerSourceMapFile(bundleAssetName)) - } - - @Test - fun resolvePackagerSourceMapFile_withHermesDisabled_returnsCorrectFile() { - val jsSourceMapsDir = tempFolder.newFolder("jsSourceMaps") - val bundleAssetName = "myassetname" - val task = - createTestTask { - it.jsSourceMapsDir.set(jsSourceMapsDir) - it.hermesEnabled.set(false) - } - - assertEquals( - File(jsSourceMapsDir, "myassetname.map"), - task.resolvePackagerSourceMapFile(bundleAssetName)) - } - - @Test - fun resolveOutputSourceMap_returnsCorrectFile() { - val jsSourceMapsDir = tempFolder.newFolder("jsSourceMaps") - val bundleAssetName = "myassetname" - val task = createTestTask { it.jsSourceMapsDir.set(jsSourceMapsDir) } - - assertEquals( - File(jsSourceMapsDir, "myassetname.map"), task.resolveOutputSourceMap(bundleAssetName)) - } - - @Test - fun resolveCompilerSourceMap_returnsCorrectFile() { - val jsIntermediateSourceMapsDir = tempFolder.newFolder("jsIntermediateSourceMaps") - val bundleAssetName = "myassetname" - val task = - createTestTask { - it.jsIntermediateSourceMapsDir.set(jsIntermediateSourceMapsDir) - } - - assertEquals( - File(jsIntermediateSourceMapsDir, "myassetname.compiler.map"), - task.resolveCompilerSourceMap(bundleAssetName)) - } - - @Test - fun getBundleCommand_returnsCorrectCommand() { - val entryFile = tempFolder.newFile("index.js") - val cliFile = tempFolder.newFile("cli.js") - val bundleFile = tempFolder.newFile("bundle.js") - val sourceMapFile = tempFolder.newFile("bundle.js.map") - val resourcesDir = tempFolder.newFolder("res") - val bundleConfig = tempFolder.newFile("bundle.config") - val task = - createTestTask { - it.nodeExecutableAndArgs.set(listOf("node", "arg1", "arg2")) - it.root.set(tempFolder.root) - it.cliFile.set(cliFile) - it.bundleCommand.set("bundle") - it.devEnabled.set(true) - it.entryFile.set(entryFile) - it.resourcesDir.set(resourcesDir) - it.bundleConfig.set(bundleConfig) - it.minifyEnabled.set(true) - it.extraPackagerArgs.set(listOf("--read-global-cache")) - } - - val bundleCommand = task.getBundleCommand(bundleFile, sourceMapFile) - - assertEquals("node", bundleCommand[0]) - assertEquals("arg1", bundleCommand[1]) - assertEquals("arg2", bundleCommand[2]) - assertEquals(cliFile.absolutePath, bundleCommand[3]) - assertEquals("bundle", bundleCommand[4]) - assertEquals("--platform", bundleCommand[5]) - assertEquals("android", bundleCommand[6]) - assertEquals("--dev", bundleCommand[7]) - assertEquals("true", bundleCommand[8]) - assertEquals("--reset-cache", bundleCommand[9]) - assertEquals("--entry-file", bundleCommand[10]) - assertEquals(entryFile.absolutePath, bundleCommand[11]) - assertEquals("--bundle-output", bundleCommand[12]) - assertEquals(bundleFile.absolutePath, bundleCommand[13]) - assertEquals("--assets-dest", bundleCommand[14]) - assertEquals(resourcesDir.absolutePath, bundleCommand[15]) - assertEquals("--sourcemap-output", bundleCommand[16]) - assertEquals(sourceMapFile.absolutePath, bundleCommand[17]) - assertEquals("--config", bundleCommand[18]) - assertEquals(bundleConfig.absolutePath, bundleCommand[19]) - assertEquals("--minify", bundleCommand[20]) - assertEquals("true", bundleCommand[21]) - assertEquals("--read-global-cache", bundleCommand[22]) - assertEquals("--verbose", bundleCommand[23]) - assertEquals(24, bundleCommand.size) - } - - @Test - @WithOs(OS.WIN) - fun getBundleCommand_onWindows_returnsWinValidCommandsPaths() { - val entryFile = tempFolder.newFile("index.js") - val cliFile = tempFolder.newFile("cli.js") - val bundleFile = tempFolder.newFile("bundle.js") - val sourceMapFile = tempFolder.newFile("bundle.js.map") - val resourcesDir = tempFolder.newFolder("res") - val bundleConfig = tempFolder.newFile("bundle.config") - val task = - createTestTask { - it.nodeExecutableAndArgs.set(listOf("node", "arg1", "arg2")) - it.root.set(tempFolder.root) - it.cliFile.set(cliFile) - it.bundleCommand.set("bundle") - it.devEnabled.set(true) - it.entryFile.set(entryFile) - it.resourcesDir.set(resourcesDir) - it.bundleConfig.set(bundleConfig) - it.minifyEnabled.set(true) - it.extraPackagerArgs.set(listOf("--read-global-cache")) - } - - val bundleCommand = task.getBundleCommand(bundleFile, sourceMapFile) - - assertEquals("cmd", bundleCommand[0]) - assertEquals("/c", bundleCommand[1]) - assertEquals("node", bundleCommand[2]) - assertEquals("arg1", bundleCommand[3]) - assertEquals("arg2", bundleCommand[4]) - assertEquals(cliFile.relativeTo(tempFolder.root).path, bundleCommand[5]) - assertEquals("bundle", bundleCommand[6]) - assertEquals("--platform", bundleCommand[7]) - assertEquals("android", bundleCommand[8]) - assertEquals("--dev", bundleCommand[9]) - assertEquals("true", bundleCommand[10]) - assertEquals("--reset-cache", bundleCommand[11]) - assertEquals("--entry-file", bundleCommand[12]) - assertEquals(entryFile.relativeTo(tempFolder.root).path, bundleCommand[13]) - assertEquals("--bundle-output", bundleCommand[14]) - assertEquals(bundleFile.relativeTo(tempFolder.root).path, bundleCommand[15]) - assertEquals("--assets-dest", bundleCommand[16]) - assertEquals(resourcesDir.relativeTo(tempFolder.root).path, bundleCommand[17]) - assertEquals("--sourcemap-output", bundleCommand[18]) - assertEquals(sourceMapFile.relativeTo(tempFolder.root).path, bundleCommand[19]) - assertEquals("--config", bundleCommand[20]) - assertEquals(bundleConfig.relativeTo(tempFolder.root).path, bundleCommand[21]) - assertEquals("--minify", bundleCommand[22]) - assertEquals("true", bundleCommand[23]) - assertEquals("--read-global-cache", bundleCommand[24]) - assertEquals("--verbose", bundleCommand[25]) - assertEquals(26, bundleCommand.size) - } - - @Test - fun getBundleCommand_withoutConfig_returnsCommandWithoutConfig() { - val entryFile = tempFolder.newFile("index.js") - val cliFile = tempFolder.newFile("cli.js") - val bundleFile = tempFolder.newFile("bundle.js") - val sourceMapFile = tempFolder.newFile("bundle.js.map") - val resourcesDir = tempFolder.newFolder("res") - val task = - createTestTask { - it.nodeExecutableAndArgs.set(listOf("node", "arg1", "arg2")) - it.root.set(tempFolder.root) - it.cliFile.set(cliFile) - it.bundleCommand.set("bundle") - it.devEnabled.set(true) - it.entryFile.set(entryFile) - it.resourcesDir.set(resourcesDir) - it.minifyEnabled.set(true) - it.extraPackagerArgs.set(listOf("--read-global-cache")) - } - - val bundleCommand = task.getBundleCommand(bundleFile, sourceMapFile) - - assertTrue("--config" !in bundleCommand) - } - - @Test - fun getHermescCommand_returnsCorrectCommand() { - val customHermesc = "hermesc" - val bytecodeFile = tempFolder.newFile("bundle.js.hbc") - val bundleFile = tempFolder.newFile("bundle.js") - val task = - createTestTask { - it.root.set(tempFolder.root) - it.hermesFlags.set(listOf("my-custom-hermes-flag")) - } - - val hermesCommand = task.getHermescCommand(customHermesc, bytecodeFile, bundleFile) - - assertEquals(customHermesc, hermesCommand[0]) - assertEquals("-emit-binary", hermesCommand[1]) - assertEquals("-out", hermesCommand[2]) - assertEquals(bytecodeFile.absolutePath, hermesCommand[3]) - assertEquals(bundleFile.absolutePath, hermesCommand[4]) - assertEquals("my-custom-hermes-flag", hermesCommand[5]) - assertEquals(6, hermesCommand.size) - } - - @Test - @WithOs(OS.WIN) - fun getHermescCommand_onWindows_returnsRelativePaths() { - val customHermesc = "hermesc" - val bytecodeFile = tempFolder.newFile("bundle.js.hbc") - val bundleFile = tempFolder.newFile("bundle.js") - val task = - createTestTask { - it.root.set(tempFolder.root) - it.hermesFlags.set(listOf("my-custom-hermes-flag")) - } - - val hermesCommand = task.getHermescCommand(customHermesc, bytecodeFile, bundleFile) - - assertEquals("cmd", hermesCommand[0]) - assertEquals("/c", hermesCommand[1]) - assertEquals(customHermesc, hermesCommand[2]) - assertEquals("-emit-binary", hermesCommand[3]) - assertEquals("-out", hermesCommand[4]) - assertEquals(bytecodeFile.relativeTo(tempFolder.root).path, hermesCommand[5]) - assertEquals(bundleFile.relativeTo(tempFolder.root).path, hermesCommand[6]) - assertEquals("my-custom-hermes-flag", hermesCommand[7]) - assertEquals(8, hermesCommand.size) - } - - @Test - fun getComposeSourceMapsCommand_returnsCorrectCommand() { - val packagerMap = tempFolder.newFile("bundle.js.packager.map") - val compilerMap = tempFolder.newFile("bundle.js.compiler.map") - val outputMap = tempFolder.newFile("bundle.js.map") - val reactNativeDir = tempFolder.newFolder("node_modules/react-native") - val composeSourceMapsFile = File(reactNativeDir, "scripts/compose-source-maps.js") - val task = - createTestTask { - it.root.set(tempFolder.root) - it.nodeExecutableAndArgs.set(listOf("node", "arg1", "arg2")) - } - - val composeSourcemapCommand = - task.getComposeSourceMapsCommand(composeSourceMapsFile, packagerMap, compilerMap, outputMap) - - assertEquals("node", composeSourcemapCommand[0]) - assertEquals("arg1", composeSourcemapCommand[1]) - assertEquals("arg2", composeSourcemapCommand[2]) - assertEquals(composeSourceMapsFile.absolutePath, composeSourcemapCommand[3]) - assertEquals(packagerMap.absolutePath, composeSourcemapCommand[4]) - assertEquals(compilerMap.absolutePath, composeSourcemapCommand[5]) - assertEquals("-o", composeSourcemapCommand[6]) - assertEquals(outputMap.absolutePath, composeSourcemapCommand[7]) - assertEquals(8, composeSourcemapCommand.size) - } - - @Test - @WithOs(OS.WIN) - fun getComposeSourceMapsCommand_onWindows_returnsRelativePaths() { - val packagerMap = tempFolder.newFile("bundle.js.packager.map") - val compilerMap = tempFolder.newFile("bundle.js.compiler.map") - val outputMap = tempFolder.newFile("bundle.js.map") - val reactNativeDir = tempFolder.newFolder("node_modules/react-native") - val composeSourceMapsFile = File(reactNativeDir, "scripts/compose-source-maps.js") - val task = - createTestTask { - it.root.set(tempFolder.root) - it.nodeExecutableAndArgs.set(listOf("node", "arg1", "arg2")) - } - - val composeSourcemapCommand = - task.getComposeSourceMapsCommand(composeSourceMapsFile, packagerMap, compilerMap, outputMap) - - assertEquals("cmd", composeSourcemapCommand[0]) - assertEquals("/c", composeSourcemapCommand[1]) - assertEquals("node", composeSourcemapCommand[2]) - assertEquals("arg1", composeSourcemapCommand[3]) - assertEquals("arg2", composeSourcemapCommand[4]) - assertEquals(composeSourceMapsFile.relativeTo(tempFolder.root).path, composeSourcemapCommand[5]) - assertEquals(packagerMap.relativeTo(tempFolder.root).path, composeSourcemapCommand[6]) - assertEquals(compilerMap.relativeTo(tempFolder.root).path, composeSourcemapCommand[7]) - assertEquals("-o", composeSourcemapCommand[8]) - assertEquals(outputMap.relativeTo(tempFolder.root).path, composeSourcemapCommand[9]) - assertEquals(10, composeSourcemapCommand.size) - } -} diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/GenerateCodegenArtifactsTaskTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/GenerateCodegenArtifactsTaskTest.kt deleted file mode 100644 index e2bf1ad7b9b4..000000000000 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/GenerateCodegenArtifactsTaskTest.kt +++ /dev/null @@ -1,213 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.tasks - -import com.facebook.react.tests.* -import com.facebook.react.tests.createProject -import com.facebook.react.tests.createTestTask -import java.io.File -import org.junit.Assert.assertEquals -import org.junit.Assert.assertTrue -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TemporaryFolder - -class GenerateCodegenArtifactsTaskTest { - - @get:Rule val tempFolder = TemporaryFolder() - - @get:Rule val osRule = OsRule() - - @Test - fun generateCodegenSchema_inputFiles_areSetCorrectly() { - val codegenDir = tempFolder.newFolder("codegen") - val outputDir = tempFolder.newFolder("output") - - val task = createTestTask { it.generatedSrcDir.set(outputDir) } - - assertEquals(File(outputDir, "schema.json"), task.generatedSchemaFile.get().asFile) - } - - @Test - fun generateCodegenSchema_outputFile_isSetCorrectly() { - val outputDir = tempFolder.newFolder("output") - - val task = createTestTask { it.generatedSrcDir.set(outputDir) } - - assertEquals(File(outputDir, "java"), task.generatedJavaFiles.get().asFile) - assertEquals(File(outputDir, "jni"), task.generatedJniFiles.get().asFile) - } - - @Test - fun generateCodegenSchema_simpleProperties_areInsideInput() { - val packageJsonFile = tempFolder.newFile("package.json") - - val task = - createTestTask { - it.nodeExecutableAndArgs.set(listOf("npm", "help")) - it.codegenJavaPackageName.set("com.example.test") - it.libraryName.set("example-test") - it.packageJsonFile.set(packageJsonFile) - } - - assertEquals(listOf("npm", "help"), task.nodeExecutableAndArgs.get()) - assertEquals("com.example.test", task.codegenJavaPackageName.get()) - assertEquals("example-test", task.libraryName.get()) - assertTrue(task.inputs.properties.containsKey("nodeExecutableAndArgs")) - assertTrue(task.inputs.properties.containsKey("codegenJavaPackageName")) - assertTrue(task.inputs.properties.containsKey("libraryName")) - } - - @Test - @WithOs(OS.LINUX) - fun setupCommandLine_willSetupCorrectly() { - val reactNativeDir = tempFolder.newFolder("node_modules/react-native/") - val outputDir = tempFolder.newFolder("output") - - val task = - createTestTask { - it.reactNativeDir.set(reactNativeDir) - it.generatedSrcDir.set(outputDir) - it.nodeExecutableAndArgs.set(listOf("--verbose")) - } - - task.setupCommandLine("example-test", "com.example.test") - - assertEquals( - listOf( - "--verbose", - File(reactNativeDir, "scripts/generate-specs-cli.js").toString(), - "--platform", - "android", - "--schemaPath", - File(outputDir, "schema.json").toString(), - "--outputDir", - outputDir.toString(), - "--libraryName", - "example-test", - "--javaPackageName", - "com.example.test", - ), - task.commandLine.toMutableList()) - } - - @Test - @WithOs(OS.WIN) - fun setupCommandLine_onWindows_willSetupCorrectly() { - val reactNativeDir = tempFolder.newFolder("node_modules/react-native/") - val outputDir = tempFolder.newFolder("output") - - val project = createProject() - val task = - createTestTask(project) { - it.reactNativeDir.set(reactNativeDir) - it.generatedSrcDir.set(outputDir) - it.nodeExecutableAndArgs.set(listOf("--verbose")) - } - - task.setupCommandLine("example-test", "com.example.test") - - assertEquals( - listOf( - "cmd", - "/c", - "--verbose", - File(reactNativeDir, "scripts/generate-specs-cli.js") - .relativeTo(project.projectDir) - .path, - "--platform", - "android", - "--schemaPath", - File(outputDir, "schema.json").relativeTo(project.projectDir).path, - "--outputDir", - outputDir.relativeTo(project.projectDir).path, - "--libraryName", - "example-test", - "--javaPackageName", - "com.example.test", - ), - task.commandLine.toMutableList()) - } - - @Test - fun resolveTaskParameters_withConfigInPackageJson_usesIt() { - val packageJsonFile = - tempFolder.newFile("package.json").apply { - // language=JSON - writeText( - """ - { - "name": "@a/libray", - "codegenConfig": { - "name": "an-awesome-library", - "android": { - "javaPackageName": "com.awesome.package" - } - } - } - """ - .trimIndent()) - } - - val task = - createTestTask { - it.packageJsonFile.set(packageJsonFile) - it.codegenJavaPackageName.set("com.example.ignored") - it.libraryName.set("a-library-name-that-is-ignored") - } - - val (libraryName, javaPackageName) = task.resolveTaskParameters() - - assertEquals("an-awesome-library", libraryName) - assertEquals("com.awesome.package", javaPackageName) - } - - @Test - fun resolveTaskParameters_withConfigMissingInPackageJson_usesGradleOne() { - val packageJsonFile = - tempFolder.newFile("package.json").apply { - // language=JSON - writeText( - """ - { - "name": "@a/libray", - "codegenConfig": { - } - } - """ - .trimIndent()) - } - - val task = - createTestTask { - it.packageJsonFile.set(packageJsonFile) - it.codegenJavaPackageName.set("com.example.test") - it.libraryName.set("a-library-name-from-gradle") - } - - val (libraryName, javaPackageName) = task.resolveTaskParameters() - - assertEquals("a-library-name-from-gradle", libraryName) - assertEquals("com.example.test", javaPackageName) - } - - @Test - fun resolveTaskParameters_withMissingPackageJson_usesGradleOne() { - val task = - createTestTask { - it.packageJsonFile.set(File(tempFolder.root, "package.json")) - it.codegenJavaPackageName.set("com.example.test") - it.libraryName.set("a-library-name-from-gradle") - } - - val (libraryName, javaPackageName) = task.resolveTaskParameters() - - assertEquals("a-library-name-from-gradle", libraryName) - assertEquals("com.example.test", javaPackageName) - } -} diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/GenerateCodegenSchemaTaskTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/GenerateCodegenSchemaTaskTest.kt deleted file mode 100644 index abe77f0dd155..000000000000 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/GenerateCodegenSchemaTaskTest.kt +++ /dev/null @@ -1,194 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.tasks - -import com.facebook.react.tests.* -import com.facebook.react.tests.createProject -import com.facebook.react.tests.createTestTask -import java.io.File -import org.junit.Assert.* -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TemporaryFolder - -class GenerateCodegenSchemaTaskTest { - - @get:Rule val tempFolder = TemporaryFolder() - - @get:Rule val osRule = OsRule() - - @Test - fun generateCodegenSchema_inputFiles_areSetCorrectly() { - val jsRootDir = - tempFolder.newFolder("js").apply { - File(this, "file.js").createNewFile() - File(this, "file.ts").createNewFile() - File(this, "ignore.txt").createNewFile() - } - - val task = createTestTask { it.jsRootDir.set(jsRootDir) } - - assertEquals(jsRootDir, task.jsInputFiles.dir) - assertEquals(setOf("**/*.js", "**/*.ts"), task.jsInputFiles.includes) - assertEquals(2, task.jsInputFiles.files.size) - assertEquals( - setOf(File(jsRootDir, "file.js"), File(jsRootDir, "file.ts")), task.jsInputFiles.files) - } - - @Test - fun generateCodegenSchema_inputFilesInExcludedPath_areExcluded() { - fun File.createFileAndPath() { - parentFile.mkdirs() - createNewFile() - } - - val jsRootDir = - tempFolder.newFolder("js").apply { - File(this, "afolder/includedfile.js").createFileAndPath() - // Those files should be excluded due to their filepath - File(this, "afolder/generated/source/codegen/anotherfolder/excludedfile.js") - .createFileAndPath() - File(this, "afolder/build/generated/assets/react/anotherfolder/excludedfile.js") - .createFileAndPath() - File(this, "afolder/build/generated/res/react/anotherfolder/excludedfile.js") - .createFileAndPath() - File(this, "afolder/build/generated/sourcemaps/react/anotherfolder/excludedfile.js") - .createFileAndPath() - File(this, "afolder/build/intermediates/sourcemaps/react/anotherfolder/excludedfile.js") - .createFileAndPath() - } - - val task = createTestTask { it.jsRootDir.set(jsRootDir) } - - assertEquals(jsRootDir, task.jsInputFiles.dir) - assertEquals( - setOf( - "**/generated/source/codegen/**/*", - "**/build/ASSETS/**/*", - "**/build/RES/**/*", - "**/build/generated/assets/react/**/*", - "**/build/generated/res/react/**/*", - "**/build/generated/sourcemaps/react/**/*", - "**/build/intermediates/sourcemaps/react/**/*", - ), - task.jsInputFiles.excludes) - assertEquals(1, task.jsInputFiles.files.size) - assertEquals(setOf(File(jsRootDir, "afolder/includedfile.js")), task.jsInputFiles.files) - } - - @Test - fun generateCodegenSchema_outputFile_isSetCorrectly() { - val outputDir = tempFolder.newFolder("output") - - val task = createTestTask { it.generatedSrcDir.set(outputDir) } - - assertEquals(File(outputDir, "schema.json"), task.generatedSchemaFile.get().asFile) - } - - @Test - fun generateCodegenSchema_nodeExecutablesArgs_areInsideInput() { - val task = - createTestTask { - it.nodeExecutableAndArgs.set(listOf("npm", "help")) - } - - assertEquals(listOf("npm", "help"), task.nodeExecutableAndArgs.get()) - assertTrue(task.inputs.properties.containsKey("nodeExecutableAndArgs")) - } - - @Test - fun wipeOutputDir_willCreateOutputDir() { - val task = - createTestTask { - it.generatedSrcDir.set(File(tempFolder.root, "output")) - } - - task.wipeOutputDir() - - assertTrue(File(tempFolder.root, "output").exists()) - assertEquals(0, File(tempFolder.root, "output").listFiles()?.size) - } - - @Test - fun wipeOutputDir_willWipeOutputDir() { - val outputDir = - tempFolder.newFolder("output").apply { File(this, "some-generated-file").createNewFile() } - - val task = createTestTask { it.generatedSrcDir.set(outputDir) } - - task.wipeOutputDir() - - assertTrue(outputDir.exists()) - assertEquals(0, outputDir.listFiles()?.size) - } - - @Test - @WithOs(OS.LINUX) - fun setupCommandLine_willSetupCorrectly() { - val codegenDir = tempFolder.newFolder("codegen") - val jsRootDir = tempFolder.newFolder("js") - val outputDir = tempFolder.newFolder("output") - - val task = - createTestTask { - it.codegenDir.set(codegenDir) - it.jsRootDir.set(jsRootDir) - it.generatedSrcDir.set(outputDir) - it.nodeExecutableAndArgs.set(listOf("node", "--verbose")) - } - - task.setupCommandLine() - - assertEquals( - listOf( - "node", - "--verbose", - File(codegenDir, "lib/cli/combine/combine-js-to-schema-cli.js").toString(), - "--platform", - "android", - File(outputDir, "schema.json").toString(), - jsRootDir.toString(), - ), - task.commandLine.toMutableList()) - } - - @Test - @WithOs(OS.WIN) - fun setupCommandLine_onWindows_willSetupCorrectly() { - val codegenDir = tempFolder.newFolder("codegen") - val jsRootDir = tempFolder.newFolder("js") - val outputDir = tempFolder.newFolder("output") - - val project = createProject() - val task = - createTestTask(project) { - it.codegenDir.set(codegenDir) - it.jsRootDir.set(jsRootDir) - it.generatedSrcDir.set(outputDir) - it.nodeExecutableAndArgs.set(listOf("node", "--verbose")) - } - - task.setupCommandLine() - - assertEquals( - listOf( - "cmd", - "/c", - "node", - "--verbose", - File(codegenDir, "lib/cli/combine/combine-js-to-schema-cli.js") - .relativeTo(project.projectDir) - .path, - "--platform", - "android", - File(outputDir, "schema.json").relativeTo(project.projectDir).path, - jsRootDir.relativeTo(project.projectDir).path, - ), - task.commandLine.toMutableList()) - } -} diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/internal/PrepareBoostTaskTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/internal/PrepareBoostTaskTest.kt deleted file mode 100644 index 73cb3fe8122e..000000000000 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/internal/PrepareBoostTaskTest.kt +++ /dev/null @@ -1,105 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.tasks.internal - -import com.facebook.react.tests.createProject -import com.facebook.react.tests.createTestTask -import java.io.* -import org.junit.Assert.* -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TemporaryFolder - -class PrepareBoostTaskTest { - - @get:Rule val tempFolder = TemporaryFolder() - - @Test(expected = IllegalStateException::class) - fun prepareBoostTask_withMissingConfiguration_fails() { - val task = createTestTask() - - task.taskAction() - } - - @Test - fun prepareBoostTask_copiesCMakefile() { - val boostpath = tempFolder.newFolder("boostpath") - val output = tempFolder.newFolder("output") - val project = createProject() - val task = - createTestTask(project = project) { - it.boostPath.setFrom(boostpath) - it.boostVersion.set("1.0.0") - it.outputDir.set(output) - } - File(project.projectDir, "src/main/jni/third-party/boost/CMakeLists.txt").apply { - parentFile.mkdirs() - createNewFile() - } - task.taskAction() - - assertTrue(output.listFiles()!!.any { it.name == "CMakeLists.txt" }) - } - - @Test - fun prepareBoostTask_copiesAsmFiles() { - val boostpath = tempFolder.newFolder("boostpath") - val output = tempFolder.newFolder("output") - val task = - createTestTask() { - it.boostPath.setFrom(boostpath) - it.boostVersion.set("1.0.0") - it.outputDir.set(output) - } - File(boostpath, "asm/asm.S").apply { - parentFile.mkdirs() - createNewFile() - } - task.taskAction() - - assertTrue(File(output, "asm/asm.S").exists()) - } - - @Test - fun prepareBoostTask_copiesBoostSourceFiles() { - val boostpath = tempFolder.newFolder("boostpath") - val output = tempFolder.newFolder("output") - val task = - createTestTask { - it.boostPath.setFrom(boostpath) - it.boostVersion.set("1.0.0") - it.outputDir.set(output) - } - File(boostpath, "boost_1.0.0/boost/config.hpp").apply { - parentFile.mkdirs() - createNewFile() - } - task.taskAction() - - assertTrue(File(output, "boost_1.0.0/boost/config.hpp").exists()) - } - - @Test - fun prepareBoostTask_copiesVersionlessBoostSourceFiles() { - val boostpath = tempFolder.newFolder("boostpath") - val output = tempFolder.newFolder("output") - val task = - createTestTask { - it.boostPath.setFrom(boostpath) - it.boostVersion.set("1.0.0") - it.outputDir.set(output) - } - File(boostpath, "boost/boost/config.hpp").apply { - parentFile.mkdirs() - createNewFile() - } - task.taskAction() - - assertTrue(File(output, "boost_1.0.0/boost/config.hpp").exists()) - } -} diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/internal/PrepareGlogTaskTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/internal/PrepareGlogTaskTest.kt deleted file mode 100644 index e767577aa4a0..000000000000 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/internal/PrepareGlogTaskTest.kt +++ /dev/null @@ -1,130 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.tasks.internal - -import com.facebook.react.tests.createProject -import com.facebook.react.tests.createTestTask -import java.io.* -import org.junit.Assert.* -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TemporaryFolder - -class PrepareGlogTaskTest { - - @get:Rule val tempFolder = TemporaryFolder() - - @Test(expected = IllegalStateException::class) - fun prepareGlogTask_withMissingConfiguration_fails() { - val task = createTestTask() - - task.taskAction() - } - - @Test - fun prepareGlogTask_copiesCMakefile() { - val glogpath = tempFolder.newFolder("glogpath") - val output = tempFolder.newFolder("output") - val project = createProject() - val task = - createTestTask(project = project) { - it.glogPath.setFrom(glogpath) - it.glogVersion.set("1.0.0") - it.outputDir.set(output) - } - File(project.projectDir, "src/main/jni/third-party/glog/CMakeLists.txt").apply { - parentFile.mkdirs() - createNewFile() - } - task.taskAction() - - assertTrue(output.listFiles()!!.any { it.name == "CMakeLists.txt" }) - } - - @Test - fun prepareGlogTask_copiesConfigHeaderFile() { - val glogpath = tempFolder.newFolder("glogpath") - val output = tempFolder.newFolder("output") - val project = createProject() - val task = - createTestTask(project = project) { - it.glogPath.setFrom(glogpath) - it.glogVersion.set("1.0.0") - it.outputDir.set(output) - } - File(project.projectDir, "src/main/jni/third-party/glog/config.h").apply { - parentFile.mkdirs() - createNewFile() - } - task.taskAction() - - assertTrue(output.listFiles()!!.any { it.name == "config.h" }) - } - - @Test - fun prepareGlogTask_copiesSourceCode() { - val glogpath = tempFolder.newFolder("glogpath") - val output = tempFolder.newFolder("output") - val task = - createTestTask { - it.glogPath.setFrom(glogpath) - it.glogVersion.set("1.0.0") - it.outputDir.set(output) - } - File(glogpath, "glog-1.0.0/src/glog.cpp").apply { - parentFile.mkdirs() - createNewFile() - } - - task.taskAction() - - assertTrue(File(output, "glog-1.0.0/src/glog.cpp").exists()) - } - - @Test - fun prepareGlogTask_replacesTokenCorrectly() { - val glogpath = tempFolder.newFolder("glogpath") - val output = tempFolder.newFolder("output") - val task = - createTestTask { - it.glogPath.setFrom(glogpath) - it.glogVersion.set("1.0.0") - it.outputDir.set(output) - } - File(glogpath, "glog-1.0.0/src/glog.h.in").apply { - parentFile.mkdirs() - writeText("ac_google_start_namespace") - } - - task.taskAction() - - val expectedFile = File(output, "glog.h") - assertTrue(expectedFile.exists()) - assertEquals("ac_google_start_namespace", expectedFile.readText()) - } - - @Test - fun prepareGlogTask_exportsHeaderCorrectly() { - val glogpath = tempFolder.newFolder("glogpath") - val output = tempFolder.newFolder("output") - val task = - createTestTask { - it.glogPath.setFrom(glogpath) - it.glogVersion.set("1.0.0") - it.outputDir.set(output) - } - File(glogpath, "glog-1.0.0/src/logging.h.in").apply { - parentFile.mkdirs() - writeText("ac_google_start_namespace") - } - - task.taskAction() - - assertTrue(File(output, "exported/glog/logging.h").exists()) - } -} diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/internal/PrepareJSCTaskTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/internal/PrepareJSCTaskTest.kt deleted file mode 100644 index bcffaa589107..000000000000 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/internal/PrepareJSCTaskTest.kt +++ /dev/null @@ -1,128 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.tasks.internal - -import com.facebook.react.tests.createProject -import com.facebook.react.tests.createTestTask -import com.facebook.react.tests.zipFiles -import java.io.* -import org.junit.Assert.* -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TemporaryFolder - -class PrepareJSCTaskTest { - - @get:Rule val tempFolder = TemporaryFolder() - - @Test(expected = IllegalStateException::class) - fun prepareJSCTask_withMissingPackage_fails() { - val task = createTestTask() - - task.taskAction() - } - - @Test(expected = IllegalStateException::class) - fun prepareJSCTask_withNullPackage_fails() { - val task = createTestTask { it.jscPackagePath.set(null as String?) } - - task.taskAction() - } - - @Test(expected = IllegalStateException::class) - fun prepareJSCTask_withMissingDistFolder_fails() { - val task = - createTestTask { it.jscPackagePath.set(tempFolder.root.absolutePath) } - - task.taskAction() - } - - @Test - fun prepareJSCTask_ignoresEmptyDirs() { - prepareInputFolder() - val output = tempFolder.newFolder("output") - File(tempFolder.root, "dist/just/an/empty/folders/").apply { mkdirs() } - - val task = - createTestTask { - it.jscPackagePath.set(tempFolder.root.absolutePath) - it.outputDir.set(output) - } - - task.taskAction() - - assertFalse(File(output, "just/an/empty/folders/").exists()) - } - - @Test - fun prepareJSCTask_copiesSoFiles() { - val soFile = tempFolder.newFile("libsomething.so") - prepareInputFolder(aarContent = listOf(soFile)) - val output = tempFolder.newFolder("output") - - val task = - createTestTask { - it.jscPackagePath.set(tempFolder.root.absolutePath) - it.outputDir.set(output) - } - - task.taskAction() - - assertEquals("libsomething.so", output.listFiles()?.first()?.name) - } - - @Test - fun prepareJSCTask_copiesHeaderFilesToCorrectFolder() { - prepareInputFolder() - File(tempFolder.root, "dist/include/justaheader.h").apply { - parentFile.mkdirs() - createNewFile() - } - val output = tempFolder.newFolder("output") - - val task = - createTestTask { - it.jscPackagePath.set(tempFolder.root.absolutePath) - it.outputDir.set(output) - } - - task.taskAction() - - assertTrue(File(output, "JavaScriptCore/justaheader.h").exists()) - } - - @Test - fun prepareJSCTask_copiesCMakefile() { - val project = createProject() - prepareInputFolder() - File(project.projectDir, "src/main/jni/third-party/jsc/CMakeLists.txt").apply { - parentFile.mkdirs() - createNewFile() - } - val output = tempFolder.newFolder("output") - - val task = - createTestTask(project = project) { - it.jscPackagePath.set(tempFolder.root.absolutePath) - it.outputDir.set(output) - } - - task.taskAction() - - assertTrue(File(output, "CMakeLists.txt").exists()) - } - - private fun prepareInputFolder(aarContent: List = listOf(tempFolder.newFile())) { - val dist = tempFolder.newFolder("dist") - File(dist, "android-jsc/android-library.aar").apply { - parentFile.mkdirs() - createNewFile() - } - zipFiles(File(dist, "android-jsc/android-library.aar"), aarContent) - } -} diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/internal/PrepareLibeventTaskTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/internal/PrepareLibeventTaskTest.kt deleted file mode 100644 index f5085df947a4..000000000000 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/internal/PrepareLibeventTaskTest.kt +++ /dev/null @@ -1,101 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.tasks.internal - -import com.facebook.react.tests.createProject -import com.facebook.react.tests.createTestTask -import java.io.* -import org.junit.Assert.* -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TemporaryFolder - -class PrepareLibeventTaskTest { - - @get:Rule val tempFolder = TemporaryFolder() - - @Test(expected = IllegalStateException::class) - fun prepareBoostTask_withMissingConfiguration_fails() { - val task = createTestTask() - - task.taskAction() - } - - @Test - fun prepareBoostTask_copiesCMakefile() { - val libeventPath = tempFolder.newFolder("libeventPath") - val output = tempFolder.newFolder("output") - val project = createProject() - val task = - createTestTask(project = project) { - it.libeventPath.setFrom(libeventPath) - it.libeventVersion.set("1.0.0") - it.outputDir.set(output) - } - File(project.projectDir, "src/main/jni/third-party/libevent/CMakeLists.txt").apply { - parentFile.mkdirs() - createNewFile() - } - task.taskAction() - - assertTrue(File(output, "CMakeLists.txt").exists()) - } - - @Test - fun prepareBoostTask_copiesConfigFiles() { - val libeventPath = tempFolder.newFolder("libeventPath") - val output = tempFolder.newFolder("output") - val project = createProject() - val task = - createTestTask(project = project) { - it.libeventPath.setFrom(libeventPath) - it.libeventVersion.set("1.0.0") - it.outputDir.set(output) - } - File(project.projectDir, "src/main/jni/third-party/libevent/event-config.h").apply { - parentFile.mkdirs() - createNewFile() - } - File(project.projectDir, "src/main/jni/third-party/libevent/evconfig-private.h").createNewFile() - - task.taskAction() - - assertTrue(File(output, "evconfig-private.h").exists()) - assertTrue(File(output, "include/event2/event-config.h").exists()) - } - - @Test - fun prepareBoostTask_copiesSourceFiles() { - val libeventPath = tempFolder.newFolder("libeventPath") - val output = tempFolder.newFolder("output") - val task = - createTestTask { - it.libeventPath.setFrom(libeventPath) - it.libeventVersion.set("1.0.0") - it.outputDir.set(output) - } - File(libeventPath, "libevent-1.0.0-stable/sample.c").apply { - parentFile.mkdirs() - createNewFile() - } - File(libeventPath, "libevent-1.0.0-stable/sample.h").apply { - parentFile.mkdirs() - createNewFile() - } - File(libeventPath, "libevent-1.0.0-stable/include/sample.h").apply { - parentFile.mkdirs() - createNewFile() - } - - task.taskAction() - - assertTrue(File(output, "sample.c").exists()) - assertTrue(File(output, "sample.h").exists()) - assertTrue(File(output, "include/sample.h").exists()) - } -} diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/internal/PreparePrefabHeadersTaskTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/internal/PreparePrefabHeadersTaskTest.kt deleted file mode 100644 index adf617cb77ea..000000000000 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/internal/PreparePrefabHeadersTaskTest.kt +++ /dev/null @@ -1,201 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.tasks.internal - -import com.facebook.react.tasks.internal.utils.PrefabPreprocessingEntry -import com.facebook.react.tests.createProject -import com.facebook.react.tests.createTestTask -import java.io.* -import org.junit.Assert.* -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TemporaryFolder - -class PreparePrefabHeadersTaskTest { - - @get:Rule val tempFolder = TemporaryFolder() - - @Test - fun preparePrefabHeadersTask_withMissingConfiguration_doesNothing() { - val task = createTestTask() - - task.taskAction() - } - - @Test - fun preparePrefabHeadersTask_withSingleEntry_copiesHeaderFile() { - val outputDir = tempFolder.newFolder("output") - File(tempFolder.root, "input/hello.h").createNewPathAndFile() - - val project = createProject(projectDir = tempFolder.root) - val task = - createTestTask(project = project) { - it.outputDir.set(outputDir) - it.input.set(listOf(PrefabPreprocessingEntry("sample_library", "input/" to ""))) - } - - task.taskAction() - - assertTrue(File(outputDir, "sample_library/hello.h").exists()) - } - - @Test - fun preparePrefabHeadersTask_withSingleEntry_respectsPrefix() { - val expectedPrefix = "react/render/something/" - val outputDir = tempFolder.newFolder("output") - File(tempFolder.root, "input/hello.h").createNewPathAndFile() - - val project = createProject(projectDir = tempFolder.root) - val task = - createTestTask(project = project) { - it.outputDir.set(outputDir) - it.input.set( - listOf(PrefabPreprocessingEntry("sample_library", "input/" to expectedPrefix))) - } - - task.taskAction() - - assertTrue(File(outputDir, "sample_library/${expectedPrefix}hello.h").exists()) - } - - @Test - fun preparePrefabHeadersTask_ignoresUnnecessaryFiles() { - val expectedPrefix = "react/render/something/" - val outputDir = tempFolder.newFolder("output") - File(tempFolder.root, "input/hello.hpp").createNewPathAndFile() - File(tempFolder.root, "input/hello.cpp").createNewPathAndFile() - File(tempFolder.root, "input/CMakeLists.txt").createNewPathAndFile() - - val project = createProject(projectDir = tempFolder.root) - val task = - createTestTask(project = project) { - it.outputDir.set(outputDir) - it.input.set( - listOf(PrefabPreprocessingEntry("sample_library", "input/" to expectedPrefix))) - } - - task.taskAction() - - assertFalse(File(outputDir, "sample_library/hello.hpp").exists()) - assertFalse(File(outputDir, "sample_library/hello.cpp").exists()) - assertFalse(File(outputDir, "sample_library/CMakeLists.txt").exists()) - } - - @Test - fun preparePrefabHeadersTask_withMultiplePaths_copiesHeaderFiles() { - val outputDir = tempFolder.newFolder("output") - File(tempFolder.root, "input/component1/hello1.h").createNewPathAndFile() - File(tempFolder.root, "input/component2/debug/hello2.h").createNewPathAndFile() - - val project = createProject(projectDir = tempFolder.root) - val task = - createTestTask(project = project) { - it.outputDir.set(outputDir) - it.input.set( - listOf( - PrefabPreprocessingEntry( - "sample_library", - listOf("input/component1/" to "", "input/component2/" to "")), - )) - } - - task.taskAction() - - assertTrue(File(outputDir, "sample_library/hello1.h").exists()) - assertTrue(File(outputDir, "sample_library/debug/hello2.h").exists()) - } - - @Test - fun preparePrefabHeadersTask_withMultipleEntries_copiesHeaderFiles() { - val outputDir = tempFolder.newFolder("output") - File(tempFolder.root, "input/lib1/hello1.h").createNewPathAndFile() - File(tempFolder.root, "input/lib2/hello2.h").createNewPathAndFile() - - val project = createProject(projectDir = tempFolder.root) - val task = - createTestTask(project = project) { - it.outputDir.set(outputDir) - it.input.set( - listOf( - PrefabPreprocessingEntry("libraryone", "input/lib1/" to ""), - PrefabPreprocessingEntry("librarytwo", "input/lib2/" to ""))) - } - - task.taskAction() - - assertTrue(File(outputDir, "libraryone/hello1.h").exists()) - assertTrue(File(outputDir, "librarytwo/hello2.h").exists()) - } - - @Test - fun preparePrefabHeadersTask_withReusedHeaders_copiesHeadersTwice() { - val outputDir = tempFolder.newFolder("output") - File(tempFolder.root, "input/lib1/hello1.h").createNewPathAndFile() - File(tempFolder.root, "input/lib2/hello2.h").createNewPathAndFile() - File(tempFolder.root, "input/shared/sharedheader.h").createNewPathAndFile() - - val project = createProject(projectDir = tempFolder.root) - val task = - createTestTask(project = project) { - it.outputDir.set(outputDir) - it.input.set( - listOf( - PrefabPreprocessingEntry( - "libraryone", listOf("input/lib1/" to "", "input/shared/" to "shared/")), - PrefabPreprocessingEntry( - "librarytwo", listOf("input/lib2/" to "", "input/shared/" to "shared/")), - )) - } - - task.taskAction() - - assertTrue(File(outputDir, "libraryone/hello1.h").exists()) - assertTrue(File(outputDir, "libraryone/shared/sharedheader.h").exists()) - assertTrue(File(outputDir, "librarytwo/hello2.h").exists()) - assertTrue(File(outputDir, "librarytwo/shared/sharedheader.h").exists()) - } - - @Test - fun preparePrefabHeadersTask_withBoostHeaders_filtersThemCorrectly() { - val outputDir = tempFolder.newFolder("output") - File(tempFolder.root, "boost/boost/config.hpp").createNewPathAndFile() - File(tempFolder.root, "boost/boost/operators.hpp").createNewPathAndFile() - File(tempFolder.root, "boost/boost/config/default/default.hpp").createNewPathAndFile() - File(tempFolder.root, "boost/boost/core/core.hpp").createNewPathAndFile() - File(tempFolder.root, "boost/boost/detail/workaround.hpp").createNewPathAndFile() - File(tempFolder.root, "boost/boost/preprocessor/preprocessor.hpp").createNewPathAndFile() - File(tempFolder.root, "boost/boost/preprocessor/detail/preprocessor_detail.hpp") - .createNewPathAndFile() - File(tempFolder.root, "boost/boost/anothermodule/wedontuse.hpp").createNewPathAndFile() - - val project = createProject(projectDir = tempFolder.root) - val task = - createTestTask(project = project) { - it.outputDir.set(outputDir) - it.input.set(listOf(PrefabPreprocessingEntry("sample_library", "boost/" to ""))) - } - - task.taskAction() - - assertTrue(File(outputDir, "sample_library/boost/config.hpp").exists()) - assertTrue(File(outputDir, "sample_library/boost/operators.hpp").exists()) - assertTrue(File(outputDir, "sample_library/boost/config/default/default.hpp").exists()) - assertTrue(File(outputDir, "sample_library/boost/core/core.hpp").exists()) - assertTrue(File(outputDir, "sample_library/boost/detail/workaround.hpp").exists()) - assertTrue(File(outputDir, "sample_library/boost/preprocessor/preprocessor.hpp").exists()) - assertTrue( - File(outputDir, "sample_library/boost/preprocessor/detail/preprocessor_detail.hpp") - .exists()) - assertFalse(File(outputDir, "sample_library/boost/anothermodule/wedontuse.hpp").exists()) - } - - private fun File.createNewPathAndFile() { - parentFile.mkdirs() - createNewFile() - } -} diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/internal/utils/PrefabPreprocessingEntryTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/internal/utils/PrefabPreprocessingEntryTest.kt deleted file mode 100644 index a8ab05065b07..000000000000 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/internal/utils/PrefabPreprocessingEntryTest.kt +++ /dev/null @@ -1,25 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.tasks.internal.utils - -import groovy.test.GroovyTestCase.assertEquals -import org.junit.Test - -class PrefabPreprocessingEntryTest { - - @Test - fun secondaryConstructor_createsAList() { - val sampleEntry = - PrefabPreprocessingEntry( - libraryName = "justALibrary", pathToPrefixCouple = "aPath" to "andAPrefix") - - assertEquals(1, sampleEntry.pathToPrefixCouples.size) - assertEquals("aPath", sampleEntry.pathToPrefixCouples[0].first) - assertEquals("andAPrefix", sampleEntry.pathToPrefixCouples[0].second) - } -} diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tests/OsRule.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tests/OsRule.kt deleted file mode 100644 index 8d500d0a7192..000000000000 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tests/OsRule.kt +++ /dev/null @@ -1,52 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.tests - -import org.junit.rules.TestRule -import org.junit.runner.Description -import org.junit.runners.model.Statement - -/** - * A JUnit [TestRule] to override values of [System.getProperties] with the support of the [WithOs] - * annotation. - */ -class OsRule : TestRule { - - private var retainOs: String? = null - private var retainArch: String? = null - - override fun apply(statement: Statement, description: Description): Statement { - return object : Statement() { - override fun evaluate() { - val annotation = description.annotations.filterIsInstance().firstOrNull() - - annotation?.os?.propertyName?.let { - retainOs = System.getProperty(OS_NAME_KEY) - System.setProperty(OS_NAME_KEY, it) - } - annotation?.arch?.let { - if (it.isNotBlank()) { - retainArch = System.getProperty(OS_ARCH_KEY) - System.setProperty(OS_ARCH_KEY, it) - } - } - try { - statement.evaluate() - } finally { - retainOs?.let { System.setProperty(OS_NAME_KEY, it) } - retainArch?.let { System.setProperty(OS_ARCH_KEY, it) } - } - } - } - } - - companion object { - const val OS_NAME_KEY = "os.name" - const val OS_ARCH_KEY = "os.arch" - } -} diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tests/TaskTestUtils.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tests/TaskTestUtils.kt deleted file mode 100644 index b677cca66704..000000000000 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tests/TaskTestUtils.kt +++ /dev/null @@ -1,69 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.tests - -import java.io.* -import java.net.URI -import java.nio.file.FileSystems -import java.nio.file.Files -import java.util.zip.ZipEntry -import java.util.zip.ZipOutputStream -import org.gradle.api.Project -import org.gradle.api.Task -import org.gradle.testfixtures.ProjectBuilder - -internal fun createProject(projectDir: File? = null): Project { - val project = - ProjectBuilder.builder() - .apply { - if (projectDir != null) { - withProjectDir(projectDir) - } - } - .build() - - project.plugins.apply("com.android.library") - project.plugins.apply("com.facebook.react") - return project -} - -internal inline fun createTestTask( - project: Project = createProject(), - taskName: String = T::class.java.simpleName, - crossinline block: (T) -> Unit = {} -): T = project.tasks.register(taskName, T::class.java) { block(it) }.get() - -/** A util function to zip a list of files from [contents] inside the zipfile at [destination]. */ -internal fun zipFiles(destination: File, contents: List) { - ZipOutputStream(BufferedOutputStream(FileOutputStream(destination.absolutePath))).use { out -> - for (file in contents) { - FileInputStream(file).use { fi -> - BufferedInputStream(fi).use { origin -> - val entry = ZipEntry(file.name) - out.putNextEntry(entry) - origin.copyTo(out, 1024) - } - } - } - } -} - -/** A util function to create a zip given a list of dummy files path. */ -internal fun createZip(dest: File, paths: List) { - val env = mapOf("create" to "true") - val uri = URI.create("jar:file:$dest") - - FileSystems.newFileSystem(uri, env).use { zipfs -> - paths.forEach { - val zipEntryPath = zipfs.getPath(it) - val zipEntryFolder = zipEntryPath.subpath(0, zipEntryPath.nameCount - 1) - Files.createDirectories(zipEntryFolder) - Files.createFile(zipEntryPath) - } - } -} diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tests/WithOs.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tests/WithOs.kt deleted file mode 100644 index 45d0a0072afd..000000000000 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tests/WithOs.kt +++ /dev/null @@ -1,17 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.tests - -/** Annotation to specify an Operating System to override the "os.name" System Property. */ -@Retention(AnnotationRetention.RUNTIME) annotation class WithOs(val os: OS, val arch: String = "") - -enum class OS(val propertyName: String) { - WIN("Windows"), - MAC("MacOs"), - LINUX("Linux") -} diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/BackwardCompatUtilsTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/BackwardCompatUtilsTest.kt deleted file mode 100644 index da08d88ad06a..000000000000 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/BackwardCompatUtilsTest.kt +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.utils - -import com.facebook.react.tests.createProject -import com.facebook.react.utils.BackwardCompatUtils.configureBackwardCompatibilityReactMap -import org.junit.Assert.assertTrue -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TemporaryFolder - -class BackwardCompatUtilsTest { - - @get:Rule val tempFolder = TemporaryFolder() - - @Test - fun configureBackwardCompatibilityReactMap_addsEmptyReactMap() { - val project = createProject() - - configureBackwardCompatibilityReactMap(project) - - assertTrue(project.extensions.extraProperties.has("react")) - @Suppress("UNCHECKED_CAST") - assertTrue((project.extensions.extraProperties.get("react") as Map).isEmpty()) - } - - @Test - fun configureBackwardCompatibilityReactMap_withExistingMapSetByUser_wipesTheMap() { - val project = createProject() - project.extensions.extraProperties.set("react", mapOf("enableHermes" to true)) - - configureBackwardCompatibilityReactMap(project) - - assertTrue(project.extensions.extraProperties.has("react")) - @Suppress("UNCHECKED_CAST") - assertTrue((project.extensions.extraProperties.get("react") as Map).isEmpty()) - } -} diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/DependencyUtilsTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/DependencyUtilsTest.kt deleted file mode 100644 index f77c0bb3026b..000000000000 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/DependencyUtilsTest.kt +++ /dev/null @@ -1,361 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.utils - -import com.facebook.react.tests.createProject -import com.facebook.react.utils.DependencyUtils.configureDependencies -import com.facebook.react.utils.DependencyUtils.configureRepositories -import com.facebook.react.utils.DependencyUtils.mavenRepoFromURI -import com.facebook.react.utils.DependencyUtils.mavenRepoFromUrl -import com.facebook.react.utils.DependencyUtils.readVersionAndGroupStrings -import java.net.URI -import org.gradle.api.artifacts.repositories.MavenArtifactRepository -import org.gradle.testfixtures.ProjectBuilder -import org.junit.Assert.* -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TemporaryFolder - -class DependencyUtilsTest { - - @get:Rule val tempFolder = TemporaryFolder() - - @Test - fun configureRepositories_withProjectPropertySet_configuresMavenLocalCorrectly() { - val localMaven = tempFolder.newFolder("m2") - val localMavenURI = localMaven.toURI() - val project = createProject() - project.extensions.extraProperties.set("REACT_NATIVE_MAVEN_LOCAL_REPO", localMaven.absolutePath) - - configureRepositories(project, tempFolder.root) - - assertNotNull( - project.repositories.firstOrNull { - it is MavenArtifactRepository && it.url == localMavenURI - }) - } - - @Test - fun configureRepositories_containsSnapshotRepo() { - val repositoryURI = URI.create("https://oss.sonatype.org/content/repositories/snapshots/") - val project = createProject() - - configureRepositories(project, tempFolder.root) - - assertNotNull( - project.repositories.firstOrNull { - it is MavenArtifactRepository && it.url == repositoryURI - }) - } - - @Test - fun configureRepositories_containsJscLocalMavenRepo() { - val projectFolder = tempFolder.newFolder() - val reactNativeDir = tempFolder.newFolder("react-native") - val jscAndroidDir = tempFolder.newFolder("jsc-android") - val repositoryURI = URI.create("file://${jscAndroidDir}/dist") - val project = createProject(projectFolder) - - configureRepositories(project, reactNativeDir) - - assertNotNull( - project.repositories.firstOrNull { - it is MavenArtifactRepository && it.url == repositoryURI - }) - } - - @Test - fun configureRepositories_containsMavenCentral() { - val repositoryURI = URI.create("https://repo.maven.apache.org/maven2/") - val project = createProject() - - configureRepositories(project, tempFolder.root) - - assertNotNull( - project.repositories.firstOrNull { - it is MavenArtifactRepository && it.url == repositoryURI - }) - } - - @Test - fun configureRepositories_containsGoogleRepo() { - val repositoryURI = URI.create("https://dl.google.com/dl/android/maven2/") - val project = createProject() - - configureRepositories(project, tempFolder.root) - - assertNotNull( - project.repositories.firstOrNull { - it is MavenArtifactRepository && it.url == repositoryURI - }) - } - - @Test - fun configureRepositories_containsJitPack() { - val repositoryURI = URI.create("https://www.jitpack.io") - val project = createProject() - - configureRepositories(project, tempFolder.root) - - assertNotNull( - project.repositories.firstOrNull { - it is MavenArtifactRepository && it.url == repositoryURI - }) - } - - @Test - fun configureRepositories_withProjectPropertySet_hasHigherPriorityThanMavenCentral() { - val localMaven = tempFolder.newFolder("m2") - val localMavenURI = localMaven.toURI() - val mavenCentralURI = URI.create("https://repo.maven.apache.org/maven2/") - val project = createProject() - project.extensions.extraProperties.set("REACT_NATIVE_MAVEN_LOCAL_REPO", localMaven.absolutePath) - - configureRepositories(project, tempFolder.root) - - val indexOfLocalRepo = - project.repositories.indexOfFirst { - it is MavenArtifactRepository && it.url == localMavenURI - } - val indexOfMavenCentral = - project.repositories.indexOfFirst { - it is MavenArtifactRepository && it.url == mavenCentralURI - } - assertTrue(indexOfLocalRepo < indexOfMavenCentral) - } - - @Test - fun configureRepositories_snapshotRepoHasHigherPriorityThanMavenCentral() { - val repositoryURI = URI.create("https://oss.sonatype.org/content/repositories/snapshots/") - val mavenCentralURI = URI.create("https://repo.maven.apache.org/maven2/") - val project = createProject() - - configureRepositories(project, tempFolder.root) - - val indexOfSnapshotRepo = - project.repositories.indexOfFirst { - it is MavenArtifactRepository && it.url == repositoryURI - } - val indexOfMavenCentral = - project.repositories.indexOfFirst { - it is MavenArtifactRepository && it.url == mavenCentralURI - } - assertTrue(indexOfSnapshotRepo < indexOfMavenCentral) - } - - @Test - fun configureRepositories_appliesToAllProjects() { - val repositoryURI = URI.create("https://repo.maven.apache.org/maven2/") - val rootProject = ProjectBuilder.builder().build() - val appProject = ProjectBuilder.builder().withName("app").withParent(rootProject).build() - val libProject = ProjectBuilder.builder().withName("lib").withParent(rootProject).build() - - configureRepositories(appProject, tempFolder.root) - - assertNotNull( - appProject.repositories.firstOrNull { - it is MavenArtifactRepository && it.url == repositoryURI - }) - assertNotNull( - libProject.repositories.firstOrNull { - it is MavenArtifactRepository && it.url == repositoryURI - }) - } - - @Test - fun configureRepositories_withPreviousExclusionRulesOnMavenCentral_appliesCorrectly() { - val repositoryURI = URI.create("https://repo.maven.apache.org/maven2/") - val rootProject = ProjectBuilder.builder().build() - val appProject = ProjectBuilder.builder().withName("app").withParent(rootProject).build() - val libProject = ProjectBuilder.builder().withName("lib").withParent(rootProject).build() - - // Let's emulate a library which set an `excludeGroup` on `com.facebook.react` for Central. - libProject.repositories.mavenCentral { repo -> - repo.content { content -> content.excludeGroup("com.facebook.react") } - } - - configureRepositories(appProject, tempFolder.root) - - // We need to make sure we have Maven Central defined twice, one by the library, - // and another is the override by RNGP. - assertEquals( - 2, - libProject.repositories.count { it is MavenArtifactRepository && it.url == repositoryURI }) - } - - @Test - fun configureDependencies_withEmptyVersion_doesNothing() { - val project = createProject() - - configureDependencies(project, "") - - assertTrue(project.configurations.first().resolutionStrategy.forcedModules.isEmpty()) - } - - @Test - fun configureDependencies_withVersionString_appliesResolutionStrategy() { - val project = createProject() - - configureDependencies(project, "1.2.3") - - val forcedModules = project.configurations.first().resolutionStrategy.forcedModules - assertTrue(forcedModules.any { it.toString() == "com.facebook.react:react-android:1.2.3" }) - assertTrue(forcedModules.any { it.toString() == "com.facebook.react:hermes-android:1.2.3" }) - } - - @Test - fun configureDependencies_withVersionString_appliesOnAllProjects() { - val rootProject = ProjectBuilder.builder().build() - val appProject = ProjectBuilder.builder().withName("app").withParent(rootProject).build() - val libProject = ProjectBuilder.builder().withName("lib").withParent(rootProject).build() - appProject.plugins.apply("com.android.application") - libProject.plugins.apply("com.android.library") - - configureDependencies(appProject, "1.2.3") - - val appForcedModules = appProject.configurations.first().resolutionStrategy.forcedModules - val libForcedModules = libProject.configurations.first().resolutionStrategy.forcedModules - assertTrue(appForcedModules.any { it.toString() == "com.facebook.react:react-android:1.2.3" }) - assertTrue(appForcedModules.any { it.toString() == "com.facebook.react:hermes-android:1.2.3" }) - assertTrue(libForcedModules.any { it.toString() == "com.facebook.react:react-android:1.2.3" }) - assertTrue(libForcedModules.any { it.toString() == "com.facebook.react:hermes-android:1.2.3" }) - } - - @Test - fun configureDependencies_withVersionStringAndGroupString_appliesOnAllProjects() { - val rootProject = ProjectBuilder.builder().build() - val appProject = ProjectBuilder.builder().withName("app").withParent(rootProject).build() - val libProject = ProjectBuilder.builder().withName("lib").withParent(rootProject).build() - appProject.plugins.apply("com.android.application") - libProject.plugins.apply("com.android.library") - - configureDependencies(appProject, "1.2.3", "io.github.test") - - val appForcedModules = appProject.configurations.first().resolutionStrategy.forcedModules - val libForcedModules = libProject.configurations.first().resolutionStrategy.forcedModules - assertTrue(appForcedModules.any { it.toString() == "io.github.test:react-android:1.2.3" }) - assertTrue(appForcedModules.any { it.toString() == "io.github.test:hermes-android:1.2.3" }) - assertTrue(libForcedModules.any { it.toString() == "io.github.test:react-android:1.2.3" }) - assertTrue(libForcedModules.any { it.toString() == "io.github.test:hermes-android:1.2.3" }) - } - - @Test - fun readVersionString_withCorrectVersionString_returnsIt() { - val propertiesFile = - tempFolder.newFile("gradle.properties").apply { - writeText( - """ - VERSION_NAME=1000.0.0 - ANOTHER_PROPERTY=true - """ - .trimIndent()) - } - - val versionString = readVersionAndGroupStrings(propertiesFile).first - - assertEquals("1000.0.0", versionString) - } - - @Test - fun readVersionString_withNightlyVersionString_returnsSnapshotVersion() { - val propertiesFile = - tempFolder.newFile("gradle.properties").apply { - writeText( - """ - VERSION_NAME=0.0.0-20221101-2019-cfe811ab1 - ANOTHER_PROPERTY=true - """ - .trimIndent()) - } - - val versionString = readVersionAndGroupStrings(propertiesFile).first - - assertEquals("0.0.0-20221101-2019-cfe811ab1-SNAPSHOT", versionString) - } - - @Test - fun readVersionString_withMissingVersionString_returnsEmpty() { - val propertiesFile = - tempFolder.newFile("gradle.properties").apply { - writeText( - """ - ANOTHER_PROPERTY=true - """ - .trimIndent()) - } - - val versionString = readVersionAndGroupStrings(propertiesFile).first - assertEquals("", versionString) - } - - @Test - fun readVersionString_withEmptyVersionString_returnsEmpty() { - val propertiesFile = - tempFolder.newFile("gradle.properties").apply { - writeText( - """ - VERSION_NAME= - ANOTHER_PROPERTY=true - """ - .trimIndent()) - } - - val versionString = readVersionAndGroupStrings(propertiesFile).first - assertEquals("", versionString) - } - - @Test - fun readGroupString_withCorrectGroupString_returnsIt() { - val propertiesFile = - tempFolder.newFile("gradle.properties").apply { - writeText( - """ - GROUP=io.github.test - ANOTHER_PROPERTY=true - """ - .trimIndent()) - } - - val groupString = readVersionAndGroupStrings(propertiesFile).second - - assertEquals("io.github.test", groupString) - } - - @Test - fun readGroupString_withEmptyGroupString_returnsDefault() { - val propertiesFile = - tempFolder.newFile("gradle.properties").apply { - writeText( - """ - ANOTHER_PROPERTY=true - """ - .trimIndent()) - } - - val groupString = readVersionAndGroupStrings(propertiesFile).second - - assertEquals("com.facebook.react", groupString) - } - - @Test - fun mavenRepoFromUrl_worksCorrectly() { - val process = createProject() - val mavenRepo = process.mavenRepoFromUrl("https://hello.world") - - assertEquals(URI.create("https://hello.world"), mavenRepo.url) - } - - @Test - fun mavenRepoFromURI_worksCorrectly() { - val process = createProject() - val repoFolder = tempFolder.newFolder("maven-repo") - val mavenRepo = process.mavenRepoFromURI(repoFolder.toURI()) - - assertEquals(repoFolder.toURI(), mavenRepo.url) - } -} diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/FileUtilsTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/FileUtilsTest.kt deleted file mode 100644 index a47e6ed47b88..000000000000 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/FileUtilsTest.kt +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.utils - -import java.io.File -import org.junit.Assert.* -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TemporaryFolder - -class FileUtilsTest { - - @get:Rule val tempFolder = TemporaryFolder() - - @Test - fun moveTo_movesCorrectly() { - val fileToMove = tempFolder.newFile().apply { writeText("42") } - val destFolder = tempFolder.newFolder("destFolder") - val destFile = File(destFolder, "destFile") - - fileToMove.moveTo(destFile) - - assertEquals("42", destFile.readText()) - assertFalse(fileToMove.exists()) - } - - @Test - fun recreateDir_worksCorrectly() { - val subFolder = tempFolder.newFolder() - File(subFolder, "1").apply { writeText("1") } - File(subFolder, "2").apply { writeText("2") } - File(subFolder, "subDir").apply { mkdirs() } - File(subFolder, "subDir/3").apply { writeText("3") } - - subFolder.recreateDir() - - assertTrue(subFolder.exists()) - assertEquals(0, subFolder.listFiles()?.size) - } -} diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/JsonUtilsTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/JsonUtilsTest.kt deleted file mode 100644 index 6335758685ac..000000000000 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/JsonUtilsTest.kt +++ /dev/null @@ -1,94 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.utils - -import org.intellij.lang.annotations.Language -import org.junit.Assert.* -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TemporaryFolder - -class JsonUtilsTest { - - @get:Rule val tempFolder = TemporaryFolder() - - @Test - fun withInvalidJson_returnsNull() { - val invalidJson = createJsonFile("""¯\_(ツ)_/¯""") - - assertNull(JsonUtils.fromCodegenJson(invalidJson)) - } - - @Test - fun withEmptyJson_returnsEmptyObject() { - val invalidJson = createJsonFile("""{}""") - - val parsed = JsonUtils.fromCodegenJson(invalidJson) - - assertNotNull(parsed) - assertNull(parsed?.codegenConfig) - } - - @Test - fun withOldJsonConfig_returnsAnEmptyLibrary() { - val oldJsonConfig = - createJsonFile( - """ - { - "name": "yet another npm package", - "codegenConfig": { - "libraries": [ - { - "name": "an awesome library", - "jsSrcsDir": "../js/", - "android": {} - } - ] - } - } - """ - .trimIndent()) - - val parsed = JsonUtils.fromCodegenJson(oldJsonConfig)!! - - assertNull(parsed.codegenConfig?.name) - assertNull(parsed.codegenConfig?.jsSrcsDir) - assertNull(parsed.codegenConfig?.android) - } - - @Test - fun withValidJson_parsesCorrectly() { - val validJson = - createJsonFile( - """ - { - "name": "yet another npm package", - "codegenConfig": { - "name": "an awesome library", - "jsSrcsDir": "../js/", - "android": { - "javaPackageName": "com.awesome.library" - }, - "ios": { - "other ios only keys": "which are ignored during parsing" - } - } - } - """ - .trimIndent()) - - val parsed = JsonUtils.fromCodegenJson(validJson)!! - - assertEquals("an awesome library", parsed.codegenConfig!!.name) - assertEquals("../js/", parsed.codegenConfig!!.jsSrcsDir) - assertEquals("com.awesome.library", parsed.codegenConfig!!.android!!.javaPackageName) - } - - private fun createJsonFile(@Language("JSON") input: String) = - tempFolder.newFile().apply { writeText(input) } -} diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/NdkConfiguratorUtilsTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/NdkConfiguratorUtilsTest.kt deleted file mode 100644 index bf2f27926ab3..000000000000 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/NdkConfiguratorUtilsTest.kt +++ /dev/null @@ -1,46 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.utils - -import com.facebook.react.utils.NdkConfiguratorUtils.getPackagingOptionsForVariant -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Test - -class NdkConfiguratorUtilsTest { - - @Test - fun getPackagingOptionsForVariant_withHermesEnabled() { - val (excludes, includes) = getPackagingOptionsForVariant(hermesEnabled = true) - - assertTrue("**/libjsc.so" in excludes) - assertTrue("**/libjscexecutor.so" in excludes) - assertFalse("**/libjsc.so" in includes) - assertFalse("**/libjscexecutor.so" in includes) - - assertTrue("**/libhermes.so" in includes) - assertTrue("**/libhermes_executor.so" in includes) - assertFalse("**/libhermes.so" in excludes) - assertFalse("**/libhermes_executor.so" in excludes) - } - - @Test - fun getPackagingOptionsForVariant_withHermesDisabled() { - val (excludes, includes) = getPackagingOptionsForVariant(hermesEnabled = false) - - assertTrue("**/libhermes.so" in excludes) - assertTrue("**/libhermes_executor.so" in excludes) - assertFalse("**/libhermes.so" in includes) - assertFalse("**/libhermes_executor.so" in includes) - - assertTrue("**/libjsc.so" in includes) - assertTrue("**/libjscexecutor.so" in includes) - assertFalse("**/libjsc.so" in excludes) - assertFalse("**/libjscexecutor.so" in excludes) - } -} diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/OsTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/OsTest.kt deleted file mode 100644 index b58a2e067f8d..000000000000 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/OsTest.kt +++ /dev/null @@ -1,86 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.utils - -import com.facebook.react.tests.OS -import com.facebook.react.tests.OsRule -import com.facebook.react.tests.WithOs -import com.facebook.react.utils.Os.cliPath -import com.facebook.react.utils.Os.unixifyPath -import org.junit.Assert.* -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TemporaryFolder - -class OsTest { - - @get:Rule val osRule = OsRule() - @get:Rule val tempFolder = TemporaryFolder() - - @Test - @WithOs(OS.LINUX, "amd64") - fun onLinuxAmd64_checksOsCorrectly() { - assertFalse(Os.isWindows()) - assertFalse(Os.isMac()) - assertTrue(Os.isLinuxAmd64()) - } - - @Test - @WithOs(OS.MAC) - fun onMac_checksOsCorrectly() { - assertFalse(Os.isWindows()) - assertTrue(Os.isMac()) - assertFalse(Os.isLinuxAmd64()) - } - - @Test - @WithOs(OS.WIN) - fun isWindows_onWindows_returnsTrue() { - assertTrue(Os.isWindows()) - assertFalse(Os.isMac()) - assertFalse(Os.isLinuxAmd64()) - } - - @Test - fun unixifyPath_withAUnixPath_doesNothing() { - val aUnixPath = "/just/a/unix/path.sh" - - assertEquals(aUnixPath, aUnixPath.unixifyPath()) - } - - @Test - fun unixifyPath_withAWindowsPath_convertsItCorrectly() { - val aWindowsPath = "D:\\just\\a\\windows\\path\\" - - assertEquals("/D/just/a/windows/path/", aWindowsPath.unixifyPath()) - } - - @Test - @WithOs(OS.WIN) - fun cliPath_onWindows_returnsRelativePath() { - val tempFile = tempFolder.newFile("test.txt").apply { createNewFile() } - - assertEquals(tempFile.relativeTo(tempFolder.root).path, tempFile.cliPath(tempFolder.root)) - } - - @Test - @WithOs(OS.LINUX) - fun cliPath_onLinux_returnsAbsolutePath() { - val tempFile = tempFolder.newFile("test.txt").apply { createNewFile() } - - assertEquals(tempFile.absolutePath, tempFile.cliPath(tempFolder.root)) - } - - @Test - @WithOs(OS.MAC) - fun cliPath_onMac_returnsAbsolutePath() { - val tempFile = tempFolder.newFile("test.txt").apply { createNewFile() } - - assertEquals(tempFile.absolutePath, tempFile.cliPath(tempFolder.root)) - } -} diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/PathUtilsTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/PathUtilsTest.kt deleted file mode 100644 index 461a66147601..000000000000 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/PathUtilsTest.kt +++ /dev/null @@ -1,320 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.utils - -import com.facebook.react.ReactExtension -import com.facebook.react.TestReactExtension -import com.facebook.react.tests.OS -import com.facebook.react.tests.OsRule -import com.facebook.react.tests.WithOs -import java.io.File -import org.gradle.testfixtures.ProjectBuilder -import org.junit.Assert.* -import org.junit.Assume.assumeTrue -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TemporaryFolder - -class PathUtilsTest { - - @get:Rule val tempFolder = TemporaryFolder() - @get:Rule val osRule = OsRule() - - @Test - fun detectedEntryFile_withProvidedVariable() { - val extension = TestReactExtension(ProjectBuilder.builder().build()) - val expected = tempFolder.newFile("fake.index.js") - extension.entryFile.set(expected) - - val actual = detectedEntryFile(extension) - - assertEquals(expected, actual) - } - - @Test - fun detectedEntryFile_withAndroidEntryPoint() { - val extension = TestReactExtension(ProjectBuilder.builder().build()) - extension.root.set(tempFolder.root) - tempFolder.newFile("index.android.js") - - val actual = detectedEntryFile(extension) - - assertEquals(File(tempFolder.root, "index.android.js"), actual) - } - - @Test - fun detectedEntryFile_withDefaultEntryPoint() { - val extension = TestReactExtension(ProjectBuilder.builder().build()) - extension.root.set(tempFolder.root) - - val actual = detectedEntryFile(extension) - - assertEquals(File(tempFolder.root, "index.js"), actual) - } - - @Test - fun detectedEntryFile_withEnvironmentVariable() { - val extension = TestReactExtension(ProjectBuilder.builder().build()) - val expected = tempFolder.newFile("./fromenv.index.js") - // As we can't override env variable for tests, we're going to emulate them here. - val envVariable = "./fromenv.index.js" - - extension.root.set(tempFolder.root) - - val actual = detectedEntryFile(extension, envVariable) - - assertEquals(expected, actual) - } - - @Test - fun detectedCliPath_withCliPathFromExtensionAndFileExists_returnsIt() { - val project = ProjectBuilder.builder().build() - val cliFile = tempFolder.newFile("cli.js").apply { createNewFile() } - val extension = TestReactExtension(project) - extension.cliFile.set(cliFile) - - val actual = detectedCliFile(extension) - - assertEquals(cliFile, actual) - } - - @Test - fun detectedCliPath_withCliFromNodeModules() { - val project = ProjectBuilder.builder().build() - val extension = TestReactExtension(project) - File(tempFolder.root, "node_modules/react-native/cli.js").apply { - parentFile.mkdirs() - writeText("") - } - val locationToResolveFrom = File(tempFolder.root, "a-subdirectory").apply { mkdirs() } - extension.root.set(locationToResolveFrom) - - val actual = detectedCliFile(extension) - - assertEquals("", actual.readText()) - } - - @Test(expected = IllegalStateException::class) - fun detectedCliPath_failsIfNotFound() { - val project = ProjectBuilder.builder().build() - val extension = TestReactExtension(project) - - detectedCliFile(extension) - } - - @Test - fun projectPathToLibraryName_withSimplePath() { - assertEquals("SampleSpec", projectPathToLibraryName(":sample")) - } - - @Test - fun projectPathToLibraryName_withComplexPath() { - assertEquals("SampleAndroidAppSpec", projectPathToLibraryName(":sample:android:app")) - } - - @Test - fun projectPathToLibraryName_withKebabCase() { - assertEquals("SampleAndroidAppSpec", projectPathToLibraryName("sample-android-app")) - } - - @Test - fun projectPathToLibraryName_withDotsAndUnderscores() { - assertEquals("SampleAndroidAppSpec", projectPathToLibraryName("sample_android.app")) - } - - @Test - fun detectOSAwareHermesCommand_withProvidedCommand() { - assertEquals( - "./my-home/hermes", detectOSAwareHermesCommand(tempFolder.root, "./my-home/hermes")) - } - - @Test - fun detectOSAwareHermesCommand_withHermescBuiltLocally() { - // As we can't mock env variables, we skip this test if an override of the Hermes - // path has been provided. - assumeTrue(System.getenv("REACT_NATIVE_OVERRIDE_HERMES_DIR") == null) - - tempFolder.newFolder("node_modules/react-native/ReactAndroid/hermes-engine/build/hermes/bin/") - val expected = - tempFolder.newFile( - "node_modules/react-native/ReactAndroid/hermes-engine/build/hermes/bin/hermesc") - - assertEquals(expected.toString(), detectOSAwareHermesCommand(tempFolder.root, "")) - } - - @Test - @WithOs(OS.MAC) - fun detectOSAwareHermesCommand_withBundledHermescInsideRN() { - tempFolder.newFolder("node_modules/react-native/sdks/hermesc/osx-bin/") - val expected = tempFolder.newFile("node_modules/react-native/sdks/hermesc/osx-bin/hermesc") - - assertEquals(expected.toString(), detectOSAwareHermesCommand(tempFolder.root, "")) - } - - @Test(expected = IllegalStateException::class) - @WithOs(OS.MAC) - fun detectOSAwareHermesCommand_failsIfNotFound() { - detectOSAwareHermesCommand(tempFolder.root, "") - } - - @Test - @WithOs(OS.MAC) - fun detectOSAwareHermesCommand_withProvidedCommand_takesPrecedence() { - tempFolder.newFolder("node_modules/react-native/sdks/hermes/build/bin/") - tempFolder.newFile("node_modules/react-native/sdks/hermes/build/bin/hermesc") - tempFolder.newFolder("node_modules/react-native/sdks/hermesc/osx-bin/") - tempFolder.newFile("node_modules/react-native/sdks/hermesc/osx-bin/hermesc") - - assertEquals( - "./my-home/hermes", detectOSAwareHermesCommand(tempFolder.root, "./my-home/hermes")) - } - - @Test - @WithOs(OS.MAC) - fun detectOSAwareHermesCommand_withoutProvidedCommand_builtHermescTakesPrecedence() { - // As we can't mock env variables, we skip this test if an override of the Hermes - // path has been provided. - assumeTrue(System.getenv("REACT_NATIVE_OVERRIDE_HERMES_DIR") == null) - - tempFolder.newFolder("node_modules/react-native/ReactAndroid/hermes-engine/build/hermes/bin/") - val expected = - tempFolder.newFile( - "node_modules/react-native/ReactAndroid/hermes-engine/build/hermes/bin/hermesc") - tempFolder.newFolder("node_modules/react-native/sdks/hermesc/osx-bin/") - tempFolder.newFile("node_modules/react-native/sdks/hermesc/osx-bin/hermesc") - - assertEquals(expected.toString(), detectOSAwareHermesCommand(tempFolder.root, "")) - } - - @Test - fun getBuiltHermescFile_withoutOverride() { - assertEquals( - File( - tempFolder.root, - "node_modules/react-native/ReactAndroid/hermes-engine/build/hermes/bin/hermesc"), - getBuiltHermescFile(tempFolder.root, "")) - } - - @Test - @WithOs(OS.WIN) - fun getBuiltHermescFile_onWindows_withoutOverride() { - assertEquals( - File( - tempFolder.root, - "node_modules/react-native/ReactAndroid/hermes-engine/build/hermes/bin/hermesc.exe"), - getBuiltHermescFile(tempFolder.root, "")) - } - - @Test - fun getBuiltHermescFile_withOverride() { - assertEquals( - File("/home/circleci/hermes/build/bin/hermesc"), - getBuiltHermescFile(tempFolder.root, "/home/circleci/hermes")) - } - - @Test - @WithOs(OS.WIN) - fun getHermesCBin_onWindows_returnsHermescExe() { - assertEquals("hermesc.exe", getHermesCBin()) - } - - @Test - @WithOs(OS.LINUX) - fun getHermesCBin_onLinux_returnsHermesc() { - assertEquals("hermesc", getHermesCBin()) - } - - @Test - @WithOs(OS.MAC) - fun getHermesCBin_onMac_returnsHermesc() { - assertEquals("hermesc", getHermesCBin()) - } - - @Test - fun findPackageJsonFile_withFileInParentFolder_picksItUp() { - tempFolder.newFile("package.json") - val moduleFolder = tempFolder.newFolder("awesome-module") - - val project = ProjectBuilder.builder().withProjectDir(moduleFolder).build() - project.plugins.apply("com.android.library") - project.plugins.apply("com.facebook.react") - val extension = project.extensions.getByType(ReactExtension::class.java) - - assertEquals(project.file("../package.json"), findPackageJsonFile(project, extension.root)) - } - - @Test - fun findPackageJsonFile_withFileConfiguredInExtension_picksItUp() { - val moduleFolder = tempFolder.newFolder("awesome-module") - val localFile = File(moduleFolder, "package.json").apply { writeText("{}") } - - val project = ProjectBuilder.builder().withProjectDir(moduleFolder).build() - project.plugins.apply("com.android.library") - project.plugins.apply("com.facebook.react") - val extension = - project.extensions.getByType(ReactExtension::class.java).apply { root.set(moduleFolder) } - - assertEquals(localFile, findPackageJsonFile(project, extension.root)) - } - - @Test - fun readPackageJsonFile_withMissingFile_returnsNull() { - val moduleFolder = tempFolder.newFolder("awesome-module") - val project = ProjectBuilder.builder().withProjectDir(moduleFolder).build() - project.plugins.apply("com.android.library") - project.plugins.apply("com.facebook.react") - val extension = - project.extensions.getByType(ReactExtension::class.java).apply { root.set(moduleFolder) } - - val actual = readPackageJsonFile(project, extension.root) - - assertNull(actual) - } - - @Test - fun readPackageJsonFile_withFileConfiguredInExtension_andMissingCodegenConfig_returnsNullCodegenConfig() { - val moduleFolder = tempFolder.newFolder("awesome-module") - File(moduleFolder, "package.json").apply { writeText("{}") } - val project = ProjectBuilder.builder().withProjectDir(moduleFolder).build() - project.plugins.apply("com.android.library") - project.plugins.apply("com.facebook.react") - val extension = - project.extensions.getByType(ReactExtension::class.java).apply { root.set(moduleFolder) } - - val actual = readPackageJsonFile(project, extension.root) - - assertNotNull(actual) - assertNull(actual!!.codegenConfig) - } - - @Test - fun readPackageJsonFile_withFileConfiguredInExtension_andHavingCodegenConfig_returnsValidCodegenConfig() { - val moduleFolder = tempFolder.newFolder("awesome-module") - File(moduleFolder, "package.json").apply { - writeText( - // language=json - """ - { - "name": "a-library", - "codegenConfig": {} - } - """ - .trimIndent()) - } - val project = ProjectBuilder.builder().withProjectDir(moduleFolder).build() - project.plugins.apply("com.android.library") - project.plugins.apply("com.facebook.react") - val extension = - project.extensions.getByType(ReactExtension::class.java).apply { root.set(moduleFolder) } - - val actual = readPackageJsonFile(project, extension.root) - - assertNotNull(actual) - assertNotNull(actual!!.codegenConfig) - } -} diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/ProjectUtilsTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/ProjectUtilsTest.kt deleted file mode 100644 index 70ea15401cc6..000000000000 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/ProjectUtilsTest.kt +++ /dev/null @@ -1,209 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.utils - -import com.facebook.react.TestReactExtension -import com.facebook.react.model.ModelCodegenConfig -import com.facebook.react.model.ModelPackageJson -import com.facebook.react.tests.createProject -import com.facebook.react.utils.ProjectUtils.getReactNativeArchitectures -import com.facebook.react.utils.ProjectUtils.isHermesEnabled -import com.facebook.react.utils.ProjectUtils.isNewArchEnabled -import com.facebook.react.utils.ProjectUtils.needsCodegenFromPackageJson -import java.io.File -import org.junit.Assert.* -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TemporaryFolder - -class ProjectUtilsTest { - - @get:Rule val tempFolder = TemporaryFolder() - - @Test - fun isNewArchEnabled_returnsFalseByDefault() { - assertFalse(createProject().isNewArchEnabled) - } - - @Test - fun isNewArchEnabled_withDisabled_returnsFalse() { - val project = createProject() - project.extensions.extraProperties.set("newArchEnabled", "false") - assertFalse(project.isNewArchEnabled) - } - - @Test - fun isNewArchEnabled_withEnabled_returnsTrue() { - val project = createProject() - project.extensions.extraProperties.set("newArchEnabled", "true") - assertTrue(project.isNewArchEnabled) - } - - @Test - fun isNewArchEnabled_withInvalid_returnsFalse() { - val project = createProject() - project.extensions.extraProperties.set("newArchEnabled", "¯\\_(ツ)_/¯") - assertFalse(project.isNewArchEnabled) - } - - @Test - fun isHermesEnabled_returnsTrueByDefault() { - assertTrue(createProject().isHermesEnabled) - } - - @Test - fun isNewArchEnabled_withDisabledViaProperty_returnsFalse() { - val project = createProject() - project.extensions.extraProperties.set("hermesEnabled", "false") - assertFalse(project.isHermesEnabled) - } - - @Test - fun isHermesEnabled_withEnabledViaProperty_returnsTrue() { - val project = createProject() - project.extensions.extraProperties.set("hermesEnabled", "true") - assertTrue(project.isHermesEnabled) - } - - @Test - fun isHermesEnabled_withInvalidViaProperty_returnsTrue() { - val project = createProject() - project.extensions.extraProperties.set("hermesEnabled", "¯\\_(ツ)_/¯") - assertTrue(project.isHermesEnabled) - } - - @Test - fun isHermesEnabled_withDisabledViaExt_returnsFalse() { - val project = createProject() - val extMap = mapOf("enableHermes" to false) - project.extensions.extraProperties.set("react", extMap) - assertFalse(project.isHermesEnabled) - } - - @Test - fun isHermesEnabled_withEnabledViaExt_returnsTrue() { - val project = createProject() - val extMap = mapOf("enableHermes" to true) - project.extensions.extraProperties.set("react", extMap) - assertTrue(project.isHermesEnabled) - } - - @Test - fun isHermesEnabled_withDisabledViaExtAsString_returnsFalse() { - val project = createProject() - val extMap = mapOf("enableHermes" to "false") - project.extensions.extraProperties.set("react", extMap) - assertFalse(project.isHermesEnabled) - } - - @Test - fun isHermesEnabled_withInvalidViaExt_returnsTrue() { - val project = createProject() - val extMap = mapOf("enableHermes" to "¯\\_(ツ)_/¯") - project.extensions.extraProperties.set("react", extMap) - assertTrue(project.isHermesEnabled) - } - - @Test - fun needsCodegenFromPackageJson_withCodegenConfigInPackageJson_returnsTrue() { - val project = createProject() - val extension = TestReactExtension(project) - File(tempFolder.root, "package.json").apply { - writeText( - // language=json - """ - { - "name": "a-library", - "codegenConfig": {} - } - """ - .trimIndent()) - } - extension.root.set(tempFolder.root) - assertTrue(project.needsCodegenFromPackageJson(extension.root)) - } - - @Test - fun needsCodegenFromPackageJson_withMissingCodegenConfigInPackageJson_returnsFalse() { - val project = createProject() - val extension = TestReactExtension(project) - File(tempFolder.root, "package.json").apply { - writeText( - // language=json - """ - { - "name": "a-library" - } - """ - .trimIndent()) - } - extension.root.set(tempFolder.root) - assertFalse(project.needsCodegenFromPackageJson(extension.root)) - } - - @Test - fun needsCodegenFromPackageJson_withCodegenConfigInModel_returnsTrue() { - val project = createProject() - val model = ModelPackageJson(ModelCodegenConfig(null, null, null, null)) - - assertTrue(project.needsCodegenFromPackageJson(model)) - } - - @Test - fun needsCodegenFromPackageJson_withMissingCodegenConfigInModel_returnsFalse() { - val project = createProject() - val model = ModelPackageJson(null) - - assertFalse(project.needsCodegenFromPackageJson(model)) - } - - @Test - fun needsCodegenFromPackageJson_withMissingPackageJson_returnsFalse() { - val project = createProject() - val extension = TestReactExtension(project) - - assertFalse(project.needsCodegenFromPackageJson(extension.root)) - } - - @Test - fun getReactNativeArchitectures_withMissingProperty_returnsEmptyList() { - val project = createProject() - assertTrue(project.getReactNativeArchitectures().isEmpty()) - } - - @Test - fun getReactNativeArchitectures_withEmptyProperty_returnsEmptyList() { - val project = createProject() - project.extensions.extraProperties.set("reactNativeArchitectures", "") - assertTrue(project.getReactNativeArchitectures().isEmpty()) - } - - @Test - fun getReactNativeArchitectures_withSingleArch_returnsSingleton() { - val project = createProject() - project.extensions.extraProperties.set("reactNativeArchitectures", "x86") - - val archs = project.getReactNativeArchitectures() - assertEquals(1, archs.size) - assertEquals("x86", archs[0]) - } - - @Test - fun getReactNativeArchitectures_withMultipleArch_returnsList() { - val project = createProject() - project.extensions.extraProperties.set( - "reactNativeArchitectures", "armeabi-v7a,arm64-v8a,x86,x86_64") - - val archs = project.getReactNativeArchitectures() - assertEquals(4, archs.size) - assertEquals("armeabi-v7a", archs[0]) - assertEquals("arm64-v8a", archs[1]) - assertEquals("x86", archs[2]) - assertEquals("x86_64", archs[3]) - } -} diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/TaskUtilsTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/TaskUtilsTest.kt deleted file mode 100644 index cafbba6f7afd..000000000000 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/TaskUtilsTest.kt +++ /dev/null @@ -1,77 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.utils - -import com.facebook.react.tests.OS -import com.facebook.react.tests.OsRule -import com.facebook.react.tests.WithOs -import org.junit.Assert.assertEquals -import org.junit.Assert.assertTrue -import org.junit.Rule -import org.junit.Test - -class TaskUtilsTest { - - @get:Rule val osRule = OsRule() - - @Test - fun windowsAwareCommandLine_withEmptyInput_isEmpty() { - assertTrue(windowsAwareCommandLine().isEmpty()) - } - - @Test - fun windowsAwareCommandLine_withList_isEqualAsVararg() { - assertEquals( - windowsAwareCommandLine(listOf("a", "b", "c")), windowsAwareCommandLine("a", "b", "c")) - } - - @Test - @WithOs(OS.MAC) - fun windowsAwareCommandLine_onMac_returnsTheList() { - assertEquals(listOf("a", "b", "c"), windowsAwareCommandLine("a", "b", "c")) - } - - @Test - @WithOs(OS.LINUX) - fun windowsAwareCommandLine_onLinux_returnsTheList() { - assertEquals(listOf("a", "b", "c"), windowsAwareCommandLine("a", "b", "c")) - } - - @Test - @WithOs(OS.WIN) - fun windowsAwareCommandLine_onWindows_prependsCmd() { - assertEquals(listOf("cmd", "/c", "a", "b", "c"), windowsAwareCommandLine("a", "b", "c")) - } - - @Test - @WithOs(OS.MAC) - fun windowsAwareBashCommandLine_onMac_returnsTheList() { - assertEquals( - listOf("a", "b", "c"), windowsAwareBashCommandLine("a", "b", "c", bashWindowsHome = "abc")) - } - - @Test - @WithOs(OS.LINUX) - fun windowsAwareBashCommandLine_onLinux_returnsTheList() { - assertEquals(listOf("a", "b", "c"), windowsAwareBashCommandLine("a", "b", "c")) - } - - @Test - @WithOs(OS.WIN) - fun windowsAwareBashCommandLine_onWindows_prependsBash() { - assertEquals(listOf("bash", "-c", "a", "b", "c"), windowsAwareBashCommandLine("a", "b", "c")) - } - - @Test - @WithOs(OS.WIN) - fun windowsAwareBashCommandLine_onWindows_prependsCustomBashPath() { - assertEquals( - listOf("/custom/bash", "-c", "a", "b", "c"), - windowsAwareBashCommandLine("a", "b", "c", bashWindowsHome = "/custom/bash")) - } -} diff --git a/packages/rn-tester/.eslintrc b/packages/rn-tester/.eslintrc deleted file mode 100644 index 9fd335839360..000000000000 --- a/packages/rn-tester/.eslintrc +++ /dev/null @@ -1,5 +0,0 @@ -{ - "rules": { - "react-native/no-inline-styles": 0 - } -} diff --git a/packages/rn-tester/.xcode.env b/packages/rn-tester/.xcode.env deleted file mode 100644 index 3d5782c71568..000000000000 --- a/packages/rn-tester/.xcode.env +++ /dev/null @@ -1,11 +0,0 @@ -# This `.xcode.env` file is versioned and is used to source the environment -# used when running script phases inside Xcode. -# To customize your local environment, you can create an `.xcode.env.local` -# file that is not versioned. - -# NODE_BINARY variable contains the PATH to the node executable. -# -# Customize the NODE_BINARY variable here. -# For example, to use nvm with brew, add the following line -# . "$(brew --prefix nvm)/nvm.sh" --no-use -export NODE_BINARY=$(command -v node) diff --git a/packages/rn-tester/BUCK b/packages/rn-tester/BUCK deleted file mode 100644 index dae1544ba4ed..000000000000 --- a/packages/rn-tester/BUCK +++ /dev/null @@ -1,348 +0,0 @@ -load("@fbsource//tools/build_defs:glob_defs.bzl", "subdir_glob") -load("@fbsource//xplat/hermes/defs:hermes.bzl", "HERMES_BYTECODE_VERSION") -load("//tools/build_defs:fb_native_wrapper.bzl", "fb_native") -load("//tools/build_defs:fb_xplat_platform_specific_rule.bzl", "fb_xplat_platform_specific_rule") -load("//tools/build_defs:fb_xplat_resource.bzl", "fb_xplat_resource") -load("//tools/build_defs/apple:fb_apple_asset_catalog.bzl", "fb_apple_asset_catalog") -load("//tools/build_defs/apple:fb_apple_bundle.bzl", "fb_apple_bundle") -load("//tools/build_defs/apple:fb_apple_test.bzl", "fb_apple_test") -load("//tools/build_defs/apple:fb_js_dep.bzl", "rn_js_bundle_dep") -load("//tools/build_defs/apple:flag_defs.bzl", "get_objc_arc_preprocessor_flags", "get_preprocessor_flags_for_build_mode") -load("//tools/build_defs/oss:metro_defs.bzl", "rn_library") -load( - "//tools/build_defs/oss:rn_defs.bzl", - "ANDROID", - "APPLE", - "YOGA_APPLE_TARGET", - "js_library_glob", - "make_resource_glob", - "react_fabric_component_plugin_provider", - "react_module_plugin_providers", - "rn_apple_library", - "rn_extra_build_flags", - "rn_xplat_cxx_library2", -) -load("//tools/build_defs/third_party:yarn_defs.bzl", "yarn_workspace") - -yarn_workspace( - name = "yarn-workspace", - srcs = glob( - ["**/*.js"], - exclude = [ - "**/__fixtures__/**", - "**/__flowtests__/**", - "**/__mocks__/**", - "**/__server_snapshot_tests__/**", - "**/__tests__/**", - "**/node_modules/**", - "**/node_modules/.bin/**", - "**/.*", - "**/.*/**", - "**/.*/.*", - "**/*.xcodeproj/**", - "**/*.xcworkspace/**", - ], - ), - visibility = ["PUBLIC"], -) - -rn_library( - name = "rn-tester", - srcs = js_library_glob( - [ - "js", - "NativeCxxModuleExample", - "NativeModuleExample", - "NativeComponentExample", - "RCTTest", - ], - excludes = [ - "**/__*__/**", - "**/*.md", - "js/examples/WebSocket/http_test_server.js", - "js/examples/WebSocket/websocket_test_server.js", - ], - ), - codegen_components = True, - codegen_modules = True, - labels = [ - "pfh:ReactNative_CommonInfrastructurePlaceholder", - ], - native_component_spec_name = "AppSpecs", - native_module_android_package_name = "com.facebook.fbreact.specs", - native_module_spec_name = "AppSpecs", - skip_processors = True, - visibility = ["PUBLIC"], - deps = [ - "//xplat/js:node_modules__nullthrows", - "//xplat/js/RKJSModules/Libraries/Core:Core", - "//xplat/js/RKJSModules/vendor/react:react", - "//xplat/js/react-native-github:react-native", - "//xplat/js/react-native-github/packages/assets:assets", - ], -) - -fb_native.filegroup( - name = "nativecomponent-srcs", - srcs = glob( - [ - "**/*NativeComponent.js", - ], - exclude = [ - "NativeComponentExample/**/*", - ], - ), - visibility = ["PUBLIC"], -) - -REACT_CORE_OSS_DEPS = [ - "//xplat/js/react-native-github:ReactInternalApple", - "//xplat/js/react-native-github:RCTPushNotificationApple", - "//xplat/js/react-native-github:RCTLinkingApple", - "//xplat/js/react-native-github:RCTAnimationApple", - "//xplat/js/react-native-github:RCTImageApple", - "//xplat/js/react-native-github:RCTNetworkApple", - "//xplat/js/react-native-github:RCTTextApple", - "//xplat/js/react-native-github:RCTBlobApple", -] - -fb_xplat_resource( - name = "RNTesterUnitTestsResources", - dirs = [], - files = [ - "RNTesterUnitTests/RNTesterUnitTestsBundle.js", - ], - platforms = APPLE, - visibility = [ - "//fbobjc/Libraries/FBReactKit:", - ], -) - -fb_apple_test( - name = "RNTesterUnitTests", - srcs = glob( - [ - "RNTesterUnitTests/**/*.m", - ], - ), - headers = glob([ - "RNTesterUnitTests/**/*.h", - ]), - contacts = ["oncall+react_native@xmail.facebook.com"], - frameworks = [ - "$PLATFORM_DIR/Developer/Library/Frameworks/XCTest.framework", - "CoreGraphics", - "Foundation", - "QuartzCore", - "UIKit", - ], - preprocessor_flags = get_objc_arc_preprocessor_flags() + [ - "-DHERMES_BYTECODE_VERSION={}".format(HERMES_BYTECODE_VERSION), - ] + get_preprocessor_flags_for_build_mode(), - visibility = [ - "//fbobjc/Libraries/FBReactKit:workspace", - ], - deps = REACT_CORE_OSS_DEPS + [ - "//xplat/js/react-native-github:RCTCxxBridgeApple", - ":RCTTestApple", - ":RNTesterUnitTestsResourcesApple", - "//fbobjc/VendorLib/OCMock:OCMock", - ], -) - -fb_xplat_resource( - name = "RNTesterIntegrationTestsResources", - files = make_resource_glob("RNTesterIntegrationTests"), - platforms = APPLE, - visibility = [ - "//fbobjc/Libraries/FBReactKit:", - ], -) - -fb_apple_test( - name = "RNTesterIntegrationTests", - autoglob = True, - contacts = ["oncall+react_native@xmail.facebook.com"], - frameworks = [ - "$PLATFORM_DIR/Developer/Library/Frameworks/XCTest.framework", - "CoreGraphics", - "Foundation", - "QuartzCore", - "UIKit", - ], - info_plist = "//xplat/configurations/buck/common_info_plists:ApplicationTest-Info.plist", - preprocessor_flags = get_objc_arc_preprocessor_flags() + get_preprocessor_flags_for_build_mode(), - test_host_app = "//fbobjc/Configurations/Buck/CommonTestHost:CommonTestHost", - visibility = [ - "//fbobjc/Libraries/FBReactKit:workspace", - ], - deps = REACT_CORE_OSS_DEPS + [ - ":RCTTestApple", - ":RNTesterIntegrationTestsResourcesApple", - ":RNTesterResourcesApple", - "//xplat/js/react-native-github:RCTCxxBridgeApple", - "//xplat/js/react-native-github/React/CoreModules:CoreModulesApple", - rn_js_bundle_dep("//xplat/js/RKJSModules/EntryPoints:RNTesterTestBundle"), - ], -) - -fb_xplat_platform_specific_rule( - name = "RNTesterBundleAssetCatalog", - dirs = ["RNTester/RNTesterBundle/OtherImages.xcassets"], - platform = APPLE, - rule = fb_apple_asset_catalog, - visibility = [ - "//fbobjc/Libraries/FBReactKit:", - ], -) - -fb_xplat_resource( - name = "RNTesterBundleResources", - dirs = [], - files = [ - "RNTester/RNTesterBundle/ImageInBundle.png", - ], - platforms = APPLE, - visibility = [ - "//fbobjc/Libraries/FBReactKit:", - ], -) - -rn_xplat_cxx_library2( - name = "RNTesterBundleBinary", - srcs = ["//xplat/configurations/buck/apple/common_files:dummy.c"], - deps = [":RNTesterBundleAssetCatalog"], -) - -fb_apple_bundle( - name = "RNTesterBundle", - binary = ":RNTesterBundleBinaryApple#static", - extension = "bundle", - info_plist = "RNTester/RNTesterBundle/Info.plist", - info_plist_substitutions = { - "PRODUCT_BUNDLE_IDENTIFIER": "com.facebook.react.RNTesterBundle", - }, - deps = [ - ":RNTesterBundleResourcesApple", - ], -) - -fb_xplat_platform_specific_rule( - name = "RNTesterAssetCatalog", - dirs = ["RNTester/Images.xcassets"], - platform = APPLE, - rule = fb_apple_asset_catalog, - visibility = [ - "//fbobjc/Libraries/FBReactKit:", - ], -) - -fb_xplat_resource( - name = "RNTesterResources", - dirs = [], - files = [ - "RNTester/legacy_image@2x.png", - "RNTester/LaunchScreen.storyboard", - ":RNTesterBundle", - ], - platforms = APPLE, - visibility = [ - "//fbobjc/Libraries/FBReactKit:", - ], -) - -rn_apple_library( - name = "RCTTestApple", - srcs = glob([ - "RCTTest/**/*.m", - "RCTTest/**/*.mm", - ]), - headers = glob([ - "RCTTest/**/*.h", - ]), - exported_headers = { - "RCTTest/RCTTestRunner.h": "RCTTest/RCTTestRunner.h", - }, - autoglob = False, - frameworks = [ - "XCTest", - ], - header_path_prefix = "React", - labels = [ - "disable_plugins_only_validation", - ], - plugins = react_module_plugin_providers( - name = "TestModule", - native_class_func = "RCTTestModuleCls", - ), - plugins_header = "FBRCTTestPlugins.h", - preprocessor_flags = get_objc_arc_preprocessor_flags() + get_preprocessor_flags_for_build_mode() + rn_extra_build_flags() + [ - "-DRN_DISABLE_OSS_PLUGIN_HEADER", - ], - visibility = ["PUBLIC"], - deps = [ - "//xplat/js/react-native-github:RCTLinkingApple", - "//xplat/js/react-native-github:RCTPushNotificationApple", - "//xplat/js/react-native-github:ReactInternalApple", - "//xplat/js/react-native-github/React/CoreModules:CoreModulesApple", - YOGA_APPLE_TARGET, - ], -) - -rn_xplat_cxx_library2( - name = "NativeComponentExample", - plugins_only = True, - srcs = glob( - [ - "NativeComponentExample/ios/*.m", - "NativeComponentExample/ios/*.mm", - ], - ), - headers = glob( - [ - "NativeComponentExample/ios/*.h", - ], - ), - header_namespace = "", - compiler_flags = [ - "-fexceptions", - "-frtti", - "-std=c++17", - "-Wall", - ], - contacts = ["oncall+react_native@xmail.facebook.com"], - labels = [ - "pfh:ReactNative_CommonInfrastructurePlaceholder", - ], - plugins = [ - react_fabric_component_plugin_provider("RNTMyNativeView", "RNTMyNativeViewCls"), - ], - plugins_header = "RCTFabricComponentsPlugins.h", - reexport_all_header_dependencies = False, - visibility = ["PUBLIC"], - deps = [ - ":generated_components-AppSpecs", - "//xplat/js/react-native-github:RCTFabricComponentViewsBase", - ], -) - -rn_xplat_cxx_library2( - name = "NativeCxxModuleExample", - srcs = glob(["NativeCxxModuleExample/*.cpp"]), - header_namespace = "", - exported_headers = subdir_glob( - [ - ("NativeCxxModuleExample", "*.h"), - ], - prefix = "NativeCxxModuleExample", - ), - fbandroid_compiler_flags = [ - "-fexceptions", - "-frtti", - ], - platforms = (ANDROID, APPLE), - visibility = ["PUBLIC"], - deps = [ - ":AppSpecsJSI", - ], -) diff --git a/packages/rn-tester/Gemfile b/packages/rn-tester/Gemfile deleted file mode 100644 index 7bb000655cb6..000000000000 --- a/packages/rn-tester/Gemfile +++ /dev/null @@ -1,5 +0,0 @@ -# Gemfile -source 'https://rubygems.org' - -gem 'cocoapods', '= 1.11.3' -gem 'rexml' diff --git a/packages/rn-tester/NativeComponentExample/MyNativeView.podspec b/packages/rn-tester/NativeComponentExample/MyNativeView.podspec deleted file mode 100644 index 3368c3e47c0c..000000000000 --- a/packages/rn-tester/NativeComponentExample/MyNativeView.podspec +++ /dev/null @@ -1,41 +0,0 @@ -# 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. - -require "json" - -package = JSON.parse(File.read(File.join(__dir__, "../" "package.json"))) - -boost_version = '1.76.0' -boost_compiler_flags = '-Wno-documentation' - -Pod::Spec.new do |s| - s.name = "MyNativeView" - s.version = package["version"] - s.summary = package["description"] - s.description = "my-native-view" - s.homepage = "https://github.com/sota000/my-native-view.git" - s.license = "MIT" - s.platforms = { :ios => "12.4" } - s.compiler_flags = boost_compiler_flags + ' -Wno-nullability-completeness' - s.author = "Facebook, Inc. and its affiliates" - s.source = { :git => "https://github.com/facebook/my-native-view.git", :tag => "#{s.version}" } - s.pod_target_xcconfig = { - "HEADER_SEARCH_PATHS" => "\"$(PODS_ROOT)/RCT-Folly\" \"$(PODS_ROOT)/boost\" \"${PODS_CONFIGURATION_BUILD_DIR}/React-Codegen/React_Codegen.framework/Headers\"", - "CLANG_CXX_LANGUAGE_STANDARD" => "c++17" - } - - s.source_files = "ios/**/*.{h,m,mm,cpp}" - s.requires_arc = true - - install_modules_dependencies(s) - - # Enable codegen for this library - use_react_native_codegen!(s, { - :library_name => "MyNativeViewSpec", - :react_native_path => "../../../", - :js_srcs_dir => "./js", - :library_type => "components" - }) -end diff --git a/packages/rn-tester/NativeComponentExample/ios/RNTMyNativeViewComponentView.h b/packages/rn-tester/NativeComponentExample/ios/RNTMyNativeViewComponentView.h deleted file mode 100644 index 6d7adce1eabb..000000000000 --- a/packages/rn-tester/NativeComponentExample/ios/RNTMyNativeViewComponentView.h +++ /dev/null @@ -1,19 +0,0 @@ -/* - * 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. - */ - -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@interface RNTMyNativeViewComponentView : RCTViewComponentView - -- (UIColor *)UIColorFromHexString:(const std::string)hexString; - -@end - -NS_ASSUME_NONNULL_END diff --git a/packages/rn-tester/NativeComponentExample/ios/RNTMyNativeViewComponentView.mm b/packages/rn-tester/NativeComponentExample/ios/RNTMyNativeViewComponentView.mm deleted file mode 100644 index 7fe66d4050d7..000000000000 --- a/packages/rn-tester/NativeComponentExample/ios/RNTMyNativeViewComponentView.mm +++ /dev/null @@ -1,88 +0,0 @@ -/* - * 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. - */ - -#import "RNTMyNativeViewComponentView.h" - -#import -#import -#import -#import - -#import "RCTFabricComponentsPlugins.h" - -using namespace facebook::react; - -@interface RNTMyNativeViewComponentView () -@end - -@implementation RNTMyNativeViewComponentView { - UIView *_view; -} - -+ (ComponentDescriptorProvider)componentDescriptorProvider -{ - return concreteComponentDescriptorProvider(); -} - -- (instancetype)initWithFrame:(CGRect)frame -{ - if (self = [super initWithFrame:frame]) { - static const auto defaultProps = std::make_shared(); - _props = defaultProps; - - _view = [[UIView alloc] init]; - _view.backgroundColor = [UIColor redColor]; - - self.contentView = _view; - } - - return self; -} - -- (UIColor *)UIColorFromHexString:(const std::string)hexString -{ - unsigned rgbValue = 0; - NSString *colorString = [NSString stringWithCString:hexString.c_str() encoding:[NSString defaultCStringEncoding]]; - NSScanner *scanner = [NSScanner scannerWithString:colorString]; - [scanner setScanLocation:1]; // bypass '#' character - [scanner scanHexInt:&rgbValue]; - return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16) / 255.0 - green:((rgbValue & 0xFF00) >> 8) / 255.0 - blue:(rgbValue & 0xFF) / 255.0 - alpha:1.0]; -} - -- (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const &)oldProps -{ - [super updateProps:props oldProps:oldProps]; -} - -- (void)onChange:(UIView *)sender -{ - // No-op - // std::dynamic_pointer_cast(_eventEmitter) - // ->onChange(ViewEventEmitter::OnChange{.value = static_cast(sender.on)}); -} - -#pragma mark - Native Commands - -- (void)handleCommand:(const NSString *)commandName args:(const NSArray *)args -{ - RCTRNTMyNativeViewHandleCommand(self, commandName, args); -} - -- (void)callNativeMethodToChangeBackgroundColor:(NSString *)colorString -{ - UIColor *color = [self UIColorFromHexString:std::string([colorString UTF8String])]; - _view.backgroundColor = color; -} -@end - -Class RNTMyNativeViewCls(void) -{ - return RNTMyNativeViewComponentView.class; -} diff --git a/packages/rn-tester/NativeComponentExample/ios/RNTMyNativeViewManager.mm b/packages/rn-tester/NativeComponentExample/ios/RNTMyNativeViewManager.mm deleted file mode 100644 index 83d8f231d425..000000000000 --- a/packages/rn-tester/NativeComponentExample/ios/RNTMyNativeViewManager.mm +++ /dev/null @@ -1,49 +0,0 @@ -/* - * 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. - */ - -#import -#import -#import - -@interface RNTMyNativeViewManager : RCTViewManager -@end - -@implementation RNTMyNativeViewManager - -RCT_EXPORT_MODULE(RNTMyNativeView) - -RCT_EXPORT_VIEW_PROPERTY(backgroundColor, UIColor) - -RCT_EXPORT_METHOD(callNativeMethodToChangeBackgroundColor : (nonnull NSNumber *)reactTag color : (NSString *)color) -{ - [self.bridge.uiManager addUIBlock:^(RCTUIManager *uiManager, NSDictionary *viewRegistry) { - UIView *view = viewRegistry[reactTag]; - if (!view || ![view isKindOfClass:[UIView class]]) { - RCTLogError(@"Cannot find NativeView with tag #%@", reactTag); - return; - } - - unsigned rgbValue = 0; - NSString *colorString = [NSString stringWithCString:std::string([color UTF8String]).c_str() - encoding:[NSString defaultCStringEncoding]]; - NSScanner *scanner = [NSScanner scannerWithString:colorString]; - [scanner setScanLocation:1]; // bypass '#' character - [scanner scanHexInt:&rgbValue]; - - view.backgroundColor = [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16) / 255.0 - green:((rgbValue & 0xFF00) >> 8) / 255.0 - blue:(rgbValue & 0xFF) / 255.0 - alpha:1.0]; - }]; -} - -- (UIView *)view -{ - return [[UIView alloc] init]; -} - -@end diff --git a/packages/rn-tester/NativeComponentExample/js/MyNativeView.js b/packages/rn-tester/NativeComponentExample/js/MyNativeView.js deleted file mode 100644 index 373e6d22f856..000000000000 --- a/packages/rn-tester/NativeComponentExample/js/MyNativeView.js +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -import * as React from 'react'; -import {useRef, useState} from 'react'; -import {View, Button} from 'react-native'; -import RNTMyNativeView, { - Commands as RNTMyNativeViewCommands, -} from './MyNativeViewNativeComponent'; -import type {MyNativeViewType} from './MyNativeViewNativeComponent'; - -const colors = [ - '#0000FF', - '#FF0000', - '#00FF00', - '#003300', - '#330000', - '#000033', -]; - -// This is an example component that migrates to use the new architecture. -export default function MyNativeView(props: {}): React.Node { - const ref = useRef | null>(null); - const [opacity, setOpacity] = useState(1.0); - return ( - - - - - - diff --git a/packages/rn-tester/js/assets/party.png b/packages/rn-tester/js/assets/party.png deleted file mode 100644 index 4b02aadddd73..000000000000 Binary files a/packages/rn-tester/js/assets/party.png and /dev/null differ diff --git a/packages/rn-tester/js/assets/poke.png b/packages/rn-tester/js/assets/poke.png deleted file mode 100644 index a5c138ee97e5..000000000000 Binary files a/packages/rn-tester/js/assets/poke.png and /dev/null differ diff --git a/packages/rn-tester/js/assets/relay@3x.png b/packages/rn-tester/js/assets/relay@3x.png deleted file mode 100644 index 59a4386a6f4e..000000000000 Binary files a/packages/rn-tester/js/assets/relay@3x.png and /dev/null differ diff --git a/packages/rn-tester/js/assets/search-icon.png b/packages/rn-tester/js/assets/search-icon.png deleted file mode 100644 index ac8e5eb99a82..000000000000 Binary files a/packages/rn-tester/js/assets/search-icon.png and /dev/null differ diff --git a/packages/rn-tester/js/assets/slider-left.png b/packages/rn-tester/js/assets/slider-left.png deleted file mode 100644 index dff4e11e19d6..000000000000 Binary files a/packages/rn-tester/js/assets/slider-left.png and /dev/null differ diff --git a/packages/rn-tester/js/assets/slider-left@2x.png b/packages/rn-tester/js/assets/slider-left@2x.png deleted file mode 100644 index 83c6dd8204eb..000000000000 Binary files a/packages/rn-tester/js/assets/slider-left@2x.png and /dev/null differ diff --git a/packages/rn-tester/js/assets/slider-right.png b/packages/rn-tester/js/assets/slider-right.png deleted file mode 100644 index 57e8c7d3fe56..000000000000 Binary files a/packages/rn-tester/js/assets/slider-right.png and /dev/null differ diff --git a/packages/rn-tester/js/assets/slider-right@2x.png b/packages/rn-tester/js/assets/slider-right@2x.png deleted file mode 100644 index 8546ba8c9446..000000000000 Binary files a/packages/rn-tester/js/assets/slider-right@2x.png and /dev/null differ diff --git a/packages/rn-tester/js/assets/slider.png b/packages/rn-tester/js/assets/slider.png deleted file mode 100644 index 9141991010c9..000000000000 Binary files a/packages/rn-tester/js/assets/slider.png and /dev/null differ diff --git a/packages/rn-tester/js/assets/slider@2x.png b/packages/rn-tester/js/assets/slider@2x.png deleted file mode 100644 index 396614fa9b9b..000000000000 Binary files a/packages/rn-tester/js/assets/slider@2x.png and /dev/null differ diff --git a/packages/rn-tester/js/assets/superlike.png b/packages/rn-tester/js/assets/superlike.png deleted file mode 100644 index b0f9c8541518..000000000000 Binary files a/packages/rn-tester/js/assets/superlike.png and /dev/null differ diff --git a/packages/rn-tester/js/assets/trees.jpg b/packages/rn-tester/js/assets/trees.jpg deleted file mode 100644 index 3d628783b783..000000000000 Binary files a/packages/rn-tester/js/assets/trees.jpg and /dev/null differ diff --git a/packages/rn-tester/js/assets/tumblr_mfqekpMktw1rn90umo1_500.gif b/packages/rn-tester/js/assets/tumblr_mfqekpMktw1rn90umo1_500.gif deleted file mode 100644 index 3e945c8c207d..000000000000 Binary files a/packages/rn-tester/js/assets/tumblr_mfqekpMktw1rn90umo1_500.gif and /dev/null differ diff --git a/packages/rn-tester/js/assets/uie_comment_highlighted@2x.png b/packages/rn-tester/js/assets/uie_comment_highlighted@2x.png deleted file mode 100644 index b33726757ed4..000000000000 Binary files a/packages/rn-tester/js/assets/uie_comment_highlighted@2x.png and /dev/null differ diff --git a/packages/rn-tester/js/assets/uie_comment_normal@2x.png b/packages/rn-tester/js/assets/uie_comment_normal@2x.png deleted file mode 100644 index 6491689fbbc8..000000000000 Binary files a/packages/rn-tester/js/assets/uie_comment_normal@2x.png and /dev/null differ diff --git a/packages/rn-tester/js/assets/uie_thumb_big.png b/packages/rn-tester/js/assets/uie_thumb_big.png deleted file mode 100644 index dbfdb1b9b2e4..000000000000 Binary files a/packages/rn-tester/js/assets/uie_thumb_big.png and /dev/null differ diff --git a/packages/rn-tester/js/assets/uie_thumb_normal@2x.png b/packages/rn-tester/js/assets/uie_thumb_normal@2x.png deleted file mode 100644 index 72683dfac123..000000000000 Binary files a/packages/rn-tester/js/assets/uie_thumb_normal@2x.png and /dev/null differ diff --git a/packages/rn-tester/js/assets/uie_thumb_selected@2x.png b/packages/rn-tester/js/assets/uie_thumb_selected@2x.png deleted file mode 100644 index 79eb69cf92b3..000000000000 Binary files a/packages/rn-tester/js/assets/uie_thumb_selected@2x.png and /dev/null differ diff --git a/packages/rn-tester/js/assets/victory.png b/packages/rn-tester/js/assets/victory.png deleted file mode 100644 index e13ed5c4769c..000000000000 Binary files a/packages/rn-tester/js/assets/victory.png and /dev/null differ diff --git a/packages/rn-tester/js/components/ListExampleShared.js b/packages/rn-tester/js/components/ListExampleShared.js deleted file mode 100644 index 1acad0e6f5a5..000000000000 --- a/packages/rn-tester/js/components/ListExampleShared.js +++ /dev/null @@ -1,371 +0,0 @@ -/** - * 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 - * @flow - */ - -'use strict'; - -const React = require('react'); - -const { - Animated, - Image, - Platform, - TouchableHighlight, - StyleSheet, - Switch, - Text, - TextInput, - View, -} = require('react-native'); - -export type Item = { - title: string, - text: string, - key: string, - pressed: boolean, - noImage?: ?boolean, - ... -}; - -function genItemData(count: number, start: number = 0): Array { - const dataBlob = []; - for (let ii = start; ii < count + start; ii++) { - const itemHash = Math.abs(hashCode('Item ' + ii)); - dataBlob.push({ - title: 'Item ' + ii, - text: LOREM_IPSUM.substr(0, (itemHash % 301) + 20), - key: String(ii), - pressed: false, - }); - } - return dataBlob; -} - -const HORIZ_WIDTH = 200; -const ITEM_HEIGHT = 72; - -class ItemComponent extends React.PureComponent<{ - fixedHeight?: ?boolean, - horizontal?: ?boolean, - item: Item, - onPress: (key: string) => void, - onShowUnderlay?: () => void, - onHideUnderlay?: () => void, - textSelectable?: ?boolean, - ... -}> { - _onPress = () => { - this.props.onPress(this.props.item.key); - }; - render(): React.Node { - const {fixedHeight, horizontal, item, textSelectable} = this.props; - const itemHash = Math.abs(hashCode(item.title)); - const imgSource = THUMB_URLS[itemHash % THUMB_URLS.length]; - return ( - - - {!item.noImage && } - - {item.title} - {item.text} - - - - ); - } -} - -const renderStackedItem = ({item}: {item: Item, ...}): React.Node => { - const itemHash = Math.abs(hashCode(item.title)); - const imgSource = THUMB_URLS[itemHash % THUMB_URLS.length]; - return ( - - - {item.title} - {item.text} - - - - ); -}; - -class FooterComponent extends React.PureComponent<{...}> { - render(): React.Node { - return ( - - - - LIST FOOTER - - - ); - } -} - -class HeaderComponent extends React.PureComponent<{...}> { - render(): React.Node { - return ( - - - LIST HEADER - - - - ); - } -} - -class ListEmptyComponent extends React.PureComponent<{...}> { - render(): React.Node { - return ( - - The list is empty :o - - ); - } -} - -class SeparatorComponent extends React.PureComponent<{...}> { - render(): React.Node { - return ; - } -} - -class ItemSeparatorComponent extends React.PureComponent<$FlowFixMeProps> { - render(): React.Node { - const style = this.props.highlighted - ? [ - styles.itemSeparator, - {marginLeft: 0, backgroundColor: 'rgb(217, 217, 217)'}, - ] - : styles.itemSeparator; - return ; - } -} - -class Spindicator extends React.PureComponent<$FlowFixMeProps> { - render(): React.Node { - return ( - - ); - } -} - -const THUMB_URLS = [ - require('../assets/like.png'), - require('../assets/dislike.png'), - require('../assets/call.png'), - require('../assets/fist.png'), - require('../assets/bandaged.png'), - require('../assets/flowers.png'), - require('../assets/heart.png'), - require('../assets/liking.png'), - require('../assets/party.png'), - require('../assets/poke.png'), - require('../assets/superlike.png'), - require('../assets/victory.png'), -]; - -const LOREM_IPSUM = - 'Lorem ipsum dolor sit amet, ius ad pertinax oportere accommodare, an vix \ -civibus corrumpit referrentur. Te nam case ludus inciderint, te mea facilisi adipiscing. Sea id \ -integre luptatum. In tota sale consequuntur nec. Erat ocurreret mei ei. Eu paulo sapientem \ -vulputate est, vel an accusam intellegam interesset. Nam eu stet pericula reprimique, ea vim illud \ -modus, putant invidunt reprehendunt ne qui.'; - -/* eslint no-bitwise: 0 */ -function hashCode(str: string): number { - let hash = 15; - for (let ii = str.length - 1; ii >= 0; ii--) { - hash = (hash << 5) - hash + str.charCodeAt(ii); - } - return hash; -} - -const HEADER = {height: 30, width: 100}; -const SEPARATOR_HEIGHT = StyleSheet.hairlineWidth; - -function getItemLayout( - data: any, - index: number, - horizontal?: boolean, -): {|index: number, length: number, offset: number|} { - const [length, separator, header] = horizontal - ? [HORIZ_WIDTH, 0, HEADER.width] - : [ITEM_HEIGHT, SEPARATOR_HEIGHT, HEADER.height]; - return {length, offset: (length + separator) * index + header, index}; -} - -function pressItem(item: Item): Item { - const title = `Item ${item.key}${!item.pressed ? ' (pressed)' : ''}`; - return {...item, title, pressed: !item.pressed}; -} - -function renderSmallSwitchOption( - label: string, - value: boolean, - setValue: boolean => void, -): null | React.Node { - if (Platform.isTV) { - return null; - } - return ( - - {label}: - - - ); -} - -function PlainInput(props: Object): React.Node { - return ( - - ); -} - -const styles = StyleSheet.create({ - headerFooter: { - ...HEADER, - alignSelf: 'center', - alignItems: 'center', - justifyContent: 'center', - }, - headerFooterContainer: { - backgroundColor: 'rgb(239, 239, 244)', - }, - listEmpty: { - alignItems: 'center', - justifyContent: 'center', - flexGrow: 1, - }, - horizItem: { - alignSelf: 'flex-start', // Necessary for touch highlight - }, - item: { - flex: 1, - }, - itemSeparator: { - height: SEPARATOR_HEIGHT, - backgroundColor: 'rgb(200, 199, 204)', - marginLeft: 60, - }, - option: { - flexDirection: 'row', - padding: 8, - paddingRight: 0, - }, - row: { - flexDirection: 'row', - padding: 10, - backgroundColor: 'white', - }, - searchTextInput: { - backgroundColor: 'white', - borderColor: '#cccccc', - borderRadius: 3, - borderWidth: 1, - paddingLeft: 8, - paddingVertical: 0, - height: 26, - fontSize: 14, - flexGrow: 1, - }, - separator: { - height: SEPARATOR_HEIGHT, - backgroundColor: 'rgb(200, 199, 204)', - }, - smallSwitch: Platform.select({ - android: { - top: 1, - margin: -6, - transform: [{scale: 0.7}], - }, - ios: { - top: 4, - margin: -10, - transform: [{scale: 0.5}], - }, - }), - stacked: { - alignItems: 'center', - backgroundColor: 'white', - padding: 10, - }, - thumb: { - width: 50, - height: 50, - left: -5, - }, - spindicator: { - marginLeft: 'auto', - marginTop: 8, - width: 2, - height: 16, - backgroundColor: 'darkgray', - }, - stackedText: { - padding: 4, - fontSize: 18, - }, - text: { - flex: 1, - }, -}); - -module.exports = { - FooterComponent, - HeaderComponent, - ListEmptyComponent, - ItemComponent, - ItemSeparatorComponent, - PlainInput, - SeparatorComponent, - Spindicator, - genItemData, - getItemLayout, - pressItem, - renderSmallSwitchOption, - renderStackedItem, -}; diff --git a/packages/rn-tester/js/components/RNTConfigurationBlock.js b/packages/rn-tester/js/components/RNTConfigurationBlock.js deleted file mode 100644 index 25ebe6ce51fd..000000000000 --- a/packages/rn-tester/js/components/RNTConfigurationBlock.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -import * as React from 'react'; -import {StyleSheet, View} from 'react-native'; -import {RNTesterThemeContext} from './RNTesterTheme'; - -type Props = $ReadOnly<{| - children?: ?React.Node, - testID?: string, -|}>; - -/** - * Container view for a block of configuration options for an example. - */ -export default function RNTConfigurationBlock(props: Props): React.Node { - const theme = React.useContext(RNTesterThemeContext); - return ( - - {props.children} - - ); -} - -const styles = StyleSheet.create({ - container: { - paddingVertical: 6, - paddingHorizontal: 10, - borderBottomWidth: 1, - }, -}); diff --git a/packages/rn-tester/js/components/RNTOption.js b/packages/rn-tester/js/components/RNTOption.js deleted file mode 100644 index 98993c4247df..000000000000 --- a/packages/rn-tester/js/components/RNTOption.js +++ /dev/null @@ -1,88 +0,0 @@ -/** - * 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 - * @flow strict-local - */ - -'use strict'; - -import * as React from 'react'; -import {Text, Pressable, StyleSheet, View} from 'react-native'; -import type {PressEvent} from 'react-native/Libraries/Types/CoreEventTypes'; -import type {ViewStyleProp} from 'react-native/Libraries/StyleSheet/StyleSheet'; -import {RNTesterThemeContext} from './RNTesterTheme'; - -type Props = $ReadOnly<{| - testID?: ?string, - label: string, - onPress?: ?(event: PressEvent) => mixed, - selected?: ?boolean, - multiSelect?: ?boolean, - disabled?: ?boolean, - style?: ViewStyleProp, -|}>; - -/** - * A reusable toggle button component for RNTester. Highlights when selected. - */ -export default function RNTOption(props: Props): React.Node { - const [pressed, setPressed] = React.useState(false); - const theme = React.useContext(RNTesterThemeContext); - - return ( - setPressed(true)} - onPressOut={() => setPressed(false)} - testID={props.testID}> - - {props.label} - - - ); -} - -const styles = StyleSheet.create({ - pressed: { - backgroundColor: 'rgba(100,215,255,.3)', - }, - label: { - color: 'black', - }, - selected: { - backgroundColor: 'rgba(100,215,255,.3)', - borderColor: 'rgba(100,215,255,.3)', - }, - disabled: {borderWidth: 0}, - container: { - borderColor: 'rgba(0,0,0, 0.1)', - borderWidth: 1, - borderRadius: 16, - padding: 6, - paddingHorizontal: 10, - alignItems: 'center', - }, -}); diff --git a/packages/rn-tester/js/components/RNTPressableRow.js b/packages/rn-tester/js/components/RNTPressableRow.js deleted file mode 100644 index 805b7c57fd1d..000000000000 --- a/packages/rn-tester/js/components/RNTPressableRow.js +++ /dev/null @@ -1,96 +0,0 @@ -/** - * 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 - * @flow - */ - -import * as React from 'react'; -import {RNTesterThemeContext} from './RNTesterTheme'; -import RNTesterComponentTitle from './RNTesterComponentTitle'; - -import {Platform, StyleSheet, Pressable, Text, View} from 'react-native'; - -type ViewStyleProp = $ElementType, 'style'>; -type Props = { - accessibilityLabel?: ?string, - testID?: ?string, - onPressIn?: ?() => mixed, - onPressOut?: ?() => mixed, - rightAddOn?: ?React.Node, - bottomAddOn?: ?React.Node, - children?: ?React.Node, - title: string, - description?: ?string, - onPress: () => mixed, - style?: ViewStyleProp | ((pressed: boolean) => ViewStyleProp), -}; - -export default function RNTPressableRow({ - onPressIn, - onPressOut, - title, - description, - rightAddOn, - bottomAddOn, - onPress, - style, - accessibilityLabel, -}: Props): React.Node { - const theme = React.useContext(RNTesterThemeContext); - const label = accessibilityLabel ?? `${title} ${description ?? ''}`; - return ( - [ - styles.row, - typeof style === 'function' ? style(pressed) : style, - pressed - ? {backgroundColor: theme.SecondarySystemFillColor} - : {backgroundColor: theme.SecondaryGroupedBackgroundColor}, - ]} - onPress={onPress}> - - {title} - {rightAddOn} - - - {description} - - {bottomAddOn} - - ); -} - -const styles = StyleSheet.create({ - row: { - justifyContent: 'center', - paddingHorizontal: 15, - paddingVertical: 12, - marginVertical: Platform.select({ios: 4, android: 8}), - marginHorizontal: 15, - overflow: 'hidden', - elevation: 5, - backgroundColor: Platform.select({ios: '#FFFFFF', android: '#F3F8FF'}), - }, - descriptionText: { - fontSize: 12, - lineHeight: 20, - marginBottom: 5, - }, - pressed: { - elevation: 3, - }, - topRowStyle: { - flexDirection: 'row', - justifyContent: 'space-between', - flex: 1, - }, -}); diff --git a/packages/rn-tester/js/components/RNTTestDetails.js b/packages/rn-tester/js/components/RNTTestDetails.js deleted file mode 100644 index 1a64dca9ef45..000000000000 --- a/packages/rn-tester/js/components/RNTTestDetails.js +++ /dev/null @@ -1,100 +0,0 @@ -/** - * 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 - * @flow strict-local - */ - -import * as React from 'react'; -import {View, Text, StyleSheet, Button, Platform} from 'react-native'; -import {type RNTesterTheme} from './RNTesterTheme'; - -function RNTTestDetails({ - description, - expect, - title, - theme, -}: { - description?: string, - expect?: string, - title: string, - theme: RNTesterTheme, -}): React.Node { - const [collapsed, setCollapsed] = React.useState(false); - - const content = ( - <> - {description == null ? null : ( - - Description - {description} - - )} - {expect == null ? null : ( - - Expectation - {expect} - - )} - - ); - return ( - - - - {title} - - {content != null && ( -