-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathanalyzer.ts
More file actions
1306 lines (1168 loc) · 37.5 KB
/
analyzer.ts
File metadata and controls
1306 lines (1168 loc) · 37.5 KB
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
import ts from 'typescript'
import type { ImportResolver, SourceHost } from './resolver'
export type ComponentKind = 'client' | 'server' | 'unknown'
export interface ScopeConfig {
declaration: boolean
element: boolean
export: boolean
import: boolean
type: boolean
}
export interface ComponentUsage {
kind: Exclude<ComponentKind, 'unknown'>
ranges: DecorationSegment[]
sourceFilePath: string
tagName: string
}
interface DecorationSegment {
end: number
start: number
}
interface CachedAnalysis {
analysis: FileAnalysis
signature: string
}
interface CachedDirective {
componentNames: Set<string>
hasStarExport: boolean
kind: Exclude<ComponentKind, 'unknown'>
reExports: Map<string, ReExportTarget>
signature: string
}
interface ReExportTarget {
source: string
sourceName: string
}
interface NamedRange {
name: string
ranges: DecorationSegment[]
}
interface LocalComponent {
kind: Exclude<ComponentKind, 'unknown'>
ranges: DecorationSegment[]
}
interface FileAnalysis {
exportReferences: NamedRange[]
imports: Map<
string,
{ exportName: string; ranges: DecorationSegment[]; source: string }
>
jsxTags: JsxTagReference[]
localComponents: Map<string, LocalComponent>
ownComponentKind: Exclude<ComponentKind, 'unknown'>
typeIdentifiers: TypeIdentifier[]
}
interface JsxTagReference {
lookupName: string
ranges: DecorationSegment[]
tagName: string
}
interface TypeIdentifier {
enclosingComponent: string | undefined
name: string
ranges: DecorationSegment[]
}
export class ComponentLensAnalyzer {
private readonly analysisCache = new Map<string, CachedAnalysis>()
private readonly directiveCache = new Map<string, CachedDirective>()
public constructor(
private readonly host: SourceHost,
private readonly resolver: ImportResolver,
) {}
public clear(): void {
this.analysisCache.clear()
this.directiveCache.clear()
this.resolver.clear()
}
public invalidateFile(filePath: string): void {
this.analysisCache.delete(filePath)
this.directiveCache.delete(filePath)
}
public async findComponentDeclaration(
filePath: string,
componentName: string,
): Promise<{ character: number; line: number } | undefined> {
const sourceText = this.host.readFileAsync
? await this.host.readFileAsync(filePath)
: this.host.readFile(filePath)
if (sourceText === undefined) {
return undefined
}
const signature = this.host.getSignatureAsync
? await this.host.getSignatureAsync(filePath)
: this.host.getSignature(filePath)
if (signature === undefined) {
return undefined
}
const analysis = this.getAnalysis(filePath, sourceText, signature)
if (!analysis) {
return undefined
}
const component = analysis.localComponents.get(componentName)
if (!component || component.ranges.length === 0) {
return undefined
}
const offset = component.ranges[0]!.start
let line = 0
let lastNewline = -1
for (let i = 0; i < offset; i++) {
if (sourceText.charCodeAt(i) === 10) {
line++
lastNewline = i
}
}
return { character: offset - lastNewline - 1, line }
}
public async analyzeDocument(
filePath: string,
sourceText: string,
signature: string,
scope: ScopeConfig = {
declaration: true,
element: true,
export: true,
import: true,
type: true,
},
): Promise<ComponentUsage[]> {
const analysis = this.getAnalysis(filePath, sourceText, signature)
if (!analysis) {
return []
}
const usages: ComponentUsage[] = []
let resolvedPaths: Map<string, string> | undefined
let fileInfos: Map<string, CachedDirective> | undefined
let reExportResolutions:
| Map<string, { sourceName: string; targetPath: string }>
| undefined
if ((scope.element || scope.import) && analysis.imports.size > 0) {
resolvedPaths = new Map()
fileInfos = new Map()
const uniqueFilePaths = new Set<string>()
for (const [lookupName, entry] of analysis.imports) {
if (
analysis.localComponents.has(lookupName) ||
resolvedPaths.has(lookupName)
) {
continue
}
const resolvedFilePath = this.resolver.resolveImport(
filePath,
entry.source,
)
if (resolvedFilePath) {
resolvedPaths.set(lookupName, resolvedFilePath)
uniqueFilePaths.add(resolvedFilePath)
}
}
if (uniqueFilePaths.size > 0) {
await Promise.all(
Array.from(uniqueFilePaths, (resolvedPath) =>
this.getFileComponentInfo(resolvedPath).then((info) => {
if (info) fileInfos!.set(resolvedPath, info)
}),
),
)
}
const reExportTargets = new Set<string>()
reExportResolutions = new Map()
for (const [lookupName, entry] of analysis.imports) {
if (analysis.localComponents.has(lookupName)) continue
const resolvedFilePath = resolvedPaths.get(lookupName)
if (!resolvedFilePath) continue
const fileInfo = fileInfos.get(resolvedFilePath)
if (!fileInfo) continue
const exportName = entry.exportName
if (exportName === '*') continue
if (fileInfo.componentNames.has(exportName)) continue
const reExport = fileInfo.reExports.get(exportName)
if (reExport) {
const targetPath = this.resolver.resolveImport(
resolvedFilePath,
reExport.source,
)
if (targetPath) {
reExportResolutions.set(lookupName, {
sourceName: reExport.sourceName,
targetPath,
})
if (!fileInfos.has(targetPath)) {
reExportTargets.add(targetPath)
}
}
}
}
if (reExportTargets.size > 0) {
await Promise.all(
Array.from(reExportTargets, (targetPath) =>
this.getFileComponentInfo(targetPath).then((info) => {
if (info) fileInfos!.set(targetPath, info)
}),
),
)
}
}
const checkImportedComponent = (
lookupName: string,
):
| {
kind: Exclude<ComponentKind, 'unknown'>
sourceFilePath: string
}
| undefined => {
if (!resolvedPaths || !fileInfos) return undefined
const resolvedFilePath = resolvedPaths.get(lookupName)
if (!resolvedFilePath) return undefined
const fileInfo = fileInfos.get(resolvedFilePath)
if (!fileInfo) return undefined
const importEntry = analysis.imports.get(lookupName)
if (!importEntry) return undefined
const exportName = importEntry.exportName
if (exportName === '*') {
return { kind: fileInfo.kind, sourceFilePath: resolvedFilePath }
}
if (fileInfo.componentNames.has(exportName)) {
return { kind: fileInfo.kind, sourceFilePath: resolvedFilePath }
}
if (reExportResolutions) {
const reExportRes = reExportResolutions.get(lookupName)
if (reExportRes) {
const targetInfo = fileInfos.get(reExportRes.targetPath)
if (targetInfo) {
if (targetInfo.componentNames.has(reExportRes.sourceName)) {
return {
kind: targetInfo.kind,
sourceFilePath: reExportRes.targetPath,
}
}
if (targetInfo.hasStarExport) {
return {
kind: targetInfo.kind,
sourceFilePath: reExportRes.targetPath,
}
}
}
}
}
if (fileInfo.hasStarExport) {
return { kind: fileInfo.kind, sourceFilePath: resolvedFilePath }
}
return undefined
}
if (scope.element) {
const jsxTags = analysis.jsxTags
for (let i = 0; i < jsxTags.length; i++) {
const jsxTag = jsxTags[i]!
const localComponent = analysis.localComponents.get(jsxTag.lookupName)
if (localComponent) {
usages.push({
kind: localComponent.kind,
ranges: jsxTag.ranges,
sourceFilePath: filePath,
tagName: jsxTag.tagName,
})
continue
}
const result = checkImportedComponent(jsxTag.lookupName)
if (result) {
usages.push({
kind: result.kind,
ranges: jsxTag.ranges,
sourceFilePath: result.sourceFilePath,
tagName: jsxTag.tagName,
})
}
}
}
if (scope.import && resolvedPaths) {
for (const [name, entry] of analysis.imports) {
const result = checkImportedComponent(name)
if (result) {
usages.push({
kind: result.kind,
ranges: entry.ranges,
sourceFilePath: result.sourceFilePath,
tagName: name,
})
}
}
}
if (scope.declaration) {
for (const [name, component] of analysis.localComponents) {
usages.push({
kind: component.kind,
ranges: component.ranges,
sourceFilePath: filePath,
tagName: name,
})
}
}
if (scope.type) {
const typeUsageKinds = new Map<
string,
Exclude<ComponentKind, 'unknown'>
>()
const deferredDeclarations: TypeIdentifier[] = []
const typeIds = analysis.typeIdentifiers
for (let i = 0; i < typeIds.length; i++) {
const typeId = typeIds[i]!
if (typeId.enclosingComponent) {
const kind =
analysis.localComponents.get(typeId.enclosingComponent)?.kind ??
analysis.ownComponentKind
if (!typeUsageKinds.has(typeId.name) || kind === 'client') {
typeUsageKinds.set(typeId.name, kind)
}
usages.push({
kind,
ranges: typeId.ranges,
sourceFilePath: filePath,
tagName: typeId.name,
})
} else {
deferredDeclarations.push(typeId)
}
}
for (let i = 0; i < deferredDeclarations.length; i++) {
const typeId = deferredDeclarations[i]!
usages.push({
kind: typeUsageKinds.get(typeId.name) ?? analysis.ownComponentKind,
ranges: typeId.ranges,
sourceFilePath: filePath,
tagName: typeId.name,
})
}
}
if (scope.export) {
const exportRefs = analysis.exportReferences
for (let i = 0; i < exportRefs.length; i++) {
const exportRef = exportRefs[i]!
if (analysis.localComponents.has(exportRef.name)) {
usages.push({
kind: analysis.ownComponentKind,
ranges: exportRef.ranges,
sourceFilePath: filePath,
tagName: exportRef.name,
})
}
}
}
return usages
}
private async getFileComponentInfo(
filePath: string,
): Promise<CachedDirective | undefined> {
const signature = this.host.getSignatureAsync
? await this.host.getSignatureAsync(filePath)
: this.host.getSignature(filePath)
if (signature === undefined) {
return undefined
}
const cached = this.directiveCache.get(filePath)
if (cached && cached.signature === signature) {
return cached
}
const sourceText = this.host.readFileAsync
? await this.host.readFileAsync(filePath)
: this.host.readFile(filePath)
if (sourceText === undefined) {
return undefined
}
const kind: Exclude<ComponentKind, 'unknown'> = hasUseClientDirective(
sourceText,
)
? 'client'
: 'server'
const { componentNames, hasStarExport, reExports } =
extractFileComponentExports(filePath, sourceText)
const info: CachedDirective = {
componentNames,
hasStarExport,
kind,
reExports,
signature,
}
this.directiveCache.set(filePath, info)
return info
}
private getAnalysis(
filePath: string,
sourceText: string,
signature: string,
): FileAnalysis | undefined {
const cached = this.analysisCache.get(filePath)
if (cached && cached.signature === signature) {
return cached.analysis
}
const analysis = parseFileAnalysis(filePath, sourceText)
this.analysisCache.set(filePath, { analysis, signature })
return analysis
}
}
function parseFileAnalysis(filePath: string, sourceText: string): FileAnalysis {
const sourceFile = ts.createSourceFile(
filePath,
sourceText,
ts.ScriptTarget.Latest,
false,
getScriptKind(filePath),
)
const asyncComponents = new Set<string>()
const componentRanges: { end: number; name: string; pos: number }[] = []
const exportReferences: NamedRange[] = []
const imports = new Map<
string,
{ exportName: string; ranges: DecorationSegment[]; source: string }
>()
const localComponents = new Map<string, LocalComponent>()
const typeIdentifiers: TypeIdentifier[] = []
let ownComponentKind: Exclude<ComponentKind, 'unknown'> = 'server'
let statementIndex = 0
const nodeRange = (node: ts.Node): DecorationSegment => ({
end: node.end,
start: node.getStart(sourceFile),
})
const registerComponent = (
name: string,
nameNode: ts.Node,
scopeNode: ts.Node,
): void => {
localComponents.set(name, {
kind: ownComponentKind,
ranges: [nodeRange(nameNode)],
})
componentRanges.push({
end: scopeNode.end,
name,
pos: scopeNode.pos,
})
}
const hasAsyncModifier = (
modifiers: ts.NodeArray<ts.ModifierLike> | undefined,
): boolean => {
if (!modifiers) return false
for (let i = 0; i < modifiers.length; i++) {
if (modifiers[i]!.kind === ASYNC_KEYWORD) return true
}
return false
}
const addImport = (
identifier: ts.Identifier,
source: string,
exportName: string,
): void => {
if (isComponentIdentifier(identifier.text)) {
imports.set(identifier.text, {
exportName,
ranges: [nodeRange(identifier)],
source,
})
}
}
for (; statementIndex < sourceFile.statements.length; statementIndex++) {
const statement = sourceFile.statements[statementIndex]!
if (statement.kind !== SK_ExprStmt) break
const expr = (statement as ts.ExpressionStatement).expression
if (expr.kind !== SK_StringLiteral) break
if ((expr as ts.StringLiteral).text === 'use client') {
ownComponentKind = 'client'
statementIndex++
break
}
}
for (; statementIndex < sourceFile.statements.length; statementIndex++) {
const statement = sourceFile.statements[statementIndex]!
switch (statement.kind) {
case SK_ImportDecl: {
const importStmt = statement as ts.ImportDeclaration
if (importStmt.moduleSpecifier.kind === SK_StringLiteral) {
const source = (importStmt.moduleSpecifier as ts.StringLiteral).text
const importClause = importStmt.importClause
if (importClause) {
if (importClause.name) {
addImport(importClause.name, source, 'default')
}
const namedBindings = importClause.namedBindings
if (namedBindings) {
if (namedBindings.kind === SK_NamespaceImport) {
addImport(
(namedBindings as ts.NamespaceImport).name,
source,
'*',
)
} else {
const elements = (namedBindings as ts.NamedImports).elements
for (let j = 0; j < elements.length; j++) {
const el = elements[j]!
addImport(
el.name,
source,
el.propertyName?.text ?? el.name.text,
)
}
}
}
}
}
break
}
case SK_FunctionDecl: {
const funcDecl = statement as ts.FunctionDeclaration
if (funcDecl.name && isComponentIdentifier(funcDecl.name.text)) {
registerComponent(funcDecl.name.text, funcDecl.name, funcDecl)
if (hasAsyncModifier(funcDecl.modifiers)) {
asyncComponents.add(funcDecl.name.text)
}
}
break
}
case SK_ClassDecl: {
const classDecl = statement as ts.ClassDeclaration
if (classDecl.name && isComponentIdentifier(classDecl.name.text)) {
registerComponent(classDecl.name.text, classDecl.name, classDecl)
}
break
}
case SK_InterfaceDecl:
case SK_TypeAliasDecl: {
const namedStmt = statement as
| ts.InterfaceDeclaration
| ts.TypeAliasDeclaration
if (isComponentIdentifier(namedStmt.name.text)) {
typeIdentifiers.push({
enclosingComponent: undefined,
name: namedStmt.name.text,
ranges: [nodeRange(namedStmt.name)],
})
}
break
}
case SK_ExportDecl: {
const exportDecl = statement as ts.ExportDeclaration
if (
exportDecl.exportClause &&
exportDecl.exportClause.kind === SK_NamedExports
) {
const elements = (exportDecl.exportClause as ts.NamedExports).elements
for (let j = 0; j < elements.length; j++) {
const element = elements[j]!
if (isComponentIdentifier(element.name.text)) {
exportReferences.push({
name: element.name.text,
ranges: [nodeRange(element.name)],
})
}
}
}
break
}
case SK_ExportAssignment: {
const exportAssign = statement as ts.ExportAssignment
if (
!exportAssign.isExportEquals &&
exportAssign.expression.kind === SK_Identifier &&
isComponentIdentifier((exportAssign.expression as ts.Identifier).text)
) {
exportReferences.push({
name: (exportAssign.expression as ts.Identifier).text,
ranges: [nodeRange(exportAssign.expression)],
})
}
break
}
case SK_VariableStmt: {
const varStmt = statement as ts.VariableStatement
const declarations = varStmt.declarationList.declarations
for (let j = 0; j < declarations.length; j++) {
const declaration = declarations[j]!
if (
declaration.name.kind !== SK_Identifier ||
!isComponentIdentifier((declaration.name as ts.Identifier).text) ||
!declaration.initializer
) {
continue
}
const declName = (declaration.name as ts.Identifier).text
if (declaration.initializer.kind === SK_ClassExpr) {
registerComponent(declName, declaration.name, declaration)
continue
}
const fn = getComponentFunction(declaration.initializer)
if (fn) {
registerComponent(declName, declaration.name, declaration)
if (hasAsyncModifier(fn.modifiers)) {
asyncComponents.add(declName)
}
}
}
break
}
}
}
const jsxTags = collectSourceElements(
sourceFile,
componentRanges,
typeIdentifiers,
localComponents,
asyncComponents,
ownComponentKind === 'server',
)
return {
exportReferences,
imports,
jsxTags,
localComponents,
ownComponentKind,
typeIdentifiers,
}
}
const ASYNC_KEYWORD = ts.SyntaxKind.AsyncKeyword
const SK_Identifier = ts.SyntaxKind.Identifier
const SK_PropertyAccess = ts.SyntaxKind.PropertyAccessExpression
const SK_JsxOpening = ts.SyntaxKind.JsxOpeningElement
const SK_JsxSelfClosing = ts.SyntaxKind.JsxSelfClosingElement
const SK_JsxClosing = ts.SyntaxKind.JsxClosingElement
const SK_TypeReference = ts.SyntaxKind.TypeReference
const SK_ImportDecl = ts.SyntaxKind.ImportDeclaration
const SK_EnumDecl = ts.SyntaxKind.EnumDeclaration
const SK_ExportDecl = ts.SyntaxKind.ExportDeclaration
const SK_FunctionDecl = ts.SyntaxKind.FunctionDeclaration
const SK_VariableDecl = ts.SyntaxKind.VariableDeclaration
const SK_JsxAttribute = ts.SyntaxKind.JsxAttribute
const SK_JsxExpression = ts.SyntaxKind.JsxExpression
const SK_ArrowFunction = ts.SyntaxKind.ArrowFunction
const SK_FunctionExpr = ts.SyntaxKind.FunctionExpression
const SK_CallExpression = ts.SyntaxKind.CallExpression
const SK_ClassExpr = ts.SyntaxKind.ClassExpression
const SK_Block = ts.SyntaxKind.Block
const SK_ExprStmt = ts.SyntaxKind.ExpressionStatement
const SK_StringLiteral = ts.SyntaxKind.StringLiteral
const SK_ClassDecl = ts.SyntaxKind.ClassDeclaration
const SK_InterfaceDecl = ts.SyntaxKind.InterfaceDeclaration
const SK_TypeAliasDecl = ts.SyntaxKind.TypeAliasDeclaration
const SK_ExportAssignment = ts.SyntaxKind.ExportAssignment
const SK_VariableStmt = ts.SyntaxKind.VariableStatement
const SK_NamespaceImport = ts.SyntaxKind.NamespaceImport
const SK_NamedExports = ts.SyntaxKind.NamedExports
const SK_ExportKw = ts.SyntaxKind.ExportKeyword
const SK_DefaultKw = ts.SyntaxKind.DefaultKeyword
const SK_TypeLiteral = ts.SyntaxKind.TypeLiteral
function isComponentIdentifier(name: string): boolean {
const code = name.charCodeAt(0)
return code >= 65 && code <= 90
}
function getComponentFunction(
initializer: ts.Expression,
): ts.ArrowFunction | ts.FunctionExpression | undefined {
const kind = initializer.kind
if (kind === SK_ArrowFunction || kind === SK_FunctionExpr) {
return initializer as ts.ArrowFunction | ts.FunctionExpression
}
if (kind === SK_CallExpression) {
const call = initializer as ts.CallExpression
if (isComponentWrapper(call.expression)) {
const args = call.arguments
for (let i = 0; i < args.length; i++) {
const argKind = args[i]!.kind
if (argKind === SK_ArrowFunction || argKind === SK_FunctionExpr) {
return args[i] as ts.ArrowFunction | ts.FunctionExpression
}
}
}
}
return undefined
}
function hasUseServerDirective(
fn: ts.ArrowFunction | ts.FunctionDeclaration | ts.FunctionExpression,
): boolean {
const body = fn.body
if (!body || body.kind !== SK_Block) {
return false
}
const statements = (body as ts.Block).statements
for (let i = 0; i < statements.length; i++) {
const stmt = statements[i]!
if (stmt.kind !== SK_ExprStmt) break
const expr = (stmt as ts.ExpressionStatement).expression
if (expr.kind !== SK_StringLiteral) break
if ((expr as ts.StringLiteral).text === 'use server') {
return true
}
}
return false
}
function isComponentWrapper(expr: ts.Expression): boolean {
if (expr.kind === SK_Identifier) {
const text = (expr as ts.Identifier).text
return text === 'forwardRef' || text === 'memo'
}
if (expr.kind === SK_PropertyAccess) {
const pa = expr as ts.PropertyAccessExpression
return (
pa.expression.kind === SK_Identifier &&
(pa.expression as ts.Identifier).text === 'React' &&
(pa.name.text === 'forwardRef' || pa.name.text === 'memo')
)
}
return false
}
function collectSourceElements(
sourceFile: ts.SourceFile,
componentRanges: { end: number; name: string; pos: number }[],
typeIdentifiers: TypeIdentifier[],
localComponents: Map<string, LocalComponent>,
asyncComponents: Set<string>,
inferClientKind: boolean,
): JsxTagReference[] {
const jsxTags: JsxTagReference[] = []
const componentByPos = new Map<number, { end: number; name: string }>()
for (let i = 0; i < componentRanges.length; i++) {
const range = componentRanges[i]!
componentByPos.set(range.pos, range)
}
let perComponentFuncs: Map<string, Map<string, boolean>> | undefined
let perComponentRefs: Map<string, string[]> | undefined
let componentsWithInlineFn: Set<string> | undefined
if (inferClientKind) {
perComponentFuncs = new Map()
perComponentRefs = new Map()
componentsWithInlineFn = new Set()
for (let i = 0; i < componentRanges.length; i++) {
const range = componentRanges[i]!
if (!asyncComponents.has(range.name)) {
perComponentFuncs.set(range.name, new Map())
perComponentRefs.set(range.name, [])
}
}
}
let currentComponent: string | undefined
let currentComponentTracked = false
let typeLiteralDepth = 0
const visit = (node: ts.Node): void => {
const nodeKind = node.kind
if (
nodeKind === SK_ImportDecl ||
nodeKind === SK_EnumDecl ||
nodeKind === SK_ExportDecl
) {
return
}
const isTypeLiteral = nodeKind === SK_TypeLiteral
if (isTypeLiteral) typeLiteralDepth++
const entry = componentByPos.get(node.pos)
const entered = entry !== undefined && entry.end === node.end
let savedComponent: string | undefined
let savedTracked = false
if (entered) {
savedComponent = currentComponent
savedTracked = currentComponentTracked
currentComponent = entry.name
currentComponentTracked = perComponentFuncs?.has(entry.name) ?? false
}
if (
nodeKind === SK_JsxOpening ||
nodeKind === SK_JsxSelfClosing ||
nodeKind === SK_JsxClosing
) {
const jsxTag = createJsxTagReference(
node as
| ts.JsxOpeningElement
| ts.JsxSelfClosingElement
| ts.JsxClosingElement,
sourceFile,
nodeKind,
)
if (jsxTag) {
jsxTags.push(jsxTag)
}
} else if (nodeKind === SK_TypeReference && typeLiteralDepth === 0) {
const typeName = (node as ts.TypeReferenceNode).typeName
if (
typeName.kind === SK_Identifier &&
isComponentIdentifier((typeName as ts.Identifier).text)
) {
const id = typeName as ts.Identifier
typeIdentifiers.push({
enclosingComponent: currentComponent,
name: id.text,
ranges: [{ end: id.end, start: id.getStart(sourceFile) }],
})
}
}
if (
currentComponentTracked &&
!componentsWithInlineFn!.has(currentComponent!)
) {
if (nodeKind === SK_FunctionDecl) {
const fn = node as ts.FunctionDeclaration
if (fn.name) {
perComponentFuncs!
.get(currentComponent!)!
.set(fn.name.text, hasUseServerDirective(fn))
}
} else if (nodeKind === SK_VariableDecl) {
const decl = node as ts.VariableDeclaration
if (
decl.name.kind === SK_Identifier &&
decl.initializer &&
(decl.initializer.kind === SK_ArrowFunction ||
decl.initializer.kind === SK_FunctionExpr)
) {
perComponentFuncs!
.get(currentComponent!)!
.set(
(decl.name as ts.Identifier).text,
hasUseServerDirective(
decl.initializer as ts.ArrowFunction | ts.FunctionExpression,
),
)
}
} else if (nodeKind === SK_JsxAttribute) {
const attr = node as ts.JsxAttribute
if (attr.initializer && attr.initializer.kind === SK_JsxExpression) {
const expr = (attr.initializer as ts.JsxExpression).expression
if (expr) {
const exprKind = expr.kind
if (
(exprKind === SK_ArrowFunction || exprKind === SK_FunctionExpr) &&
!hasUseServerDirective(
expr as ts.ArrowFunction | ts.FunctionExpression,
)
) {
componentsWithInlineFn!.add(currentComponent!)
} else if (exprKind === SK_Identifier) {
perComponentRefs!
.get(currentComponent!)!
.push((expr as ts.Identifier).text)
}
}
}
}
}
ts.forEachChild(node, visit)
if (isTypeLiteral) typeLiteralDepth--
if (entered) {
currentComponent = savedComponent
currentComponentTracked = savedTracked
}
}
ts.forEachChild(sourceFile, visit)
if (!perComponentFuncs) {
return jsxTags
}
for (const [name, funcs] of perComponentFuncs) {
if (componentsWithInlineFn!.has(name)) {
localComponents.get(name)!.kind = 'client'
continue
}
const refs = perComponentRefs!.get(name)!
let hasClientRef = false
for (let i = 0; i < refs.length; i++) {
if (funcs.get(refs[i]!) === false) {
hasClientRef = true
break
}
}
if (hasClientRef) {
localComponents.get(name)!.kind = 'client'
}
}
return jsxTags
}
function createJsxTagReference(
node: ts.JsxOpeningElement | ts.JsxSelfClosingElement | ts.JsxClosingElement,
sourceFile: ts.SourceFile,
nodeKind: ts.SyntaxKind,
): JsxTagReference | undefined {
const tagNameExpression = node.tagName
const tagKind = tagNameExpression.kind
if (tagKind === SK_Identifier) {
const text = (tagNameExpression as ts.Identifier).text
if (!isComponentIdentifier(text)) {
return undefined
}
return {
lookupName: text,
ranges: getTagRanges(node, tagNameExpression, sourceFile, nodeKind),
tagName: text,
}
}
if (tagKind !== SK_PropertyAccess) {