/
props.ts
693 lines (612 loc) · 18 KB
/
props.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
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
import {
type MagicString,
type SFC,
babelParse,
isStaticObjectKey,
resolveIdentifier,
resolveObjectExpression,
resolveString,
} from '@vue-macros/common'
import {
type TSFile,
type TSNamespace,
type TSProperties,
type TSResolvedType,
type TSScope,
isTSNamespace,
resolveTSProperties,
resolveTSReferencedType,
resolveTSScope,
} from '../ts'
import { type ASTDefinition, DefinitionKind } from './types'
import { attachNodeLoc, inferRuntimeType } from './utils'
import type {
CallExpression,
Expression,
ExpressionStatement,
LVal,
Node,
ObjectMethod,
ObjectProperty,
StringLiteral,
TSInterfaceDeclaration,
TSIntersectionType,
TSMappedType,
TSMethodSignature,
TSPropertySignature,
TSType,
TSTypeLiteral,
TSTypeReference,
TSUnionType,
VariableDeclaration,
} from '@babel/types'
type BuiltInTypesHandler = Record<
string,
{
handleType: (resolved: TSTypeReference) => TSType | undefined
handleTSProperties?: (properties: TSProperties) => TSProperties
}
>
const builtInTypesHandlers: BuiltInTypesHandler = {
Partial: {
handleType(resolved) {
return resolved.typeParameters?.params[0]
},
handleTSProperties(properties) {
for (const prop of Object.values(properties.properties)) {
prop.optional = true
}
return properties
},
},
Required: {
handleType(resolved) {
return resolved.typeParameters?.params[0]
},
handleTSProperties(properties) {
for (const prop of Object.values(properties.properties)) {
prop.optional = false
}
return properties
},
},
Readonly: {
handleType(resolved) {
return resolved.typeParameters?.params[0]
},
},
// TODO: pick, omit
}
export async function handleTSPropsDefinition({
s,
file,
offset,
definePropsAst,
typeDeclRaw,
withDefaultsAst,
defaultsDeclRaw,
statement,
declId,
}: {
s: MagicString
file: TSFile
sfc: SFC
offset: number
definePropsAst: CallExpression
typeDeclRaw: TSType
withDefaultsAst?: CallExpression
defaultsDeclRaw?: DefaultsASTRaw
statement: DefinePropsStatement
declId?: LVal
}): Promise<TSProps> {
const { definitions, definitionsAst } = await resolveDefinitions({
type: typeDeclRaw,
scope: file,
})
const { defaults, defaultsAst } = resolveDefaults(defaultsDeclRaw)
const addProp: TSProps['addProp'] = (name, value, optional) => {
const { key, signature, valueAst, signatureAst } = buildNewProp(
name,
value,
optional,
)
if (definitions[key]) return false
if (definitionsAst.scope === file) {
if (definitionsAst.ast.type === 'TSIntersectionType') {
s.appendLeft(definitionsAst.ast.end! + offset, ` & { ${signature} }`)
} else {
s.appendLeft(definitionsAst.ast.end! + offset - 1, ` ${signature}\n`)
}
}
definitions[key] = {
type: 'property',
value: {
code: value,
ast: valueAst,
scope: undefined,
},
optional: !!optional,
signature: {
code: signature,
ast: signatureAst,
scope: undefined,
},
addByAPI: true,
}
return true
}
const setProp: TSProps['setProp'] = (name, value, optional) => {
const { key, signature, signatureAst, valueAst } = buildNewProp(
name,
value,
optional,
)
const def = definitions[key]
if (!definitions[key]) return false
switch (def.type) {
case 'method': {
attachNodeLoc(def.methods[0].ast, signatureAst)
if (def.methods[0].scope === file)
s.overwriteNode(def.methods[0].ast, signature, { offset })
def.methods.slice(1).forEach((method) => {
if (method.scope === file) {
s.removeNode(method.ast, { offset })
}
})
break
}
case 'property': {
attachNodeLoc(def.signature.ast, signatureAst)
if (def.signature.scope === file && !def.addByAPI) {
s.overwriteNode(def.signature.ast, signature, { offset })
}
break
}
}
definitions[key] = {
type: 'property',
value: {
code: value,
ast: valueAst,
scope: undefined as any,
},
optional: !!optional,
signature: {
code: signature,
ast: signatureAst,
scope: undefined as any,
},
addByAPI: def.type === 'property' && def.addByAPI,
}
return true
}
const removeProp: TSProps['removeProp'] = (name) => {
const key = resolveString(name)
if (!definitions[key]) return false
const def = definitions[key]
switch (def.type) {
case 'property': {
if (def.signature.scope === file && !def.addByAPI) {
s.removeNode(def.signature.ast, { offset })
}
break
}
case 'method':
def.methods.forEach((method) => {
if (method.scope === file) s.removeNode(method.ast, { offset })
})
break
}
delete definitions[key]
return true
}
const getRuntimeDefinitions: TSProps['getRuntimeDefinitions'] = async () => {
const props: Record<string, RuntimePropDefinition> = Object.create(null)
for (const [propName, def] of Object.entries(definitions)) {
let prop: RuntimePropDefinition
if (def.type === 'method') {
prop = {
type: ['Function'],
required: !def.optional,
}
} else {
const resolvedType = def.value
if (resolvedType) {
const optional = def.optional
prop = {
type: await inferRuntimeType({
scope: resolvedType.scope || file,
type: resolvedType.ast,
}),
required: !optional,
}
} else {
prop = { type: ['null'], required: false }
}
}
const defaultValue = defaults?.[propName]
if (defaultValue) {
prop.default = (key = 'default') => {
switch (defaultValue.type) {
case 'ObjectMethod':
return `${
defaultValue.kind !== 'method' ? `${defaultValue.kind} ` : ''
}${defaultValue.async ? `async ` : ''}${key}(${s.sliceNode(
defaultValue.params,
{ offset },
)}) ${s.sliceNode(defaultValue.body, { offset })}`
case 'ObjectProperty':
return `${key}: ${s.sliceNode(defaultValue.value, { offset })}`
}
}
}
props[propName] = prop
}
return props
}
return {
kind: DefinitionKind.TS,
definitions,
defaults,
declId,
addProp,
setProp,
removeProp,
getRuntimeDefinitions,
// AST
definitionsAst,
defaultsAst,
statementAst: statement,
definePropsAst,
withDefaultsAst,
}
async function resolveUnion(definitionsAst: TSUnionType, scope: TSScope) {
const unionDefs: TSProps['definitions'][] = []
const keys = new Set<string>()
for (const type of definitionsAst.types) {
const defs = await resolveDefinitions({ type, scope }).then(
({ definitions }) => definitions,
)
Object.keys(defs).forEach((key) => keys.add(key))
unionDefs.push(defs)
}
const results: TSProps['definitions'] = Object.create(null)
for (const key of keys) {
let optional = false
let result: TSPropsMethod | TSPropsProperty | undefined
for (const defMap of unionDefs) {
const def = defMap[key]
if (!def) {
optional = true
continue
}
optional ||= def.optional
if (!result) {
result = def
continue
}
if (result.type === 'method' && def.type === 'method') {
result.methods.push(...def.methods)
} else if (result.type === 'property' && def.type === 'property') {
if (!def.value) {
continue
} else if (!result.value) {
result = def
continue
}
if (
def.value.ast.type === 'TSImportType' ||
def.value.ast.type === 'TSDeclareFunction' ||
def.value.ast.type === 'TSEnumDeclaration' ||
def.value.ast.type === 'TSInterfaceDeclaration' ||
def.value.ast.type === 'TSModuleDeclaration' ||
result.value.ast.type === 'TSImportType' ||
result.value.ast.type === 'TSDeclareFunction' ||
result.value.ast.type === 'TSEnumDeclaration' ||
result.value.ast.type === 'TSInterfaceDeclaration' ||
result.value.ast.type === 'TSModuleDeclaration'
) {
// no way!
continue
}
if (result.value.ast.type === 'TSUnionType') {
result.value.ast.types.push(def.value.ast)
} else {
// overwrite original to union type
result = {
type: 'property',
value: buildDefinition({
scope,
type: {
type: 'TSUnionType',
types: [result.value.ast, def.value.ast],
} satisfies TSUnionType,
}),
signature: null as any,
optional,
addByAPI: false,
}
}
} else {
throw new SyntaxError(
`Cannot resolve TS definition. Union type contains different types of results.`,
)
}
}
if (result) {
results[key] = { ...result, optional }
}
}
return {
definitions: results,
definitionsAst: buildDefinition({ scope, type: definitionsAst }),
}
}
async function resolveIntersection(
definitionsAst: TSIntersectionType,
scope: TSScope,
) {
const results: TSProps['definitions'] = Object.create(null)
for (const type of definitionsAst.types) {
const defMap = await resolveDefinitions({ type, scope }).then(
({ definitions }) => definitions,
)
for (const [key, def] of Object.entries(defMap)) {
const result = results[key]
if (!result) {
results[key] = def
continue
}
if (result.type === 'method' && def.type === 'method') {
result.methods.push(...def.methods)
} else {
results[key] = def
}
}
}
return {
definitions: results,
definitionsAst: buildDefinition({ scope, type: definitionsAst }),
}
}
async function resolveNormal(properties: TSProperties) {
const definitions: TSProps['definitions'] = Object.create(null)
for (const [key, sign] of Object.entries(properties.methods)) {
const methods = sign.map((sign) => buildDefinition(sign))
definitions[key] = {
type: 'method',
methods,
optional: sign.some((sign) => !!sign.type.optional),
}
}
for (const [key, value] of Object.entries(properties.properties)) {
const referenced = value.value
? await resolveTSReferencedType(value.value)
: undefined
definitions[key] = {
type: 'property',
addByAPI: false,
value:
referenced && !isTSNamespace(referenced)
? buildDefinition(referenced)
: undefined,
optional: value.optional,
signature: buildDefinition(value.signature),
}
}
return definitions
}
async function resolveDefinitions(
typeDeclRaw: TSResolvedType<TSType>,
): Promise<{
definitions: TSProps['definitions']
definitionsAst: TSProps['definitionsAst']
}> {
let resolved:
| TSResolvedType
| TSResolvedType<TSType>
| TSNamespace
| undefined = (await resolveTSReferencedType(typeDeclRaw)) || typeDeclRaw
let builtInTypesHandler: BuiltInTypesHandler[string] | undefined
if (
resolved &&
!isTSNamespace(resolved) &&
resolved.type.type === 'TSTypeReference' &&
resolved.type.typeName.type === 'Identifier'
) {
const typeName = resolved.type.typeName.name
let type: TSType | undefined
if (typeName in builtInTypesHandlers) {
builtInTypesHandler = builtInTypesHandlers[typeName]
type = builtInTypesHandler.handleType(resolved.type)
}
if (type)
resolved = await resolveTSReferencedType({
type,
scope: resolved.scope,
})
}
if (!resolved || isTSNamespace(resolved)) {
throw new SyntaxError(`Cannot resolve TS definition.`)
}
const { type: definitionsAst, scope } = resolved
if (definitionsAst.type === 'TSIntersectionType') {
return resolveIntersection(definitionsAst, scope)
} else if (definitionsAst.type === 'TSUnionType') {
return resolveUnion(definitionsAst, scope)
} else if (
definitionsAst.type !== 'TSInterfaceDeclaration' &&
definitionsAst.type !== 'TSTypeLiteral' &&
definitionsAst.type !== 'TSMappedType'
) {
if (definitionsAst.type === 'TSTypeReference') {
throw new SyntaxError(
`Cannot resolve TS type: ${resolveIdentifier(
definitionsAst.typeName,
).join('.')}`,
)
} else {
throw new SyntaxError(
`Cannot resolve TS definition: ${definitionsAst.type}`,
)
}
}
let properties = await resolveTSProperties({
scope,
type: definitionsAst,
})
if (builtInTypesHandler?.handleTSProperties)
properties = builtInTypesHandler.handleTSProperties(properties)
return {
definitions: await resolveNormal(properties),
definitionsAst: buildDefinition({ scope, type: definitionsAst }),
}
}
function resolveDefaults(defaultsAst?: DefaultsASTRaw): {
defaultsAst?: TSProps['defaultsAst']
defaults?: TSProps['defaults']
} {
if (!defaultsAst) return {}
const isStatic =
defaultsAst.type === 'ObjectExpression' && isStaticObjectKey(defaultsAst)
if (!isStatic) return { defaultsAst: defaultsAst as Expression }
const defaults = resolveObjectExpression(defaultsAst)
if (!defaults) return { defaultsAst }
return { defaults, defaultsAst }
}
function buildNewProp(
name: string | StringLiteral,
value: string,
optional: boolean | undefined,
) {
const key = resolveString(name)
const signature = `${name}${optional ? '?' : ''}: ${value}`
const valueAst = (babelParse(`type T = (${value})`, 'ts').body[0] as any)
.typeAnnotation.typeAnnotation
const signatureAst = (
babelParse(`interface T {${signature}}`, 'ts').body[0] as any
).body.body[0]
return { key, signature, signatureAst, valueAst }
}
function buildDefinition<T extends Node>({
type,
scope,
}: TSResolvedType<T>): ASTDefinition<T> {
return {
code: resolveTSScope(scope).file.content.slice(type.start!, type.end!),
ast: type,
scope,
}
}
}
export type Props = /* ReferenceProps | ObjectProps | */ TSProps | undefined
export type DefinePropsStatement = VariableDeclaration | ExpressionStatement
export type DefaultsASTRaw = CallExpression['arguments'][number]
export interface PropsBase {
declId?: LVal
statementAst: DefinePropsStatement
definePropsAst: CallExpression
withDefaultsAst?: CallExpression
}
// TODO: not implement yet
// export interface RuntimeProps extends PropsBase {
// /**
// * @example addProp('foo', 'String')
// * @example addProp('foo', '{ type: String, default: "foo" }')
// */
// addProp(name: string | StringLiteral, definition: string): void
// /**
// * Removes specified prop from TS interface.
// *
// * @returns `true` if prop was removed, `false` if prop was not found.
// */
// removeProp(name: string | StringLiteral): boolean
// }
// export interface ReferenceProps extends RuntimeProps {
// kind: DefinitionKind.Reference
// }
// export interface ObjectProps extends RuntimeProps {
// kind: DefinitionKind.Object
// /** propName -> definition */
// definitions?: Record<string, string>
// }
export interface TSPropsMethod {
type: 'method'
methods: ASTDefinition<TSMethodSignature>[]
optional: boolean
}
export interface TSPropsProperty {
type: 'property'
value: ASTDefinition<TSResolvedType['type']> | undefined
optional: boolean
signature: ASTDefinition<TSPropertySignature | TSMappedType>
/** Whether added by `addProp` API */
addByAPI: boolean
}
export interface RuntimePropDefinition {
type: string[]
required: boolean
default?: (key?: string) => string
}
export interface TSProps extends PropsBase {
kind: DefinitionKind.TS
definitions: Record<string | number, TSPropsMethod | TSPropsProperty>
definitionsAst: ASTDefinition<
| TSInterfaceDeclaration
| TSTypeLiteral
| TSIntersectionType
| TSUnionType
| TSMappedType
| TSTypeReference
>
/**
* Default value of props.
*
* `undefined` if not defined or it's not a static expression that cannot be analyzed statically.
*/
defaults?: Record<string, ObjectMethod | ObjectProperty>
/**
* `undefined` if not defined.
*/
defaultsAst?: Expression
/**
* Adds a new prop to the definitions. `definitions` will updated after this call.
*
* Added definition cannot be set and removed again.
*
* @example addProp('foo', 'string | boolean')
*
* @returns false if the definition already exists.
*/
addProp: (
name: string | StringLiteral,
type: string,
optional?: boolean,
) => boolean
/**
* Modify a definition of a prop. `definitions` will updated after this call.
*
* @limitation Cannot set the prop added by `addProp`.
*
* @example setProp('foo', 'string | boolean')
*
* @returns false if the definition does not exist.
*/
setProp: (
name: string | StringLiteral,
type: string,
optional?: boolean,
) => boolean
/**
* Removes specified prop from TS interface. `definitions` will updated after this call.
*
* @limitation Cannot remove prop added by `addProp`. (it will be removed in definitions though)
*
* @returns `true` if prop was removed, `false` if prop was not found.
*/
removeProp: (name: string | StringLiteral) => boolean
/**
* get runtime definitions.
*/
getRuntimeDefinitions: () => Promise<Record<string, RuntimePropDefinition>>
}