-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathts.go
More file actions
1529 lines (1394 loc) · 46.8 KB
/
Copy pathts.go
File metadata and controls
1529 lines (1394 loc) · 46.8 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
package tsextractor
import (
"context"
"encoding/json"
"log"
"os"
"path/filepath"
"strings"
"github.com/enola-labs/enola/internal/facts"
"github.com/enola-labs/enola/internal/parallel"
sitter "github.com/tree-sitter/go-tree-sitter"
typescript "github.com/tree-sitter/tree-sitter-typescript/bindings/go"
)
// TSExtractor extracts architectural facts from TypeScript/TSX source code using tree-sitter.
type TSExtractor struct{}
// New creates a new TSExtractor.
func New() *TSExtractor {
return &TSExtractor{}
}
func (e *TSExtractor) Name() string {
return "typescript"
}
// Detect returns true if the repository (or one of its immediate subdirectories
// in the case of a monorepo) contains TypeScript markers.
func (e *TSExtractor) Detect(repoPath string) (bool, error) {
_, found := findTSRoot(repoPath)
return found, nil
}
// findTSRoot returns the directory that is the TypeScript project root, along
// with a boolean indicating whether one was found. Search depth adapts to
// repo structure: Java/Gradle projects nest UI code deep (src/main/resources/ui)
// so we search up to 8 levels; plain repos need at most 2.
func findTSRoot(repoPath string) (string, bool) {
if hasTSMarkers(repoPath) {
return repoPath, true
}
maxDepth := 2
if isDeepNestedProject(repoPath) {
maxDepth = 8
}
return searchTSRoot(repoPath, 0, maxDepth)
}
func isDeepNestedProject(repoPath string) bool {
markers := []string{
"pom.xml", "build.gradle", "build.gradle.kts",
"pyproject.toml", "setup.py", "setup.cfg", "requirements.txt",
}
for _, marker := range markers {
if _, err := os.Stat(filepath.Join(repoPath, marker)); err == nil {
return true
}
}
return false
}
var tsSkipDirs = map[string]bool{
"node_modules": true, "dist": true, ".next": true,
"build": true, "out": true, "target": true, "vendor": true,
}
func searchTSRoot(dir string, depth, maxDepth int) (string, bool) {
if depth >= maxDepth {
return "", false
}
entries, err := os.ReadDir(dir)
if err != nil {
return "", false
}
for _, entry := range entries {
if !entry.IsDir() || strings.HasPrefix(entry.Name(), ".") || tsSkipDirs[entry.Name()] {
continue
}
sub := filepath.Join(dir, entry.Name())
if hasTSMarkers(sub) {
return sub, true
}
if found, ok := searchTSRoot(sub, depth+1, maxDepth); ok {
return found, true
}
}
return "", false
}
// hasTSMarkers returns true if the directory looks like a project root this
// extractor should handle (TypeScript, or a JS framework it also parses).
func hasTSMarkers(dir string) bool {
// tsconfig.json (standard) or tsconfig.base.json (Nx monorepo)
for _, name := range []string{"tsconfig.json", "tsconfig.base.json"} {
if _, err := os.Stat(filepath.Join(dir, name)); err == nil {
return true
}
}
for _, pkg := range []string{"typescript", "vue", "react", "svelte", "next", "nuxt"} {
if hasPkgDependency(dir, pkg) {
return true
}
}
return false
}
// Extract parses TypeScript/TSX files and emits architectural facts.
func (e *TSExtractor) Extract(ctx context.Context, repoPath string, files []string) ([]facts.Fact, error) {
var allFacts []facts.Fact
// Detect frameworks
isNextJS := detectNextJS(repoPath)
isVue := detectVue(repoPath)
isNuxt := detectNuxt(repoPath)
isSvelteKit := detectSvelteKit(repoPath)
// Parse tsconfig.json path aliases, one root per package for monorepos.
aliasRoots := collectTSAliasRoots(repoPath)
// SvelteKit maps $lib → src/lib by convention.
if isSvelteKit {
aliasRoots = withSvelteKitLibDefault(aliasRoots)
}
// Restrict to TypeScript files once, then parse them in parallel. The
// framework flags and path aliases above are read-only, and extractFile is a
// pure function of (src, relFile, …), so per-file work is independent. Results
// are merged in file order for deterministic output.
var tsFiles []string
for _, relFile := range files {
if isTypeScriptFile(relFile) {
tsFiles = append(tsFiles, relFile)
}
}
perFileFacts := parallel.MapFiles(ctx, tsFiles, func(relFile string) []facts.Fact {
src, err := os.ReadFile(filepath.Join(repoPath, relFile))
if err != nil {
log.Printf("[ts-extractor] error reading %s: %v", relFile, err)
return nil
}
aliases := aliasesForDir(aliasRoots, filepath.Dir(relFile))
return e.extractFile(src, relFile, isNextJS, isVue, isNuxt, isSvelteKit, aliases)
})
// Group files by directory for module detection
modules := make(map[string]bool)
for i, fileFacts := range perFileFacts {
allFacts = append(allFacts, fileFacts...)
modules[filepath.Dir(tsFiles[i])] = true
}
// Emit module facts for each directory
for dir := range modules {
allFacts = append(allFacts, facts.Fact{
Kind: facts.KindModule,
Name: dir,
File: dir,
Props: map[string]any{
"language": "typescript",
},
})
}
return allFacts, nil
}
// extractCtx bundles the per-file state threaded through declaration extraction
// so symbols can be enriched with React/Next.js semantic classification.
type extractCtx struct {
src []byte
relFile string
dir string
isTSX bool
isNextJS bool
isVue bool
isNuxt bool
importMap map[string]string
}
func (e *TSExtractor) extractFile(src []byte, relFile string, isNextJS, isVue, isNuxt, isSvelteKit bool, aliases map[string]string) []facts.Fact {
if isVueFile(relFile) {
return e.extractVueSFC(src, relFile, isNuxt, aliases)
}
if isSvelteFile(relFile) {
return e.extractSvelteSFC(src, relFile, isSvelteKit, aliases)
}
var result []facts.Fact
// Parse openapi-typescript generated files for backend API route dependencies.
// These are client-role route facts showing which backend routes the TS code calls.
if openapiRoutes := extractOpenAPITypescriptFacts(src, relFile); len(openapiRoutes) > 0 {
result = append(result, openapiRoutes...)
}
// Hand-written fetch / makeRequest API calls are also client-role routes.
result = append(result, extractHTTPClientFacts(src, relFile)...)
isTSX := strings.HasSuffix(relFile, ".tsx") || strings.HasSuffix(relFile, ".jsx")
lang := typescript.LanguageTypescript()
if isTSX {
lang = typescript.LanguageTSX()
}
parser := sitter.NewParser()
defer parser.Close()
if err := parser.SetLanguage(sitter.NewLanguage(lang)); err != nil {
return result
}
tree := parser.Parse(src, nil)
defer tree.Close()
root := tree.RootNode()
// Extract from the tree
result = append(result, e.extractImports(root, src, relFile, aliases)...)
ctx := &extractCtx{
src: src,
relFile: relFile,
dir: filepath.Dir(relFile),
isTSX: isTSX,
isNextJS: isNextJS,
isVue: isVue,
isNuxt: isNuxt,
importMap: buildImportSymbols(root, src, relFile, aliases),
}
decls := e.extractDeclarations(root, ctx)
// A declaration may be exported via a separate `export { A, B }` clause or
// `export default Name` statement rather than an inline `export` keyword.
// Mark the corresponding symbols as exported.
if exported := collectExportedLocalNames(root, src); len(exported) > 0 {
for i := range decls {
if decls[i].Kind != facts.KindSymbol {
continue
}
local := decls[i].Name[strings.LastIndexByte(decls[i].Name, '.')+1:]
if exported[local] {
decls[i].Props["exported"] = true
}
}
}
result = append(result, decls...)
// Detect Next.js routes
if isNextJS {
if routeFact := detectRoute(relFile); routeFact != nil {
result = append(result, *routeFact)
}
}
// Detect Vue Router configuration files
if (isVue || isNuxt) && containsCreateRouterCall(root, src) {
result = append(result, facts.Fact{
Kind: facts.KindRoute,
Name: relFile,
File: relFile,
Line: 1,
Props: map[string]any{
"type": "router_config",
"language": "typescript",
"framework": "vue",
},
})
}
return result
}
func (e *TSExtractor) extractImports(root *sitter.Node, src []byte, relFile string, aliases map[string]string) []facts.Fact {
var result []facts.Fact
dir := filepath.Dir(relFile)
for i := range root.ChildCount() {
child := root.Child(i)
// export_statement only has a "source" field for re-exports
// (export * from / export { X } from), not local declarations.
var source *sitter.Node
isReexport := false
switch child.Kind() {
case "import_statement":
source = findChildByKind(child, "string")
case "export_statement":
source = child.ChildByFieldName("source")
isReexport = true
default:
continue
}
if source == nil {
continue
}
importPath := strings.Trim(nodeText(source, src), `"'`)
// Resolve path aliases and relative imports to filesystem-relative paths
resolved, isExternal := resolveImportPath(importPath, dir, aliases)
importSource := "internal"
if isExternal {
importSource = "external"
}
props := map[string]any{
"language": "typescript",
"source": importSource,
}
if isReexport {
props["reexport"] = true
}
result = append(result, facts.Fact{
Kind: facts.KindDependency,
Name: dir + " -> " + resolved,
File: relFile,
Line: int(child.StartPosition().Row) + 1,
Props: props,
Relations: []facts.Relation{
{Kind: facts.RelImports, Target: resolved},
},
})
}
return result
}
func (e *TSExtractor) extractDeclarations(root *sitter.Node, ctx *extractCtx) []facts.Fact {
var result []facts.Fact
for i := range root.ChildCount() {
result = append(result, e.extractNode(root.Child(i), ctx, false, "")...)
}
return result
}
// extractNode emits facts for a single declaration node. fallbackName supplies a
// name for anonymous default-exported declarations (e.g. `export default function
// () {}`), derived from the file name; it is ignored when the declaration has its
// own name.
func (e *TSExtractor) extractNode(node *sitter.Node, ctx *extractCtx, isExported bool, fallbackName string) []facts.Fact {
var result []facts.Fact
src, dir, relFile := ctx.src, ctx.dir, ctx.relFile
switch node.Kind() {
case "export_statement":
isDefault := hasChildKind(node, "default")
fb := ""
if isDefault {
fb = fileSymbolName(relFile)
}
// Named/inline declaration inside the export.
if decl := firstDeclChild(node); decl != nil {
return e.extractNode(decl, ctx, true, fb)
}
// Anonymous default export of a value: name it after the file.
if isDefault {
for _, k := range []string{"function_expression", "generator_function", "class", "arrow_function", "call_expression"} {
if c := findChildByKind(node, k); c != nil {
return e.extractNode(c, ctx, true, fb)
}
}
}
case "function_declaration", "function_expression", "generator_function_declaration", "generator_function":
name := findChildByKind(node, "identifier")
symbolName := fallbackName
if name != nil {
symbolName = nodeText(name, src)
}
if symbolName == "" {
break
}
result = append(result, e.funcSymbol(node, node, ctx, symbolName, isExported))
case "arrow_function":
if fallbackName != "" {
result = append(result, e.funcSymbol(node, node, ctx, fallbackName, isExported))
}
case "call_expression":
// Reached for `export default memo(...)` / `forwardRef(...)`.
if fallbackName != "" {
result = append(result, e.funcSymbol(node, node, ctx, fallbackName, isExported))
}
case "class_declaration", "abstract_class_declaration", "class":
name := findChildByKind(node, "type_identifier")
symbolName := fallbackName
if name != nil {
symbolName = nodeText(name, src)
}
if symbolName == "" {
break
}
f := facts.Fact{
Kind: facts.KindSymbol,
Name: dir + "." + symbolName,
File: relFile,
Line: int(node.StartPosition().Row) + 1,
Props: map[string]any{
"symbol_kind": facts.SymbolClass,
"exported": isExported,
"language": "typescript",
},
Relations: []facts.Relation{
{Kind: facts.RelDeclares, Target: dir},
},
}
// Check for implements clause (nested under class_heritage)
for j := range node.ChildCount() {
c := node.Child(j)
if c.Kind() == "class_heritage" {
for k := range c.ChildCount() {
heritage := c.Child(k)
if heritage.Kind() == "implements_clause" {
for l := range heritage.ChildCount() {
t := heritage.Child(l)
if t.Kind() == "type_identifier" {
f.Relations = append(f.Relations, facts.Relation{
Kind: facts.RelImplements,
Target: nodeText(t, src),
})
}
}
}
}
}
}
classBody := findChildByKind(node, "class_body")
classifySymbol(&f, symbolName, classBody, ctx, facts.SymbolClass)
result = append(result, f)
// Extract class methods
if classBody != nil {
for j := range classBody.ChildCount() {
member := classBody.Child(j)
if member.Kind() != "method_definition" && member.Kind() != "public_field_definition" {
continue
}
methodName := findChildByKind(member, "property_identifier")
if methodName == nil {
methodName = findChildByKind(member, "identifier")
}
if methodName == nil {
continue
}
mName := nodeText(methodName, src)
if strings.HasPrefix(mName, "#") || mName == "constructor" {
continue
}
isPrivate := false
for k := range member.ChildCount() {
c := member.Child(k)
if c.Kind() == "accessibility_modifier" && nodeText(c, src) == "private" {
isPrivate = true
break
}
}
mRels := []facts.Relation{{Kind: facts.RelDeclares, Target: dir}}
callRels, m := collectCallsWithMetrics(member, src, dir, symbolName, ctx.importMap, dir+"."+symbolName+"."+mName, mName)
mRels = append(mRels, callRels...)
mProps := map[string]any{
"symbol_kind": facts.SymbolMethod,
"exported": isExported && !isPrivate,
"language": "typescript",
"receiver": symbolName,
}
applyTSMetrics(mProps, m)
result = append(result, facts.Fact{
Kind: facts.KindSymbol,
Name: dir + "." + symbolName + "." + mName,
File: relFile,
Line: int(member.StartPosition().Row) + 1,
Props: mProps,
Relations: mRels,
})
}
}
case "interface_declaration":
if name := findChildByKind(node, "type_identifier"); name != nil {
result = append(result, e.simpleSymbol(node, ctx, nodeText(name, src), facts.SymbolInterface, isExported))
}
case "type_alias_declaration":
if name := findChildByKind(node, "type_identifier"); name != nil {
result = append(result, e.simpleSymbol(node, ctx, nodeText(name, src), facts.SymbolType, isExported))
}
case "enum_declaration":
name := findChildByKind(node, "identifier")
if name == nil {
name = findChildByKind(node, "type_identifier")
}
if name != nil {
result = append(result, e.simpleSymbol(node, ctx, nodeText(name, src), facts.SymbolEnum, isExported))
}
case "internal_module", "module":
// TypeScript `namespace X {}` / `module X {}`.
name := findChildByKind(node, "identifier")
if name == nil {
name = findChildByKind(node, "nested_identifier")
}
if name != nil {
result = append(result, e.simpleSymbol(node, ctx, nodeText(name, src), "namespace", isExported))
}
case "lexical_declaration", "variable_declaration":
for j := range node.ChildCount() {
decl := node.Child(j)
if decl.Kind() != "variable_declarator" {
continue
}
name := findChildByKind(decl, "identifier")
if name == nil {
continue
}
symbolName := nodeText(name, src)
// Determine the value node and the symbol kind. Arrow functions and
// memo/forwardRef-wrapped values are functions/components; everything
// else is a plain variable.
symbolKind := facts.SymbolVariable
var body *sitter.Node
if v := findChildByKind(decl, "arrow_function"); v != nil {
symbolKind = facts.SymbolFunc
body = v
} else if call := findChildByKind(decl, "call_expression"); call != nil && isComponentWrapper(call, src) {
symbolKind = facts.SymbolFunc
body = call
}
vRels := []facts.Relation{{Kind: facts.RelDeclares, Target: dir}}
var vMetrics *tsBodyMetrics
if body != nil {
callRels, m := collectCallsWithMetrics(body, src, dir, "", ctx.importMap, dir+"."+symbolName, symbolName)
vRels = append(vRels, callRels...)
vMetrics = m
}
f := facts.Fact{
Kind: facts.KindSymbol,
Name: dir + "." + symbolName,
File: relFile,
Line: int(node.StartPosition().Row) + 1,
Props: map[string]any{
"symbol_kind": symbolKind,
"exported": isExported,
"language": "typescript",
},
Relations: vRels,
}
if symbolKind == facts.SymbolFunc {
applyTSMetrics(f.Props, vMetrics)
}
classifySymbol(&f, symbolName, body, ctx, symbolKind)
result = append(result, f)
}
}
return result
}
// funcSymbol builds a function/component symbol fact. declNode supplies the source
// location; body is walked for outgoing calls and JSX-based classification.
func (e *TSExtractor) funcSymbol(declNode, body *sitter.Node, ctx *extractCtx, name string, exported bool) facts.Fact {
rels := []facts.Relation{{Kind: facts.RelDeclares, Target: ctx.dir}}
callRels, m := collectCallsWithMetrics(body, ctx.src, ctx.dir, "", ctx.importMap, ctx.dir+"."+name, name)
rels = append(rels, callRels...)
f := facts.Fact{
Kind: facts.KindSymbol,
Name: ctx.dir + "." + name,
File: ctx.relFile,
Line: int(declNode.StartPosition().Row) + 1,
Props: map[string]any{
"symbol_kind": facts.SymbolFunc,
"exported": exported,
"language": "typescript",
},
Relations: rels,
}
applyTSMetrics(f.Props, m)
classifySymbol(&f, name, body, ctx, facts.SymbolFunc)
return f
}
// simpleSymbol builds a declaration-only symbol fact (interface, type, enum, namespace).
func (e *TSExtractor) simpleSymbol(node *sitter.Node, ctx *extractCtx, name, kind string, exported bool) facts.Fact {
f := facts.Fact{
Kind: facts.KindSymbol,
Name: ctx.dir + "." + name,
File: ctx.relFile,
Line: int(node.StartPosition().Row) + 1,
Props: map[string]any{
"symbol_kind": kind,
"exported": exported,
"language": "typescript",
},
Relations: []facts.Relation{{Kind: facts.RelDeclares, Target: ctx.dir}},
}
return f
}
// detectRoute checks if a file path corresponds to a Next.js route.
func detectRoute(relFile string) *facts.Fact {
// Next.js App Router: app/**/page.tsx, app/**/route.tsx
// Next.js Pages Router: pages/**/*.tsx
parts := strings.Split(filepath.ToSlash(relFile), "/")
// App Router
for i, p := range parts {
if p == "app" && i < len(parts)-1 {
fileName := parts[len(parts)-1]
baseName := strings.TrimSuffix(strings.TrimSuffix(fileName, ".tsx"), ".ts")
if baseName == "page" || baseName == "route" || baseName == "layout" || baseName == "loading" || baseName == "error" {
// Strip Next.js route groups — directory segments wrapped in ()
// that act as layout organizers without affecting the URL.
// e.g. (standard), (client-data), (header) → removed from path.
segParts := parts[i+1 : len(parts)-1]
urlParts := make([]string, 0, len(segParts))
for _, seg := range segParts {
if len(seg) >= 2 && seg[0] == '(' && seg[len(seg)-1] == ')' {
continue // route group — not part of the URL
}
urlParts = append(urlParts, seg)
}
routePath := "/" + strings.Join(urlParts, "/")
if routePath == "/" {
routePath = "/"
}
method := "GET"
if baseName == "route" {
method = "ALL" // API route handler
}
return &facts.Fact{
Kind: facts.KindRoute,
Name: routePath,
File: relFile,
Line: 1,
Props: map[string]any{
"method": method,
"type": baseName,
"router": "app",
"language": "typescript",
"framework": "nextjs",
},
}
}
}
}
// Pages Router
for i, p := range parts {
if p == "pages" && i < len(parts)-1 {
remaining := parts[i+1:]
fileName := remaining[len(remaining)-1]
baseName := strings.TrimSuffix(strings.TrimSuffix(fileName, ".tsx"), ".ts")
// Skip _app, _document, _error
if strings.HasPrefix(baseName, "_") {
return nil
}
routeParts := make([]string, 0, len(remaining))
for j, rp := range remaining {
if j == len(remaining)-1 {
if baseName != "index" {
routeParts = append(routeParts, baseName)
}
} else {
routeParts = append(routeParts, rp)
}
}
routePath := "/" + strings.Join(routeParts, "/")
// Detect API routes
isAPI := len(remaining) > 0 && remaining[0] == "api"
method := "GET"
if isAPI {
method = "ALL"
}
return &facts.Fact{
Kind: facts.KindRoute,
Name: routePath,
File: relFile,
Line: 1,
Props: map[string]any{
"method": method,
"type": "page",
"router": "pages",
"language": "typescript",
"framework": "nextjs",
},
}
}
}
return nil
}
// detectNextJS checks if the repository is a Next.js project.
// It searches the TypeScript root directory (which may be a subdirectory in a
// monorepo) for next.config.* files or a package.json with a "next" dependency.
func detectNextJS(repoPath string) bool {
tsRoot, _ := findTSRoot(repoPath)
return detectNextJSAt(tsRoot) || (tsRoot != repoPath && detectNextJSAt(repoPath))
}
func detectNextJSAt(dir string) bool {
// Check next.config.* at this directory level
for _, name := range []string{"next.config.js", "next.config.mjs", "next.config.ts"} {
if _, err := os.Stat(filepath.Join(dir, name)); err == nil {
return true
}
}
// Check package.json for next dependency
data, err := os.ReadFile(filepath.Join(dir, "package.json"))
if err != nil {
return false
}
var pkg map[string]any
if err := json.Unmarshal(data, &pkg); err != nil {
return false
}
for _, key := range []string{"dependencies", "devDependencies"} {
if deps, ok := pkg[key].(map[string]any); ok {
if _, ok := deps["next"]; ok {
return true
}
}
}
return false
}
func isTypeScriptFile(path string) bool {
ext := strings.ToLower(filepath.Ext(path))
return ext == ".ts" || ext == ".tsx" || ext == ".vue" || ext == ".js" || ext == ".jsx" || ext == ".svelte"
}
// OwnsFile implements plugin.FileOwner for incremental caching.
func (e *TSExtractor) OwnsFile(relFile string) bool { return isTypeScriptFile(relFile) }
// hasChildKind reports whether node has a direct child of the given kind.
func hasChildKind(node *sitter.Node, kind string) bool {
return findChildByKind(node, kind) != nil
}
// firstDeclChild returns the first named declaration child of an export_statement,
// or nil if the export wraps something else (a value, re-export clause, etc.).
func firstDeclChild(node *sitter.Node) *sitter.Node {
for _, k := range []string{
"function_declaration", "generator_function_declaration",
"class_declaration", "abstract_class_declaration",
"interface_declaration", "type_alias_declaration",
"lexical_declaration", "variable_declaration",
"enum_declaration", "internal_module", "module",
} {
if c := findChildByKind(node, k); c != nil {
return c
}
}
return nil
}
// fileSymbolName derives a symbol name from a file path for anonymous default
// exports. Generic Next.js filenames (page, route, layout, …) are disambiguated
// with their parent directory segment, e.g. app/dashboard/page.tsx → "DashboardPage".
func fileSymbolName(relFile string) string {
base := filepath.Base(relFile)
base = strings.TrimSuffix(base, filepath.Ext(base))
switch base {
case "index", "page", "route", "layout", "loading", "error", "not-found", "template", "default",
"+page", "+layout", "+error", "+server":
parent := filepath.Base(filepath.Dir(relFile))
if parent != "" && parent != "." && parent != string(filepath.Separator) {
return toPascal(parent) + toPascal(base)
}
}
return toPascal(base)
}
// toPascal converts an arbitrary identifier-ish string into PascalCase, splitting
// on any non-alphanumeric characters (e.g. "my-component" → "MyComponent").
func toPascal(s string) string {
var b strings.Builder
upNext := true
for _, r := range s {
switch {
case (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9'):
if upNext && r >= 'a' && r <= 'z' {
r -= 'a' - 'A'
}
b.WriteRune(r)
upNext = false
default:
upNext = true
}
}
return b.String()
}
// collectExportedLocalNames returns the set of locally-declared names that are
// exported via a separate `export { A, B as C }` clause or `export default Name`
// statement (where the declaration itself carries no inline export keyword).
func collectExportedLocalNames(root *sitter.Node, src []byte) map[string]bool {
out := make(map[string]bool)
for i := range root.ChildCount() {
child := root.Child(i)
if child.Kind() != "export_statement" {
continue
}
// export { A, B as C }
if clause := findChildByKind(child, "export_clause"); clause != nil {
for j := range clause.ChildCount() {
spec := clause.Child(j)
if spec.Kind() != "export_specifier" {
continue
}
if n := spec.ChildByFieldName("name"); n != nil {
out[nodeText(n, src)] = true
}
}
continue
}
// export default Name
if hasChildKind(child, "default") {
if id := findChildByKind(child, "identifier"); id != nil {
out[nodeText(id, src)] = true
}
}
}
return out
}
// reactHTTPMethods are the App Router route-handler export names.
var reactHTTPMethods = map[string]bool{
"GET": true, "POST": true, "PUT": true, "DELETE": true,
"PATCH": true, "HEAD": true, "OPTIONS": true,
}
// classifySymbol enriches a symbol fact with React/Next.js semantic props
// (web_component, framework, and for route handlers method), mirroring the
// ios_component/framework classification used by the Swift extractor. body, when
// non-nil, is scanned for JSX to confirm component-ness in non-TSX files.
func classifySymbol(f *facts.Fact, name string, body *sitter.Node, ctx *extractCtx, symbolKind string) {
// Next.js App Router route handler: GET/POST/... in a route.{ts,tsx} file.
if symbolKind == facts.SymbolFunc && reactHTTPMethods[name] && isAppRouteFile(ctx.relFile) {
f.Props["web_component"] = "route_handler"
f.Props["method"] = name
f.Props["framework"] = "nextjs"
return
}
// Composable (Vue/Nuxt) or hook (React): a useXxx function.
if symbolKind == facts.SymbolFunc && isHookName(name) {
if ctx.isVue || ctx.isNuxt {
f.Props["web_component"] = "composable"
if ctx.isNuxt {
f.Props["framework"] = "nuxt"
} else {
f.Props["framework"] = "vue"
}
} else {
f.Props["web_component"] = "hook"
f.Props["framework"] = "react"
}
return
}
// React component: a PascalCase function/class that renders JSX. In .tsx/.jsx
// files a PascalCase function/class is treated as a component; elsewhere we
// require literal JSX in the body to avoid misclassifying plain classes.
if isComponentName(name) && (symbolKind == facts.SymbolFunc || symbolKind == facts.SymbolClass) {
if ctx.isTSX || (body != nil && containsJSX(body)) {
f.Props["web_component"] = "component"
if ctx.isNextJS {
f.Props["framework"] = "nextjs"
} else {
f.Props["framework"] = "react"
}
}
}
}
// isHookName reports whether name follows the React hook convention useXxx.
func isHookName(name string) bool {
if !strings.HasPrefix(name, "use") || len(name) < 4 {
return false
}
c := name[3]
return c >= 'A' && c <= 'Z'
}
// isComponentName reports whether name is PascalCase (a React component convention).
func isComponentName(name string) bool {
return name != "" && name[0] >= 'A' && name[0] <= 'Z'
}
// isAppRouteFile reports whether relFile is a Next.js App Router route handler
// file (a route.{ts,tsx} under an "app" directory segment).
func isAppRouteFile(relFile string) bool {
base := filepath.Base(relFile)
base = strings.TrimSuffix(strings.TrimSuffix(base, ".tsx"), ".ts")
if base != "route" {
return false
}
for _, seg := range strings.Split(filepath.ToSlash(relFile), "/") {
if seg == "app" {
return true
}
}
return false
}
// containsJSX reports whether the subtree rooted at node contains a JSX element.
func containsJSX(node *sitter.Node) bool {
if node == nil {
return false
}
switch node.Kind() {
case "jsx_element", "jsx_self_closing_element", "jsx_fragment":
return true
}
for i := range node.ChildCount() {
if containsJSX(node.Child(i)) {
return true
}
}
return false
}
// isComponentWrapper reports whether a call expression wraps a component, i.e. it
// calls memo / forwardRef (optionally as React.memo / React.forwardRef).
func isComponentWrapper(call *sitter.Node, src []byte) bool {
fn := call.ChildByFieldName("function")
if fn == nil {
return false
}
name := ""
switch fn.Kind() {
case "identifier":
name = nodeText(fn, src)
case "member_expression":
if prop := fn.ChildByFieldName("property"); prop != nil {
name = nodeText(prop, src)
}
}
return name == "memo" || name == "forwardRef"
}
func findChildByKind(node *sitter.Node, kind string) *sitter.Node {
for i := range node.ChildCount() {
child := node.Child(i)
if child.Kind() == kind {
return child
}
}
return nil
}
func nodeText(node *sitter.Node, src []byte) string {
return string(src[node.StartByte():node.EndByte()])
}
// tsAliasRoot is a directory (repoPath-relative, "" = root) and the alias
// map its tsconfig declares, already qualified with dir as a prefix.
type tsAliasRoot struct {
dir string
aliases map[string]string
}
// collectTSAliasRoots finds every directory whose tsconfig.json (or
// tsconfig.base.json) declares path aliases — unlike findTSRoot, which stops
// at the first match, this covers monorepos with one tsconfig per package.
func collectTSAliasRoots(repoPath string) []tsAliasRoot {
maxDepth := 2
if isDeepNestedProject(repoPath) {
maxDepth = 8
}
var roots []tsAliasRoot
walkTSAliasRoots(repoPath, repoPath, 0, maxDepth, &roots)
return roots
}
func walkTSAliasRoots(repoPath, dir string, depth, maxDepth int, out *[]tsAliasRoot) {
if aliases, ok := aliasesAtDir(dir); ok {