/
overrides.ts
574 lines (562 loc) · 17.6 KB
/
overrides.ts
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
import { OverridesVisitor } from "../../../packages/flow2dts/src/transform/applyOverridesVisitors"
import template from "@babel/template"
import { types as t } from "@babel/core"
import { NodePath, Scope, Visitor } from "@babel/traverse"
const ast = template({
plugins: ["typescript"],
}).ast
function isReactImportSpecifier(scope: Scope, id: t.Identifier) {
const declarationPath = scope.getBinding(id.name)!.path
if (t.isImportDeclaration(declarationPath.parent)) {
if (declarationPath.parent.source.value === "react") {
return true
}
}
return false
}
/**
* Flow code tends to use `void` as the type of the `state` instance property,
* however the React DT typings do not allow that. In reality React sets it to
* `null` at runtime, but the DT typings of React don't allow that either, it
* defaults to `{}` istead. So here we simply replace `void` with `{}`.
*
* TODO: Currently only handling PureComponent
*/
function noVoidForReactComponentState(path: NodePath<t.DeclareClass>) {
const superclass = path.node.extends![0]
if (superclass) {
const id = superclass.id as any
const typeParameters = superclass.typeParameters as any
if (
t.isTSQualifiedName(id) &&
t.isIdentifier(id.left) &&
isReactImportSpecifier(path.scope, id.left) &&
t.isTSTypeParameterInstantiation(typeParameters)
) {
if (id.right.name === "PureComponent") {
const stateType = typeParameters.params[1]
if (t.isTSVoidKeyword(stateType)) {
// TODO: In reality this is `null`, but DT React types default to `{}`
typeParameters.params[1] = t.tsTypeLiteral([])
}
}
}
}
}
// `HostComponent<unknown>` does not satisfy some of the React DT typings, so change it to `HostComponent<{}>`.
// TODO: Unsure if this should ideally still be `unknown`.
function removeUnknownFromHostComponent(path: NodePath<t.TSTypeReference>) {
const id = path.node.typeName
if (
t.isIdentifier(id) &&
id.name === "HostComponent" &&
t.isTSTypeParameterInstantiation(path.node.typeParameters) &&
t.isTSUnknownKeyword(path.node.typeParameters.params[0])
) {
path.node.typeParameters.params[0] = t.tsTypeLiteral([])
}
}
const animatedVisitors: OverridesVisitor[] = [
// Override exported components with those taken from DT
[
"Libraries/Animated/src/Animated.d.ts",
{
Program: {
exit(path) {
const exportDeclaration = ast`
export * from "../../../TypeScriptSupplementals/Animated"
` as t.ExportDeclaration
path.unshiftContainer("body", [exportDeclaration])
},
},
},
],
[
"Libraries/Animated/src/Animated.d.ts",
{
Identifier: {
exit(path) {
if (path.node.name.startsWith("$f2d_")) {
const parentPath =
path.findParent((p) => p.isVariableDeclaration()) || path.findParent((p) => p.isExportSpecifier())
if (parentPath) {
parentPath.remove()
}
}
},
},
},
],
// Export all of the AnimatedMock ES6 exports, so those and the ES6 exports of Animated can be...
[
"Libraries/Animated/src/Animated.d.ts",
{
Program: {
exit(path) {
const exportDeclaration = ast`
export * from "./AnimatedMock"
` as t.ExportDeclaration
path.unshiftContainer("body", [exportDeclaration])
},
},
},
],
// ...imported as a namespace
[
"index.d.ts",
{
ImportDefaultSpecifier: {
exit(path) {
if (path.node.local.name === "Animated$f2tTypeof") {
path.replaceWith(t.importNamespaceSpecifier(path.node.local))
}
},
},
},
],
[
"Libraries/Animated/src/AnimatedImplementation.d.ts",
{
ImportDeclaration: {
exit(path) {
if (path.node.source.value === "./AnimatedEvent") {
path.node.specifiers = path.node.specifiers.map((specifier) =>
t.isImportDefaultSpecifier(specifier) ? t.importNamespaceSpecifier(specifier.local) : specifier
)
}
},
},
},
],
]
// TODO: These are specifically to get the Artsy app green
// and should be removed when it is done by the hinting work.
//
// Doing this so we don't forget to update the other visitor that refers to this var
const AnimatedInterpolationName = "Interpolation"
const AnimatedNodeName = "Node"
const listsVisitor: Visitor = {
TSTypeAliasDeclaration: {
exit(path) {
if (path.node.id.name === "Props") {
path.node.typeParameters!.params[0]!.constraint = t.tsTypeReference(
t.identifier("SectionBase"),
t.tsTypeParameterInstantiation([t.tsAnyKeyword()])
)
path.skip()
}
},
},
}
const listsVisitors: OverridesVisitor[] = [
["Libraries/Lists/SectionList.d.ts", listsVisitor],
["Libraries/Lists/VirtualizedSectionList.d.ts", listsVisitor],
]
const logboxVisitor: Visitor = {
TSTypeReference: {
exit(path) {
if (t.isIdentifier(path.node.typeName)) {
if (path.node.typeName.name === "LogBoxLog") {
path.replaceWith(t.tsTypeQuery(t.identifier("LogBoxLog")))
path.skip()
}
}
},
},
}
const logboxVisitors: OverridesVisitor[] = [
["Libraries/LogBox/LogBoxInspectorContainer.d.ts", logboxVisitor],
["Libraries/LogBox/UI/LogBoxInspectorReactFrames.d.ts", logboxVisitor],
["Libraries/LogBox/UI/LogBoxInspectorStackFrames.d.ts", logboxVisitor],
]
const visitors: OverridesVisitor[] = [
...animatedVisitors,
...listsVisitors,
...logboxVisitors,
[
"**/*",
{
// TODO: We should convert DeclareClass, which is a Flow type, to ClassDeclaration.
DeclareClass: {
exit(path) {
noVoidForReactComponentState(path)
},
},
},
],
[
"**/*",
{
TSTypeReference: {
exit(path) {
removeUnknownFromHostComponent(path)
},
},
},
],
[
"**/*",
{
// Remove all propTypes typings. They are hard to get right, don't add any value to type-consumers, and are deprecated to boot.
TSPropertySignature: {
exit(path) {
if (t.isIdentifier(path.node.key) && path.node.key.name === "propTypes") {
path.remove()
}
},
},
},
],
[
"index.d.ts",
{
Program: {
exit(path) {
// These deprecated DT types are defined in a separate file for ease of external contribution.
path.pushContainer("body", ast`export * from "./TypeScriptSupplementals"` as t.Statement[])
},
},
},
],
// This happens due to removing propTypes in Text.d.ts, so we resolve it manually
[
"Libraries/DeprecatedPropTypes/DeprecatedTextInputPropTypes.d.ts",
{
ImportDeclaration: {
exit(path) {
if (path.node.source.value === "flow2dts-flow-types-polyfill") {
path.node.specifiers.push(t.importSpecifier(t.identifier("ReactPropsCheckType"), t.identifier("ReactPropsCheckType")))
}
}
},
TSTypeQuery: {
exit(path) {
if (path.node.exprName.type === "TSQualifiedName" && path.node.exprName.left.type === "TSQualifiedName") {
if (path.node.exprName.right.name === "style" && path.node.exprName.left.right.name === "propTypes") {
path.replaceWith(t.tsTypeReference(t.identifier("ReactPropsCheckType")))
}
}
}
},
}
],
// TODO: This could probably move upstream, as `Element` is slightly more restrictive than `Node`.
[
"Libraries/Components/TextInput/TextInput.d.ts",
{
TSDeclareFunction: {
exit(path) {
if (t.isIdentifier(path.node.id) && path.node.id.name === "InternalTextInput") {
const returnType = path.node.returnType
t.assertTSTypeAnnotation(returnType)
t.assertTSTypeReference(returnType.typeAnnotation)
const typeAnnotation = returnType.typeAnnotation
t.assertTSQualifiedName(typeAnnotation.typeName)
typeAnnotation.typeName.right = t.identifier("Element")
typeAnnotation.typeParameters = t.tsTypeParameterInstantiation([t.tsTypeReference(t.identifier("Props"))])
}
},
},
},
],
[
"Libraries/Components/TextInput/TextInputNativeCommands.d.ts",
{
TSInterfaceDeclaration: {
exit(path) {
if (path.node.id.name === "TextInputNativeCommands") {
const replacementDeclaration = ast`
interface TextInputNativeCommands<
T extends
| React.ForwardRefExoticComponent<any>
| { new (props: any): React.Component<any> }
| ((props: any, context?: any) => React.ReactElement | null)
| keyof JSX.IntrinsicElements
> {}
` as t.TSInterfaceDeclaration
replacementDeclaration.body = path.node.body
path.replaceWith(replacementDeclaration)
path.skip()
}
},
},
},
],
[
"Libraries/Performance/PureComponentDebug.d.ts",
{
// TODO: We should convert DeclareClass, which is a Flow type, to ClassDeclaration.
DeclareClass: {
exit(path) {
if (path.node.id.name === "PureComponentDebug") {
const typeParameters = path.node.typeParameters as any
t.assertTSTypeParameterDeclaration(typeParameters)
typeParameters.params.find((param) => param.name === "S")!.default = t.tsUndefinedKeyword()
path.skip()
}
},
},
},
],
[
"Libraries/Interaction/PanResponder.d.ts",
{
TSTypeAliasDeclaration: {
exit(path) {
if (path.node.id.name === "PanResponderInstance") {
// TS can't support the type of type mapping that $Call does, so convert it manually.
const replacementDeclaration = ast`
declare type PanResponderInstance = ReturnType<typeof PanResponder["create"]>
` as t.TSTypeAliasDeclaration
path.replaceWith(replacementDeclaration)
path.skip()
}
},
},
},
],
// TODO: This should be fixed upstream in RN. This seems like simply broken upstream code.
[
"Libraries/Utilities/ReactNativeTestTools.d.ts",
{
TSTypeAliasDeclaration: {
exit(path) {
switch (path.node.id.name) {
case "$ReturnType": {
const replacementDeclaration = ast`
declare type $ReturnType<Fn extends (...args: any) => any> = ReturnType<Fn>
` as t.TSTypeAliasDeclaration
path.replaceWith(replacementDeclaration)
path.skip()
break
}
case "ReactTestRendererJSON": {
const replacementDeclaration = ast`
declare type ReactTestRendererJSON =
$ReturnType<
$ReturnType<
typeof import("react-test-renderer")["create"]
>["toJSON"]
>
` as t.TSTypeAliasDeclaration
path.replaceWith(replacementDeclaration)
path.skip()
break
}
}
},
},
},
],
// TODO: This should be fixed upstream in RN. No duplicate prop entries should exist.
[
"Libraries/Text/TextProps.d.ts",
{
Program: {
enter(_, state: any) {
state.seen_adjustsFontSizeToFit_times = 0
},
},
TSPropertySignature: {
exit(path, state: any) {
if (t.isIdentifier(path.node.key) && path.node.key.name === "adjustsFontSizeToFit") {
state.seen_adjustsFontSizeToFit_times += 1
if (state.seen_adjustsFontSizeToFit_times === 2) {
path.remove()
}
}
},
},
},
],
[
"Libraries/Components/Pressable/useAndroidRippleForView.d.ts",
{
ImportDeclaration: {
exit(path) {
if (path.node.source.value === "../../..") {
if (path.node.specifiers.length !== 1 || path.node.specifiers[0].local.name !== "View") {
throw path.buildCodeFrameError("Expected a single `View` import specificier")
}
const replacementDeclaration = ast`
import View from "../../Components/View/View"
` as t.ImportDeclaration
path.replaceWith(replacementDeclaration)
path.skip()
}
},
},
},
],
[
"Libraries/Components/Touchable/TouchableBounce.d.ts",
{
ImportDeclaration: {
exit(path) {
if (path.node.source.value === "../../..") {
if (path.node.specifiers.length !== 1 || path.node.specifiers[0].local.name !== "Animated") {
throw path.buildCodeFrameError("Expected a single `Animated` import specificier")
}
const replacementDeclaration = ast`
import * as Animated from "../../Animated/src/Animated"
` as t.ImportDeclaration
path.replaceWith(replacementDeclaration)
path.skip()
}
},
},
},
],
[
"Libraries/Components/Picker/Picker.d.ts",
{
DeclareClass: {
exit(path) {
if (path.node.id.name === "PickerItem") {
const body = path.node.body as any
t.assertClassBody(body)
const renderMethod = body.body.find(
(m) => t.isTSDeclareMethod(m) && t.isIdentifier(m.key) && m.key.name === "render"
)
t.assertTSDeclareMethod(renderMethod)
t.assertTSTypeAnnotation(renderMethod.returnType)
t.assertTSVoidKeyword(renderMethod.returnType.typeAnnotation)
renderMethod.returnType.typeAnnotation = t.tsNeverKeyword()
}
},
},
},
],
// TODO: These should all be optional upstream
[
"Libraries/Lists/FlatList.d.ts",
{
TSTypeAliasDeclaration: {
exit(path) {
if (path.node.id.name === "OptionalProps") {
const typeLiteral = path.node.typeAnnotation
t.assertTSTypeLiteral(typeLiteral)
typeLiteral.members.forEach((propertySignature) => {
t.assertTSPropertySignature(propertySignature)
propertySignature.optional = true
})
}
},
},
},
],
// TODO: These should be typed as such upstream
[
"Libraries/Utilities/Dimensions.d.ts",
{
Program: {
exit(path) {
path.unshiftContainer(
"body",
ast`
import type { DisplayMetrics } from "./NativeDeviceInfo"
type DimensionsValue = {
window?: DisplayMetrics
screen?: DisplayMetrics
}
` as t.Statement[]
)
},
},
TSDeclareMethod: {
exit(path) {
t.assertTSDeclareMethod(path.node)
t.assertIdentifier(path.node.key)
if (
path.node.key.name === "get" &&
path.findParent((p) => p.isDeclareClass() && p.node.id.name === "Dimensions")
) {
const prop = (ast`
class _ {
static get<K extends keyof DimensionsValue>(dim: K): Required<DimensionsValue>[K]
}
` as t.ClassDeclaration).body.body[0]
path.replaceWith(prop)
path.skip()
}
},
},
},
],
// This is done so people can merge their own NativeModules interface declaration.
[
"Libraries/BatchedBridge/NativeModules.d.ts",
{
DeclareVariable: {
exit(path) {
const id = path.node.id
if (t.isIdentifier(id) && id.name === "NativeModules") {
t.assertTypeAnnotation(id.typeAnnotation)
const typeLiteral = id.typeAnnotation.typeAnnotation as any
t.assertTSTypeLiteral(typeLiteral)
const members = typeLiteral.members
path.insertBefore(
t.exportNamedDeclaration(
t.tsInterfaceDeclaration(
t.identifier("NativeModules"),
undefined,
undefined,
t.tsInterfaceBody(members)
)
)
)
id.typeAnnotation.typeAnnotation = t.tsTypeReference(t.identifier("NativeModules")) as any
}
},
},
},
],
// TODO: This is pending the work to port the better DT typings to Flow:
// https://github.com/microsoft/flow2dts/issues/14
[
"Libraries/Network/XMLHttpRequest.d.ts",
{
TSTypeReference: {
exit(path) {
if (t.isIdentifier(path.node.typeName) && path.node.typeName.name === "EventListener") {
path.replaceWith(t.tsAnyKeyword())
}
},
},
},
],
[
"Libraries/Animated/src/createAnimatedComponent.d.ts",
{
TSTypeParameter: {
exit(path) {
if (path.node.name === "Props") {
const constraint = path.node.constraint
t.assertTSTypeLiteral(constraint)
constraint.members = []
}
},
},
},
],
// TODO: These should be typed as such upstream
[
"Libraries/Components/View/ViewPropTypes.d.ts",
{
TSPropertySignature: {
exit(path) {
if (t.isIdentifier(path.node.key) && path.node.key.name === "focusable") {
const typeAnnotation = path.node.typeAnnotation!.typeAnnotation
t.assertTSBooleanKeyword(typeAnnotation)
path.node.typeAnnotation!.typeAnnotation = t.tsUnionType([
t.tsNullKeyword(),
t.tsUndefinedKeyword(),
t.tsBooleanKeyword(),
])
}
},
},
},
],
]
export default visitors