-
Notifications
You must be signed in to change notification settings - Fork 54
/
index.ts
1269 lines (1174 loc) · 31.8 KB
/
index.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
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
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import { FileUtils } from '@ts-morph/common'
import {
EnumDeclaration,
ExportableNode,
ImportDeclarationStructure,
InterfaceDeclaration,
Node,
Project,
SourceFile,
StructureKind,
Type,
TypeAliasDeclaration,
} from 'ts-morph'
const GENERATED_WARNING = 'WARNING: Do not manually change this file.'
// -- Helpers --
function reportError(message: string, ...args: unknown[]) {
console.error(`ERROR: ${message}`, ...args)
}
function lowerFirst(s: string): string {
const first_code_point = s.codePointAt(0)
if (first_code_point === undefined) return s
const first_letter = String.fromCodePoint(first_code_point)
return first_letter.toLowerCase() + s.substr(first_letter.length)
}
function findExportableNode(type: Type): (ExportableNode & Node) | null {
const symbol = type.getSymbol()
if (symbol === undefined) {
return null
}
return (
symbol
.getDeclarations()
.reduce<Node[]>((acc, node) => [...acc, node, ...node.getAncestors()], [])
.filter(Node.isExportable)
.find(n => n.isExported()) || null
)
}
function typeToDependency(type: Type, addDependency: IAddDependency): void {
const exportable = findExportableNode(type)
if (exportable === null) {
return
}
const sourceFile = exportable.getSourceFile()
const name = exportable.getSymbol()!.getName()
const isDefault = exportable.isDefaultExport()
if (!exportable.isExported()) {
reportError(`${name} is not exported from ${sourceFile.getFilePath()}`)
}
addDependency(sourceFile, name, isDefault)
}
function outFilePath(sourcePath: string, guardFileName: string) {
const outPath = sourcePath.replace(
/\.(ts|tsx|d\.ts)$/,
`.${guardFileName}.ts`
)
if (outPath === sourcePath)
throw new Error(
'Internal Error: sourcePath and outFilePath are identical: ' + outPath
)
return outPath
}
function deleteGuardFile(sourceFile: SourceFile) {
if (sourceFile.getFullText().indexOf(GENERATED_WARNING) >= 0) {
sourceFile.delete()
} else {
console.warn(
`${sourceFile.getFilePath()} is named like a guard file, but does not contain the generated header. Consider removing or renaming the file, or change the guardFileName setting.`
)
}
}
// https://github.com/dsherret/ts-simple-ast/issues/108#issuecomment-342665874
function isClassType(type: Type): boolean {
if (type.getConstructSignatures().length > 0) {
return true
}
const symbol = type.getSymbol()
if (symbol == null) {
return false
}
for (const declaration of symbol.getDeclarations()) {
if (Node.isClassDeclaration(declaration)) {
return true
}
if (
Node.isVariableDeclaration(declaration) &&
declaration.getType().getConstructSignatures().length > 0
) {
return true
}
}
return false
}
function isReadonlyArrayType(type: Type): boolean {
const symbol = type.getSymbol()
if (symbol === undefined) {
return false
}
return (
symbol.getName() === 'ReadonlyArray' && type.getTypeArguments().length === 1
)
}
function getReadonlyArrayType(type: Type): Type | undefined {
return type.getTypeArguments()[0]
}
function getTypeGuardName(
child: Guardable,
options: IProcessOptions
): string | null {
const jsDocs = child.getJsDocs()
for (const doc of jsDocs) {
for (const line of doc.getInnerText().split('\n')) {
const match = line
.trim()
.match(/@see\s+(?:{\s*(@link\s*)?(\w+)\s*}\s+)?ts-auto-guard:([^\s]*)/)
if (match !== null) {
const [, , typeGuardName, command] = match
if (command !== 'type-guard') {
reportError(`command ${command} is not supported!`)
return null
}
return typeGuardName
}
}
}
if (options.exportAll) {
const t = child.getType()
const symbols = [child, t.getSymbol(), t.getAliasSymbol()]
// type aliases have type __type sometimes
const name = symbols
.filter(x => x && x.getName() !== '__type')[0]
?.getName()
if (name) {
return 'is' + name
}
}
return null
}
// -- Main program --
function ors(...statements: string[]): string {
return parens(statements.join(' || \n'))
}
function ands(...statements: string[]): string {
return statements.join(' && \n')
}
function eq(a: string, b: string): string {
return `${a} === ${b}`
}
function ne(a: string, b: string): string {
return `${a} !== ${b}`
}
function typeOf(varName: string, type: string): string {
return eq(`typeof ${varName}`, `"${type}"`)
}
function typeUnionConditions(
varName: string,
types: Type[],
addDependency: IAddDependency,
project: Project,
path: string,
arrayDepth: number,
records: readonly IRecord[],
outFile: SourceFile,
options: IProcessOptions
): string {
const conditions: string[] = []
conditions.push(
...(types
.map(type =>
typeConditions(
varName,
type,
addDependency,
project,
path,
arrayDepth,
true,
records,
outFile,
options
)
)
.filter(v => v !== null) as string[])
)
return ors(...conditions)
}
function typeIntersectionConditions(
varName: string,
types: Type[],
addDependency: IAddDependency,
project: Project,
path: string,
arrayDepth: number,
records: readonly IRecord[],
outFile: SourceFile,
options: IProcessOptions
): string {
const conditions: string[] = []
conditions.push(
...(types
.map(type =>
typeConditions(
varName,
type,
addDependency,
project,
path,
arrayDepth,
true,
records,
outFile,
options
)
)
.filter(v => v !== null) as string[])
)
return ands(...conditions)
}
function parens(code: string) {
return `(${code})`
}
function arrayCondition(
varName: string,
arrayType: Type,
addDependency: IAddDependency,
project: Project,
path: string,
arrayDepth: number,
records: readonly IRecord[],
outFile: SourceFile,
options: IProcessOptions
): string {
if (arrayType.getText() === 'never') {
return ands(`Array.isArray(${varName})`, eq(`${varName}.length`, '0'))
}
const indexIdentifier = `i${arrayDepth}`
const elementPath = `${path}[\${${indexIdentifier}}]`
const conditions = typeConditions(
'e',
arrayType,
addDependency,
project,
elementPath,
arrayDepth + 1,
true,
records,
outFile,
options
)
if (conditions === null) {
return `Array.isArray(${varName})`
}
// Bit of a hack, just check if the second argument is used before actually
// creating it. This avoids unused parameter errors.
const secondArg = conditions.includes(elementPath)
? `, ${indexIdentifier}: number`
: ''
return ands(
`Array.isArray(${varName})`,
`${varName}.every((e: any${secondArg}) =>\n${conditions}\n)`
)
}
function objectTypeCondition(varName: string, callable: boolean): string {
return callable
? typeOf(varName, 'function')
: ors(
ands(ne(varName, 'null'), typeOf(varName, 'object')),
typeOf(varName, 'function')
)
}
function indexKeyTypeToString(type: Type): IndexKeyType {
switch (true) {
case type.isString():
return 'string'
case type.isNumber():
return 'number'
case type.isAny():
return 'any'
default:
throw new Error(
`Invalid type for index key: ${type.getText()}. Only string or number are expected.`
)
}
}
function objectCondition(
varName: string,
type: Type,
addDependency: IAddDependency,
project: Project,
path: string,
arrayDepth: number,
records: readonly IRecord[],
outFile: SourceFile,
options: IProcessOptions
): string | null {
const conditions: string[] = []
const symbol = type.getSymbol()
if (symbol === undefined) {
// I think this is happening when the type is declare in a node module.
// tslint:disable-next-line:no-console
console.error(`Unable to get symbol for type ${type.getText()}`)
return typeOf(varName, 'object')
}
const declarations = symbol.getDeclarations()
// TODO: https://github.com/rhys-vdw/ts-auto-guard/issues/29
const declaration = declarations[0]
if (declaration === undefined) {
reportError(`Couldn't find declaration for type ${type.getText()}`)
return null
}
const callable = type.getCallSignatures().length !== 0
if (callable) {
// emit warning
const suppressComment = 'ts-auto-guard-suppress function-type'
const commentsBefore = declaration.getLeadingCommentRanges()
const commentBefore = commentsBefore[commentsBefore.length - 1]
if (
commentBefore === undefined ||
!commentBefore.getText().includes(suppressComment)
) {
console.warn(
`
It seems that ${varName} has a function type.
Note that it is impossible to check if a function has the correct signature and return type at runtime.
To disable this warning, put comment "${suppressComment}" before the declaration.
`
)
}
}
if (type.isInterface()) {
if (!Node.isInterfaceDeclaration(declaration)) {
throw new TypeError(
'Extected declaration to be an interface declaration!'
)
}
declaration.getBaseTypes().forEach(baseType => {
const condition = typeConditions(
varName,
baseType,
addDependency,
project,
path,
arrayDepth,
true,
records,
outFile,
options
)
if (condition !== null) {
conditions.push(condition)
}
})
if (conditions.length === 0) {
conditions.push(objectTypeCondition(varName, callable))
}
// getProperties does not include methods like `foo(): void`
const properties = [
...declaration.getProperties(),
...declaration.getMethods(),
].map(p => ({
name: p.getSymbol()?.getEscapedName() ?? p.getName(),
type: p.getType(),
}))
conditions.push(
...propertiesConditions(
varName,
properties,
addDependency,
project,
path,
arrayDepth,
records,
outFile,
options
)
)
const indexSignatures = declaration
.getIndexSignatures()
.map(p => ({ keyType: p.getKeyType(), type: p.getReturnType() }))
if (indexSignatures.length) {
conditions.push(
indexSignaturesCondition(
varName,
indexSignatures.map(x => ({
keyType: indexKeyTypeToString(x.keyType),
type: x.type,
})),
properties,
addDependency,
project,
path,
arrayDepth,
records,
outFile,
options
)
)
}
} else {
conditions.push(objectTypeCondition(varName, callable))
// Get object literal properties...
try {
const properties = type.getProperties()
const typeDeclarations = type.getSymbol()?.getDeclarations()
const propertySignatures = properties.map(p => {
const propertyDeclarations = p.getDeclarations()
const typeAtLocation =
propertyDeclarations.length !== 0
? p.getTypeAtLocation(propertyDeclarations[0])
: p.getTypeAtLocation((typeDeclarations || [])[0])
return {
name: p.getName(),
type: typeAtLocation,
}
})
conditions.push(
...propertiesConditions(
varName,
propertySignatures,
addDependency,
project,
path,
arrayDepth,
records,
outFile,
options
)
)
const stringIndexType = type.getStringIndexType()
if (stringIndexType) {
conditions.push(
indexSignaturesCondition(
varName,
[{ keyType: 'string', type: stringIndexType }],
propertySignatures,
addDependency,
project,
path,
arrayDepth,
records,
outFile,
options
)
)
}
const numberIndexType = type.getNumberIndexType()
if (numberIndexType) {
conditions.push(
indexSignaturesCondition(
varName,
[{ keyType: 'number', type: numberIndexType }],
propertySignatures,
addDependency,
project,
path,
arrayDepth,
records,
outFile,
options
)
)
}
} catch (error) {
if (error instanceof TypeError) {
// see https://github.com/dsherret/ts-simple-ast/issues/397
reportError(`Internal ts-simple-ast error for ${type.getText()}`, error)
}
}
}
return ands(...conditions)
}
function tupleCondition(
varName: string,
type: Type,
addDependency: IAddDependency,
project: Project,
path: string,
arrayDepth: number,
records: readonly IRecord[],
outFile: SourceFile,
options: IProcessOptions
): string {
const types = type.getTupleElements()
const conditions = types.reduce(
(acc, elementType, i) => {
const condition = typeConditions(
`${varName}[${i}]`,
elementType,
addDependency,
project,
path,
arrayDepth,
true,
records,
outFile,
options
)
if (condition !== null) {
acc.push(condition)
}
return acc
},
[`Array.isArray(${varName})`]
)
return ands(...conditions)
}
function literalCondition(
varName: string,
type: Type,
addDependency: IAddDependency
): string | null {
if (type.isEnumLiteral()) {
const node = type
.getSymbol()!
.getDeclarations()
.find(Node.isEnumMember)!
.getParent()
if (node === undefined) {
reportError("Couldn't find enum literal parent")
return null
}
if (!Node.isEnumDeclaration(node)) {
reportError('Enum literal parent was not an enum declaration')
return null
}
typeToDependency(type, addDependency)
// type.getText() returns incorrect module name for some reason
return eq(
varName,
`${node.getSymbol()!.getName()}.${type.getSymbol()!.getName()}`
)
}
return eq(varName, type.getText())
}
function reusedCondition(
type: Type,
records: readonly IRecord[],
outFile: SourceFile,
addDependency: IAddDependency,
varName: string
): string | null {
const record = records.find(x => x.typeDeclaration.getType() === type)
if (record) {
if (record.outFile !== outFile) {
addDependency(record.outFile, record.guardName, false)
}
return `${record.guardName}(${varName}) as boolean`
}
return null
}
function typeConditions(
varName: string,
type: Type,
addDependency: IAddDependency,
project: Project,
path: string,
arrayDepth: number,
useGuard: boolean,
records: readonly IRecord[],
outFile: SourceFile,
options: IProcessOptions
): string | null {
const reused = reusedCondition(type, records, outFile, addDependency, varName)
if (useGuard && reused) {
return reused
}
if (type.isNull()) {
return eq(varName, 'null')
}
if (type.getText() === 'any' || type.getText() === 'unknown') {
return null
}
if (type.getText() === 'never') {
return typeOf(varName, 'undefined')
}
if (type.isBoolean()) {
return typeOf(varName, 'boolean')
}
if (type.isUnion()) {
// Seems to be bug here where enums can only be detected with enum
// literal + union check... odd.
if (type.isEnumLiteral()) {
typeToDependency(type, addDependency)
}
return typeUnionConditions(
varName,
type.getUnionTypes(),
addDependency,
project,
path,
arrayDepth,
records,
outFile,
options
)
}
if (type.isIntersection()) {
return typeIntersectionConditions(
varName,
type.getIntersectionTypes(),
addDependency,
project,
path,
arrayDepth,
records,
outFile,
options
)
}
if (type.isArray()) {
return arrayCondition(
varName,
type.getArrayElementType()!,
addDependency,
project,
path,
arrayDepth,
records,
outFile,
options
)
}
if (isReadonlyArrayType(type)) {
return arrayCondition(
varName,
getReadonlyArrayType(type)!,
addDependency,
project,
path,
arrayDepth,
records,
outFile,
options
)
}
if (isClassType(type)) {
typeToDependency(type, addDependency)
return `${varName} instanceof ${type.getSymbol()!.getName()}`
}
if (type.isTuple()) {
return tupleCondition(
varName,
type,
addDependency,
project,
path,
arrayDepth,
records,
outFile,
options
)
}
if (type.isObject()) {
return objectCondition(
varName,
type,
addDependency,
project,
path,
arrayDepth,
records,
outFile,
options
)
}
if (type.isLiteral()) {
return literalCondition(varName, type, addDependency)
}
return typeOf(varName, type.getText())
}
function propertyConditions(
objName: string,
property: { name: string; type: Type },
addDependency: IAddDependency,
project: Project,
path: string,
arrayDepth: number,
records: readonly IRecord[],
outFile: SourceFile,
options: IProcessOptions
): string | null {
const { debug } = options
const propertyName = property.name
const strippedName = propertyName.replace(/"/g, '')
const varName = `${objName}["${strippedName}"]`
const propertyPath = `${path}["${strippedName}"]`
let expectedType = property.type.getText()
const conditions = typeConditions(
varName,
property.type,
addDependency,
project,
propertyPath,
arrayDepth,
true,
records,
outFile,
options
)
if (debug) {
if (expectedType.indexOf('import') > -1) {
const standardizedCwd = FileUtils.standardizeSlashes(process.cwd())
expectedType = expectedType.replace(standardizedCwd, '.')
}
return (
conditions &&
`evaluate(${conditions}, \`${propertyPath}\`, ${JSON.stringify(
expectedType
)}, ${varName})`
)
}
return conditions
}
function propertiesConditions(
varName: string,
properties: ReadonlyArray<{ name: string; type: Type }>,
addDependency: IAddDependency,
project: Project,
path: string,
arrayDepth: number,
records: readonly IRecord[],
outFile: SourceFile,
options: IProcessOptions
): string[] {
return properties
.map(prop =>
propertyConditions(
varName,
prop,
addDependency,
project,
path,
arrayDepth,
records,
outFile,
options
)
)
.filter(v => v !== null) as string[]
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function assertNever<T>(_: never): T {
throw new Error('should be unreachable.')
}
function signatureKeyConditions(
keyType: IndexKeyType,
varName: string
): string | null {
if (keyType === 'string') {
return typeOf(varName, 'string')
} else if (keyType === 'number') {
return typeOf(varName, 'number')
} else if (keyType === 'any') {
return null
} else {
return assertNever(keyType)
}
}
function indexSignatureConditions(
objName: string,
keyName: string,
valueUsed: () => void,
keyUsed: () => void,
index: { keyType: IndexKeyType; type: Type },
addDependency: IAddDependency,
project: Project,
path: string,
arrayDepth: number,
records: readonly IRecord[],
outFile: SourceFile,
options: IProcessOptions
): string | null {
const { debug } = options
const expectedType = index.type.getText()
const conditions = typeConditions(
objName,
index.type,
addDependency,
project,
`${path} ${objName}`,
arrayDepth,
true,
records,
outFile,
options
)
const keyConditions = signatureKeyConditions(index.keyType, keyName)
if (conditions) {
valueUsed()
}
if (keyConditions) {
keyUsed()
}
if (debug) {
const cleanKeyReplacer = '${key.toString().replace(/"/g, \'\\\\"\')}'
const evaluation =
conditions &&
`evaluate(${conditions}, \`${path}["${cleanKeyReplacer}"]\`, ${JSON.stringify(
expectedType
)}, ${objName})`
const keyEvaluation =
keyConditions &&
`evaluate(${keyConditions}, \`${path} (key: "${cleanKeyReplacer}")\`, ${JSON.stringify(
index.keyType
)}, ${keyName})`
if (evaluation || keyEvaluation) {
keyUsed()
}
if (evaluation && keyEvaluation) {
return ands(evaluation, keyEvaluation)
}
return evaluation || keyEvaluation
}
if (conditions && keyConditions) {
return ands(conditions, keyConditions)
}
// If we don't have both try and return one, or null if neither
return conditions || keyConditions
}
type IndexKeyType = 'string' | 'number' | 'any'
function indexSignaturesCondition(
varName: string,
indexSignatures: ReadonlyArray<{ keyType: IndexKeyType; type: Type }>,
properties: ReadonlyArray<{ name: string; type: Type }>,
addDependency: IAddDependency,
project: Project,
path: string,
arrayDepth: number,
records: readonly IRecord[],
outFile: SourceFile,
options: IProcessOptions
): string {
let valuePrefix = '_'
const valueUsed = () => {
valuePrefix = ''
}
let keyPrefix = '_'
const keyUsed = () => {
keyPrefix = ''
}
const conditions = ors(
...(indexSignatures
.map(indexSignature =>
indexSignatureConditions(
'value',
'key',
valueUsed,
keyUsed,
indexSignature,
addDependency,
project,
path,
arrayDepth,
records,
outFile,
options
)
)
.filter(v => v !== null) as string[])
)
const staticKeysFilter = properties.length
? `
.filter(([key]) => ![${properties
.map(({ name }) => `"${name}"`)
.join(',')}].includes(key))`
: ''
return `Object.entries<any>(${varName})${staticKeysFilter}
.every(([${keyPrefix}key, ${valuePrefix}value]) => ${conditions})`
}
function generateTypeGuard(
functionName: string,
typeDeclaration: Guardable,
addDependency: IAddDependency,
project: Project,
records: readonly IRecord[],
outFile: SourceFile,
options: IProcessOptions
): string {
const { debug, shortCircuitCondition } = options
const typeName = typeDeclaration.getName()
const defaultArgumentName = lowerFirst(typeName)
const signatureObjName = 'obj'
const innerObjName = 'typedObj'
const conditions = typeConditions(
innerObjName,
typeDeclaration.getType(),
addDependency,
project,
'${argumentName}', // tslint:disable-line:no-invalid-template-strings
0,
false,
records,
outFile,
options
)
const secondArgument = debug
? `, argumentName: string = "${defaultArgumentName}"`
: ''
const signature = `export function ${functionName}(${signatureObjName}: unknown${secondArgument}): ${signatureObjName} is ${typeName} {\n`
const shortCircuit = shortCircuitCondition
? `if (${shortCircuitCondition}) return true\n`
: ''
const functionBody = `const ${innerObjName} = ${signatureObjName} as ${typeName}\nreturn (\n${
conditions || true
}\n)\n}\n`
return [signature, shortCircuit, functionBody].join('')
}
// -- Process project --
interface IImports {
[exportName: string]: string
}
type Dependencies = Map<SourceFile, IImports>
type IAddDependency = (
sourceFile: SourceFile,
exportName: string,
isDefault: boolean
) => void
function createAddDependency(dependencies: Dependencies): IAddDependency {
return function addDependency(sourceFile, name, isDefault) {
const alias = name
if (isDefault) {
name = 'default'
}
let imports = dependencies.get(sourceFile)
if (imports === undefined) {
imports = {}
dependencies.set(sourceFile, imports)
}
const previousAlias = imports[name]
if (previousAlias !== undefined && previousAlias !== alias) {
reportError(
`Conflicting export alias for "${sourceFile.getFilePath()}": "${alias}" vs "${previousAlias}"`