-
Notifications
You must be signed in to change notification settings - Fork 24.3k
/
parsers-commons.js
1401 lines (1269 loc) · 36.4 KB
/
parsers-commons.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (c) Meta Platforms, Inc. 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 {
EventTypeAnnotation,
EventTypeShape,
NamedShape,
NativeModuleAliasMap,
NativeModuleBaseTypeAnnotation,
NativeModuleEnumMap,
NativeModuleEventEmitterShape,
NativeModuleFunctionTypeAnnotation,
NativeModuleParamTypeAnnotation,
NativeModulePropertyShape,
NativeModuleSchema,
NativeModuleTypeAnnotation,
Nullable,
ObjectTypeAnnotation,
OptionsShape,
PropTypeAnnotation,
SchemaType,
} from '../CodegenSchema.js';
import type {ParserType} from './errors';
import type {Parser} from './parser';
import type {ComponentSchemaBuilderConfig} from './schema.js';
import type {
ParserErrorCapturer,
PropAST,
TypeDeclarationMap,
TypeResolutionStatus,
} from './utils';
const {
throwIfConfigNotfound,
throwIfEventEmitterEventTypeIsUnsupported,
throwIfEventEmitterTypeIsUnsupported,
throwIfIncorrectModuleRegistryCallArgument,
throwIfIncorrectModuleRegistryCallTypeParameterParserError,
throwIfModuleInterfaceIsMisnamed,
throwIfModuleInterfaceNotFound,
throwIfModuleTypeIsUnsupported,
throwIfMoreThanOneCodegenNativecommands,
throwIfMoreThanOneConfig,
throwIfMoreThanOneModuleInterfaceParserError,
throwIfMoreThanOneModuleRegistryCalls,
throwIfPropertyValueTypeIsUnsupported,
throwIfTypeAliasIsNotInterface,
throwIfUnsupportedFunctionParamTypeAnnotationParserError,
throwIfUnsupportedFunctionReturnTypeAnnotationParserError,
throwIfUntypedModule,
throwIfUnusedModuleInterfaceParserError,
throwIfWrongNumberOfCallExpressionArgs,
} = require('./error-utils');
const {
MissingTypeParameterGenericParserError,
MoreThanOneTypeParameterGenericParserError,
UnnamedFunctionParamParserError,
UnsupportedObjectDirectRecursivePropertyParserError,
} = require('./errors');
const {
createParserErrorCapturer,
extractNativeModuleName,
getConfigType,
getSortedObject,
isModuleRegistryCall,
verifyPlatforms,
visit,
} = require('./utils');
const invariant = require('invariant');
export type CommandOptions = $ReadOnly<{
supportedCommands: $ReadOnlyArray<string>,
}>;
// $FlowFixMe[unclear-type] TODO(T108222691): Use flow-types for @babel/parser
type OptionsAST = Object;
type ExtendedPropResult = {
type: 'ReactNativeBuiltInType',
knownTypeName: 'ReactNativeCoreViewProps',
} | null;
export type EventArgumentReturnType = {
argumentProps: ?$ReadOnlyArray<$FlowFixMe>,
paperTopLevelNameDeprecated: ?$FlowFixMe,
bubblingType: ?'direct' | 'bubble',
};
function wrapModuleSchema(
nativeModuleSchema: NativeModuleSchema,
hasteModuleName: string,
): SchemaType {
return {
modules: {
[hasteModuleName]: nativeModuleSchema,
},
};
}
// $FlowFixMe[unsupported-variance-annotation]
function unwrapNullable<+T: NativeModuleTypeAnnotation>(
x: Nullable<T>,
): [T, boolean] {
if (x.type === 'NullableTypeAnnotation') {
return [x.typeAnnotation, true];
}
return [x, false];
}
// $FlowFixMe[unsupported-variance-annotation]
function wrapNullable<+T: NativeModuleTypeAnnotation>(
nullable: boolean,
typeAnnotation: T,
): Nullable<T> {
if (!nullable) {
return typeAnnotation;
}
return {
type: 'NullableTypeAnnotation',
typeAnnotation,
};
}
function assertGenericTypeAnnotationHasExactlyOneTypeParameter(
moduleName: string,
/**
* TODO(T108222691): Use flow-types for @babel/parser
*/
typeAnnotation: $FlowFixMe,
parser: Parser,
) {
if (typeAnnotation.typeParameters == null) {
throw new MissingTypeParameterGenericParserError(
moduleName,
typeAnnotation,
parser,
);
}
const typeAnnotationType = parser.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,
parser,
);
}
}
function isObjectProperty(property: $FlowFixMe, language: ParserType): boolean {
switch (language) {
case 'Flow':
return property.type === 'ObjectTypeProperty';
case 'TypeScript':
return property.type === 'TSPropertySignature';
default:
return false;
}
}
function getObjectTypeAnnotations(
hasteModuleName: string,
types: TypeDeclarationMap,
tryParse: ParserErrorCapturer,
translateTypeAnnotation: $FlowFixMe,
parser: Parser,
): {...NativeModuleAliasMap} {
const aliasMap: {...NativeModuleAliasMap} = {};
Object.entries(types).forEach(([key, value]) => {
const isTypeAlias =
value.type === 'TypeAlias' || value.type === 'TSTypeAliasDeclaration';
if (!isTypeAlias) {
return;
}
const parent = parser.nextNodeForTypeAlias(value);
if (
parent.type !== 'ObjectTypeAnnotation' &&
parent.type !== 'TSTypeLiteral'
) {
return;
}
const typeProperties = parser
.getAnnotatedElementProperties(value)
.map(prop =>
parseObjectProperty(
parent,
prop,
hasteModuleName,
types,
aliasMap,
{}, // enumMap
tryParse,
true, // cxxOnly
prop?.optional || false,
translateTypeAnnotation,
parser,
),
);
aliasMap[key] = {
type: 'ObjectTypeAnnotation',
properties: typeProperties,
};
});
return aliasMap;
}
function parseObjectProperty(
parentObject?: $FlowFixMe,
property: $FlowFixMe,
hasteModuleName: string,
types: TypeDeclarationMap,
aliasMap: {...NativeModuleAliasMap},
enumMap: {...NativeModuleEnumMap},
tryParse: ParserErrorCapturer,
cxxOnly: boolean,
nullable: boolean,
translateTypeAnnotation: $FlowFixMe,
parser: Parser,
): NamedShape<Nullable<NativeModuleBaseTypeAnnotation>> {
const language = parser.language();
const name = parser.getKeyName(property, hasteModuleName);
const {optional = false} = property;
const languageTypeAnnotation =
language === 'TypeScript'
? property.typeAnnotation.typeAnnotation
: property.value;
// Handle recursive types
if (parentObject) {
const propertyType = parser.getResolveTypeAnnotationFN()(
languageTypeAnnotation,
types,
parser,
);
if (
propertyType.typeResolutionStatus.successful === true &&
propertyType.typeResolutionStatus.type === 'alias' &&
(language === 'TypeScript'
? parentObject.typeName &&
parentObject.typeName.name === languageTypeAnnotation.typeName?.name
: parentObject.id &&
parentObject.id.name === languageTypeAnnotation.id?.name)
) {
if (!optional) {
throw new UnsupportedObjectDirectRecursivePropertyParserError(
name,
languageTypeAnnotation,
hasteModuleName,
);
}
return {
name,
optional,
typeAnnotation: {
type: 'TypeAliasTypeAnnotation',
name: propertyType.typeResolutionStatus.name,
},
};
}
}
// Handle non-recursive types
const [propertyTypeAnnotation, isPropertyNullable] =
unwrapNullable<$FlowFixMe>(
translateTypeAnnotation(
hasteModuleName,
languageTypeAnnotation,
types,
aliasMap,
enumMap,
tryParse,
cxxOnly,
parser,
),
);
if (
(propertyTypeAnnotation.type === 'FunctionTypeAnnotation' && !cxxOnly) ||
propertyTypeAnnotation.type === 'PromiseTypeAnnotation' ||
propertyTypeAnnotation.type === 'VoidTypeAnnotation'
) {
throwIfPropertyValueTypeIsUnsupported(
hasteModuleName,
languageTypeAnnotation,
property.key,
propertyTypeAnnotation.type,
);
}
return {
name,
optional,
typeAnnotation: wrapNullable(isPropertyNullable, propertyTypeAnnotation),
};
}
function translateFunctionTypeAnnotation(
hasteModuleName: string,
// TODO(T108222691): Use flow-types for @babel/parser
// TODO(T71778680): This is a FunctionTypeAnnotation. Type this.
functionTypeAnnotation: $FlowFixMe,
types: TypeDeclarationMap,
aliasMap: {...NativeModuleAliasMap},
enumMap: {...NativeModuleEnumMap},
tryParse: ParserErrorCapturer,
cxxOnly: boolean,
translateTypeAnnotation: $FlowFixMe,
parser: Parser,
): NativeModuleFunctionTypeAnnotation {
type Param = NamedShape<Nullable<NativeModuleParamTypeAnnotation>>;
const params: Array<Param> = [];
for (const param of parser.getFunctionTypeAnnotationParameters(
functionTypeAnnotation,
)) {
const parsedParam = tryParse(() => {
if (parser.getFunctionNameFromParameter(param) == null) {
throw new UnnamedFunctionParamParserError(param, hasteModuleName);
}
const paramName = parser.getParameterName(param);
const [paramTypeAnnotation, isParamTypeAnnotationNullable] =
unwrapNullable<$FlowFixMe>(
translateTypeAnnotation(
hasteModuleName,
parser.getParameterTypeAnnotation(param),
types,
aliasMap,
enumMap,
tryParse,
cxxOnly,
parser,
),
);
if (
paramTypeAnnotation.type === 'VoidTypeAnnotation' ||
paramTypeAnnotation.type === 'PromiseTypeAnnotation'
) {
return throwIfUnsupportedFunctionParamTypeAnnotationParserError(
hasteModuleName,
param.typeAnnotation,
paramName,
paramTypeAnnotation.type,
);
}
return {
name: paramName,
optional: Boolean(param.optional),
typeAnnotation: wrapNullable(
isParamTypeAnnotationNullable,
paramTypeAnnotation,
),
};
});
if (parsedParam != null) {
params.push(parsedParam);
}
}
const [returnTypeAnnotation, isReturnTypeAnnotationNullable] =
unwrapNullable<$FlowFixMe>(
translateTypeAnnotation(
hasteModuleName,
parser.getFunctionTypeAnnotationReturnType(functionTypeAnnotation),
types,
aliasMap,
enumMap,
tryParse,
cxxOnly,
parser,
),
);
throwIfUnsupportedFunctionReturnTypeAnnotationParserError(
hasteModuleName,
functionTypeAnnotation,
'FunctionTypeAnnotation',
cxxOnly,
returnTypeAnnotation.type,
);
return {
type: 'FunctionTypeAnnotation',
returnTypeAnnotation: wrapNullable(
isReturnTypeAnnotationNullable,
returnTypeAnnotation,
),
params,
};
}
function buildPropertySchema(
hasteModuleName: string,
// TODO(T108222691): [TS] Use flow-types for @babel/parser
// TODO(T71778680): [Flow] 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},
enumMap: {...NativeModuleEnumMap},
tryParse: ParserErrorCapturer,
cxxOnly: boolean,
translateTypeAnnotation: $FlowFixMe,
parser: Parser,
): NativeModulePropertyShape {
let nullable: boolean = false;
let {key, value} = property;
const methodName: string = key.name;
if (parser.language() === 'TypeScript') {
value =
property.type === 'TSMethodSignature'
? property
: property.typeAnnotation;
}
const resolveTypeAnnotationFN = parser.getResolveTypeAnnotationFN();
({nullable, typeAnnotation: value} = resolveTypeAnnotationFN(
value,
types,
parser,
));
throwIfModuleTypeIsUnsupported(
hasteModuleName,
property.value,
key.name,
value.type,
parser,
);
return {
name: methodName,
optional: Boolean(property.optional),
typeAnnotation: wrapNullable(
nullable,
translateFunctionTypeAnnotation(
hasteModuleName,
value,
types,
aliasMap,
enumMap,
tryParse,
cxxOnly,
translateTypeAnnotation,
parser,
),
),
};
}
function buildEventEmitterSchema(
hasteModuleName: string,
// TODO(T108222691): [TS] Use flow-types for @babel/parser
// TODO(T71778680): [Flow] 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},
enumMap: {...NativeModuleEnumMap},
tryParse: ParserErrorCapturer,
cxxOnly: boolean,
translateTypeAnnotation: $FlowFixMe,
parser: Parser,
): NativeModuleEventEmitterShape {
const {key} = property;
const value =
parser.language() === 'TypeScript'
? property.typeAnnotation.typeAnnotation
: property.value;
const eventemitterName: string = key.name;
const resolveTypeAnnotationFN = parser.getResolveTypeAnnotationFN();
const [typeAnnotation, typeAnnotationNullable] = unwrapNullable(value);
const typeAnnotationUntyped =
value.typeParameters.params.length === 1 &&
parser.language() === 'TypeScript'
? value.typeParameters.params[0].type === 'TSTypeLiteral' &&
value.typeParameters.params[0].members.length === 0
: value.typeParameters.params[0].type === 'ObjectTypeAnnotation' &&
value.typeParameters.params[0].properties.length === 0;
throwIfEventEmitterTypeIsUnsupported(
hasteModuleName,
key.name,
typeAnnotation.type,
parser,
typeAnnotationNullable,
typeAnnotationUntyped,
);
const eventTypeResolutionStatus = resolveTypeAnnotationFN(
typeAnnotation.typeParameters.params[0],
types,
parser,
);
throwIfEventEmitterEventTypeIsUnsupported(
hasteModuleName,
key.name,
eventTypeResolutionStatus.typeAnnotation,
parser,
eventTypeResolutionStatus.nullable,
);
const eventTypeAnnotation = translateTypeAnnotation(
hasteModuleName,
typeAnnotation.typeParameters.params[0],
types,
aliasMap,
enumMap,
tryParse,
cxxOnly,
parser,
);
return {
name: eventemitterName,
optional: false,
typeAnnotation: {
type: 'EventEmitterTypeAnnotation',
typeAnnotation: eventTypeAnnotation,
},
};
}
function buildSchemaFromConfigType(
configType: 'module' | 'component' | 'none',
filename: ?string,
ast: $FlowFixMe,
wrapComponentSchema: (config: ComponentSchemaBuilderConfig) => SchemaType,
buildComponentSchema: (
ast: $FlowFixMe,
parser: Parser,
) => ComponentSchemaBuilderConfig,
buildModuleSchema: (
hasteModuleName: string,
ast: $FlowFixMe,
tryParse: ParserErrorCapturer,
parser: Parser,
translateTypeAnnotation: $FlowFixMe,
) => NativeModuleSchema,
parser: Parser,
translateTypeAnnotation: $FlowFixMe,
): SchemaType {
switch (configType) {
case 'component': {
return wrapComponentSchema(buildComponentSchema(ast, parser));
}
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,
parser,
translateTypeAnnotation,
),
);
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 buildSchema(
contents: string,
filename: ?string,
wrapComponentSchema: (config: ComponentSchemaBuilderConfig) => SchemaType,
buildComponentSchema: (
ast: $FlowFixMe,
parser: Parser,
) => ComponentSchemaBuilderConfig,
buildModuleSchema: (
hasteModuleName: string,
ast: $FlowFixMe,
tryParse: ParserErrorCapturer,
parser: Parser,
translateTypeAnnotation: $FlowFixMe,
) => NativeModuleSchema,
Visitor: ({isComponent: boolean, isModule: boolean}) => {
[type: string]: (node: $FlowFixMe) => void,
},
parser: Parser,
translateTypeAnnotation: $FlowFixMe,
): SchemaType {
// Early return for non-Spec JavaScript files
if (
!contents.includes('codegenNativeComponent') &&
!contents.includes('TurboModule')
) {
return {modules: {}};
}
const ast = parser.getAst(contents, filename);
const configType = getConfigType(ast, Visitor);
return buildSchemaFromConfigType(
configType,
filename,
ast,
wrapComponentSchema,
buildComponentSchema,
buildModuleSchema,
parser,
translateTypeAnnotation,
);
}
function createComponentConfig(
foundConfig: $FlowFixMe,
commandsTypeNames: $FlowFixMe,
): $FlowFixMe {
return {
...foundConfig,
commandTypeName:
commandsTypeNames[0] == null
? null
: commandsTypeNames[0].commandTypeName,
commandOptionsExpression:
commandsTypeNames[0] == null
? null
: commandsTypeNames[0].commandOptionsExpression,
};
}
const parseModuleName = (
hasteModuleName: string,
moduleSpec: $FlowFixMe,
ast: $FlowFixMe,
parser: Parser,
): string => {
const callExpressions = [];
visit(ast, {
CallExpression(node) {
if (isModuleRegistryCall(node)) {
callExpressions.push(node);
}
},
});
throwIfUnusedModuleInterfaceParserError(
hasteModuleName,
moduleSpec,
callExpressions,
);
throwIfMoreThanOneModuleRegistryCalls(
hasteModuleName,
callExpressions,
callExpressions.length,
);
const [callExpression] = callExpressions;
const typeParameters = parser.callExpressionTypeParameters(callExpression);
const methodName = callExpression.callee.property.name;
throwIfWrongNumberOfCallExpressionArgs(
hasteModuleName,
callExpression,
methodName,
callExpression.arguments.length,
);
throwIfIncorrectModuleRegistryCallArgument(
hasteModuleName,
callExpression.arguments[0],
methodName,
);
const $moduleName = callExpression.arguments[0].value;
throwIfUntypedModule(
typeParameters,
hasteModuleName,
callExpression,
methodName,
$moduleName,
);
throwIfIncorrectModuleRegistryCallTypeParameterParserError(
hasteModuleName,
typeParameters,
methodName,
$moduleName,
parser,
);
return $moduleName;
};
const buildModuleSchema = (
hasteModuleName: string,
/**
* TODO(T71778680): Flow-type this node.
*/
ast: $FlowFixMe,
tryParse: ParserErrorCapturer,
parser: Parser,
translateTypeAnnotation: $FlowFixMe,
): NativeModuleSchema => {
const language = parser.language();
const types = parser.getTypes(ast);
const moduleSpecs = (Object.values(types): $ReadOnlyArray<$FlowFixMe>).filter(
t => parser.isModuleInterface(t),
);
throwIfModuleInterfaceNotFound(
moduleSpecs.length,
hasteModuleName,
ast,
language,
);
throwIfMoreThanOneModuleInterfaceParserError(
hasteModuleName,
moduleSpecs,
language,
);
const [moduleSpec] = moduleSpecs;
throwIfModuleInterfaceIsMisnamed(hasteModuleName, moduleSpec.id, language);
// Parse Module Name
const moduleName = parseModuleName(hasteModuleName, moduleSpec, ast, parser);
// 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,
moduleName,
);
const aliasMap: {...NativeModuleAliasMap} = cxxOnly
? getObjectTypeAnnotations(
hasteModuleName,
types,
tryParse,
translateTypeAnnotation,
parser,
)
: {};
const properties: $ReadOnlyArray<$FlowFixMe> =
language === 'Flow' ? moduleSpec.body.properties : moduleSpec.body.body;
type PropertyShape =
| {type: 'eventEmitter', value: NativeModuleEventEmitterShape}
| {type: 'method', value: NativeModulePropertyShape};
// $FlowFixMe[missing-type-arg]
const nativeModuleSchema = properties
.filter(
property =>
property.type === 'ObjectTypeProperty' ||
property.type === 'TSPropertySignature' ||
property.type === 'TSMethodSignature',
)
.map<?{
aliasMap: NativeModuleAliasMap,
enumMap: NativeModuleEnumMap,
propertyShape: PropertyShape,
}>(property => {
const enumMap: {...NativeModuleEnumMap} = {};
const isEventEmitter =
language === 'TypeScript'
? property?.type === 'TSPropertySignature' &&
property?.typeAnnotation?.typeAnnotation?.typeName?.name ===
'EventEmitter'
: property?.value?.type === 'GenericTypeAnnotation' &&
property?.value?.id?.name === 'EventEmitter';
return tryParse(() => ({
aliasMap,
enumMap,
propertyShape: isEventEmitter
? {
type: 'eventEmitter',
value: buildEventEmitterSchema(
hasteModuleName,
property,
types,
aliasMap,
enumMap,
tryParse,
cxxOnly,
translateTypeAnnotation,
parser,
),
}
: {
type: 'method',
value: buildPropertySchema(
hasteModuleName,
property,
types,
aliasMap,
enumMap,
tryParse,
cxxOnly,
translateTypeAnnotation,
parser,
),
},
}));
})
.filter(Boolean)
.reduce(
(moduleSchema: NativeModuleSchema, {enumMap, propertyShape}) => ({
type: 'NativeModule',
aliasMap: {...moduleSchema.aliasMap, ...aliasMap},
enumMap: {...moduleSchema.enumMap, ...enumMap},
spec: {
eventEmitters: [...moduleSchema.spec.eventEmitters].concat(
propertyShape.type === 'eventEmitter' ? [propertyShape.value] : [],
),
methods: [...moduleSchema.spec.methods].concat(
propertyShape.type === 'method' ? [propertyShape.value] : [],
),
},
moduleName: moduleSchema.moduleName,
excludedPlatforms: moduleSchema.excludedPlatforms,
}),
{
type: 'NativeModule',
aliasMap: {},
enumMap: {},
spec: {eventEmitters: [], methods: []},
moduleName,
excludedPlatforms:
excludedPlatforms.length !== 0 ? [...excludedPlatforms] : undefined,
},
);
return {
type: 'NativeModule',
aliasMap: getSortedObject(nativeModuleSchema.aliasMap),
enumMap: getSortedObject(nativeModuleSchema.enumMap),
spec: {
eventEmitters: nativeModuleSchema.spec.eventEmitters.sort(),
methods: nativeModuleSchema.spec.methods.sort(),
},
moduleName,
excludedPlatforms: nativeModuleSchema.excludedPlatforms,
};
};
/**
* This function is used to find the type of a native component
* provided the default exports statement from generated AST.
* @param statement The statement to be parsed.
* @param foundConfigs The 'mutable' array of configs that have been found.
* @param parser The language parser to be used.
* @returns void
*/
function findNativeComponentType(
statement: $FlowFixMe,
foundConfigs: Array<{[string]: string}>,
parser: Parser,
): void {
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.type === 'AsExpression' ||
declaration.type === 'TypeCastExpression'
) {
declaration = declaration.expression;
}
try {
if (declaration.callee.name === 'codegenNativeComponent') {
const typeArgumentParams =
parser.getTypeArgumentParamsFromDeclaration(declaration);
const funcArgumentParams = declaration.arguments;
const nativeComponentType: {[string]: string} =
parser.getNativeComponentType(typeArgumentParams, funcArgumentParams);
if (funcArgumentParams.length > 1) {
nativeComponentType.optionsExpression = funcArgumentParams[1];
}
foundConfigs.push(nativeComponentType);
}
} catch (e) {
// ignore
}
}
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;