-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathindex.ts
More file actions
1147 lines (1023 loc) · 38.1 KB
/
index.ts
File metadata and controls
1147 lines (1023 loc) · 38.1 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
/**
* Angular Analyzer - Comprehensive Angular-specific code analysis
* Understands components, services, directives, pipes, modules, guards, interceptors, etc.
* Detects state management patterns, architectural layers, and Angular-specific patterns
*/
import { promises as fs } from 'fs';
import path from 'path';
import { parse } from '@typescript-eslint/typescript-estree';
import type { TSESTree } from '@typescript-eslint/typescript-estree';
import {
FrameworkAnalyzer,
AnalysisResult,
CodebaseMetadata,
CodeChunk,
CodeComponent,
ImportStatement,
ExportStatement,
ArchitecturalLayer,
DependencyCategory
} from '../../types/index.js';
import { createChunksFromCode } from '../../utils/chunking.js';
import {
CODEBASE_CONTEXT_DIRNAME,
KEYWORD_INDEX_FILENAME
} from '../../constants/codebase-context.js';
import { registerComplementaryPatterns } from '../../patterns/semantics.js';
interface AngularInput {
name: string;
type: string;
style: 'decorator' | 'signal';
required?: boolean;
}
interface AngularOutput {
name: string;
type: string;
style: 'decorator' | 'signal';
}
export class AngularAnalyzer implements FrameworkAnalyzer {
readonly name = 'angular';
readonly version = '1.0.0';
readonly supportedExtensions = ['.ts', '.js', '.html', '.scss', '.css', '.sass', '.less'];
readonly priority = 100; // Highest priority for Angular files
constructor() {
// Self-register Angular-specific complementary patterns.
// computed + effect are complementary, not conflicting.
registerComplementaryPatterns('reactivity', ['Computed', 'Effect']);
}
private angularPatterns = {
component: /@Component\s*\(/,
service: /@Injectable\s*\(/,
directive: /@Directive\s*\(/,
pipe: /@Pipe\s*\(/,
module: /@NgModule\s*\(/,
// Guards: Check for interface implementation OR method signature OR functional guard
guard:
/(?:implements\s+(?:CanActivate|CanDeactivate|CanLoad|CanMatch)|canActivate\s*\(|canDeactivate\s*\(|canLoad\s*\(|canMatch\s*\(|CanActivateFn|CanDeactivateFn|CanMatchFn)/,
interceptor: /(?:implements\s+HttpInterceptor|intercept\s*\(|HttpInterceptorFn)/,
resolver: /(?:implements\s+Resolve|resolve\s*\(|ResolveFn)/,
validator: /(?:implements\s+(?:Validator|AsyncValidator)|validate\s*\()/
};
private stateManagementPatterns = {
ngrx: /@ngrx\/store|createAction|createReducer|createSelector/,
akita: /@datorama\/akita|Query|Store\.update/,
elf: /@ngneat\/elf|createStore|withEntities/,
signals: /\bsignal\s*[<(]|\bcomputed\s*[<(]|\beffect\s*\(|\blinkedSignal\s*[<(]/,
rxjsState: /BehaviorSubject|ReplaySubject|shareReplay/
};
private modernAngularPatterns = {
signalInput: /\binput\s*[<(]|\binput\.required\s*[<(]/,
signalOutput: /\boutput\s*[<(]/,
signalModel: /\bmodel\s*[<(]|\bmodel\.required\s*[<(]/,
signalViewChild: /\bviewChild\s*[<(]|\bviewChild\.required\s*[<(]/,
signalViewChildren: /\bviewChildren\s*[<(]/,
signalContentChild: /\bcontentChild\s*[<(]|\bcontentChild\.required\s*[<(]/,
signalContentChildren: /\bcontentChildren\s*[<(]/,
controlFlowIf: /@if\s*\(/,
controlFlowFor: /@for\s*\(/,
controlFlowSwitch: /@switch\s*\(/,
controlFlowDefer: /@defer\s*[({]/,
injectFunction: /\binject\s*[<(]/
};
canAnalyze(filePath: string, content?: string): boolean {
const ext = path.extname(filePath).toLowerCase();
if (!this.supportedExtensions.includes(ext)) {
return false;
}
// For TypeScript files, check if it contains Angular decorators
if (ext === '.ts' && content) {
return Object.values(this.angularPatterns).some((pattern) => pattern.test(content));
}
// Angular component templates and styles
if (['.html', '.scss', '.css', '.sass', '.less'].includes(ext)) {
// Check if there's a corresponding .ts file
// const baseName = filePath.replace(/\.(html|scss|css|sass|less)$/, '');
return true; // We'll verify during analysis
}
return false;
}
async analyze(filePath: string, content: string): Promise<AnalysisResult> {
const ext = path.extname(filePath).toLowerCase();
const relativePath = path.relative(process.cwd(), filePath);
if (ext === '.ts') {
return this.analyzeTypeScriptFile(filePath, content, relativePath);
} else if (ext === '.html') {
return this.analyzeTemplateFile(filePath, content, relativePath);
} else if (['.scss', '.css', '.sass', '.less'].includes(ext)) {
return this.analyzeStyleFile(filePath, content, relativePath);
}
// Fallback
return {
filePath,
language: 'unknown',
framework: 'angular',
components: [],
imports: [],
exports: [],
dependencies: [],
metadata: {},
chunks: []
};
}
private async analyzeTypeScriptFile(
filePath: string,
content: string,
relativePath: string
): Promise<AnalysisResult> {
const components: CodeComponent[] = [];
const imports: ImportStatement[] = [];
const exports: ExportStatement[] = [];
const dependencies: string[] = [];
try {
const ast = parse(content, {
loc: true,
range: true,
comment: true
});
// Extract imports
for (const node of ast.body) {
if (node.type === 'ImportDeclaration' && node.source.value) {
const source = node.source.value as string;
imports.push({
source,
imports: node.specifiers.map((s: TSESTree.ImportClause) => {
if (s.type === 'ImportDefaultSpecifier') return 'default';
if (s.type === 'ImportNamespaceSpecifier') return '*';
const specifier = s as TSESTree.ImportSpecifier;
return specifier.imported.name || specifier.local.name;
}),
isDefault: node.specifiers.some((s: TSESTree.ImportClause) => s.type === 'ImportDefaultSpecifier'),
isDynamic: false,
line: node.loc?.start.line
});
// Track dependencies
if (!source.startsWith('.') && !source.startsWith('/')) {
dependencies.push(source.split('/')[0]);
}
}
// Extract class declarations with decorators
if (
node.type === 'ExportNamedDeclaration' &&
node.declaration?.type === 'ClassDeclaration'
) {
const classNode = node.declaration;
if (classNode.id && classNode.decorators) {
const component = await this.extractAngularComponent(classNode, content);
if (component) {
components.push(component);
}
}
}
// Handle direct class exports
if (node.type === 'ClassDeclaration' && node.id && node.decorators) {
const component = await this.extractAngularComponent(node, content);
if (component) {
components.push(component);
}
}
// Extract exports
if (node.type === 'ExportNamedDeclaration') {
if (node.declaration) {
if (node.declaration.type === 'ClassDeclaration' && node.declaration.id) {
exports.push({
name: node.declaration.id.name,
isDefault: false,
type: 'class'
});
}
}
}
if (node.type === 'ExportDefaultDeclaration') {
const name = node.declaration.type === 'Identifier' ? node.declaration.name : 'default';
exports.push({
name,
isDefault: true,
type: 'default'
});
}
}
} catch (error) {
console.warn(`Failed to parse Angular TypeScript file ${filePath}:`, error);
}
// Detect state management
const statePattern = this.detectStateManagement(content);
// Detect Angular v17+ modern patterns
const modernPatterns = this.detectModernAngularPatterns(content);
// Determine architectural layer
const layer = this.determineLayer(filePath, components);
// Create chunks with Angular-specific metadata
const chunks = await createChunksFromCode(
content,
filePath,
relativePath,
'typescript',
components,
{
framework: 'angular',
layer,
statePattern,
dependencies,
modernPatterns
}
);
// Build detected patterns for the indexer to forward
const detectedPatterns: Array<{ category: string; name: string }> = [];
// Dependency Injection pattern
if (modernPatterns.includes('injectFunction')) {
detectedPatterns.push({ category: 'dependencyInjection', name: 'inject() function' });
} else if (
content.includes('constructor(') &&
content.includes('private') &&
(relativePath.endsWith('.service.ts') || relativePath.endsWith('.component.ts'))
) {
detectedPatterns.push({ category: 'dependencyInjection', name: 'Constructor injection' });
}
// State Management pattern
if (/BehaviorSubject|ReplaySubject|Subject|Observable/.test(content)) {
detectedPatterns.push({ category: 'stateManagement', name: 'RxJS' });
}
if (modernPatterns.some((p) => p.startsWith('signal'))) {
detectedPatterns.push({ category: 'stateManagement', name: 'Signals' });
}
// Reactivity patterns
if (/\beffect\s*\(/.test(content)) {
detectedPatterns.push({ category: 'reactivity', name: 'Effect' });
}
if (/\bcomputed\s*[<(]/.test(content)) {
detectedPatterns.push({ category: 'reactivity', name: 'Computed' });
}
// Component Style pattern detection
// Logic: explicit standalone: true → Standalone
// explicit standalone: false → NgModule-based
// no explicit flag + uses modern patterns (inject, signals) → likely Standalone (Angular v19+ default)
// no explicit flag + no modern patterns → ambiguous, don't classify
const hasExplicitStandalone = content.includes('standalone: true');
const hasExplicitNgModule = content.includes('standalone: false');
const usesModernPatterns =
modernPatterns.includes('injectFunction') ||
modernPatterns.some((p) => p.startsWith('signal'));
if (
relativePath.endsWith('component.ts') ||
relativePath.endsWith('directive.ts') ||
relativePath.endsWith('pipe.ts')
) {
if (hasExplicitStandalone) {
detectedPatterns.push({ category: 'componentStyle', name: 'Standalone' });
} else if (hasExplicitNgModule) {
detectedPatterns.push({ category: 'componentStyle', name: 'NgModule-based' });
} else if (usesModernPatterns) {
// No explicit flag but uses modern patterns → likely v19+ standalone default
detectedPatterns.push({ category: 'componentStyle', name: 'Standalone' });
}
// If no explicit flag and no modern patterns, don't classify (ambiguous)
}
// Input style pattern
if (modernPatterns.includes('signalInput')) {
detectedPatterns.push({ category: 'componentInputs', name: 'Signal-based inputs' });
} else if (content.includes('@Input()')) {
detectedPatterns.push({ category: 'componentInputs', name: 'Decorator-based @Input' });
}
return {
filePath,
language: 'typescript',
framework: 'angular',
components,
imports,
exports,
dependencies: dependencies.map((name) => ({
name,
category: this.categorizeDependency(name),
layer
})),
metadata: {
analyzer: this.name,
layer,
statePattern,
modernPatterns,
// isStandalone: true if explicit standalone: true, or if uses modern patterns (implying v19+ default)
isStandalone:
content.includes('standalone: true') ||
(!content.includes('standalone: false') &&
(modernPatterns.includes('injectFunction') ||
modernPatterns.some((p) => p.startsWith('signal')))),
hasRoutes: content.includes('RouterModule') || content.includes('routes'),
usesSignals:
modernPatterns.length > 0 && modernPatterns.some((p) => p.startsWith('signal')),
usesControlFlow: modernPatterns.some((p) => p.startsWith('controlFlow')),
usesInject: modernPatterns.includes('injectFunction'),
usesRxJS: /BehaviorSubject|ReplaySubject|Subject|Observable/.test(content),
usesEffect: /\beffect\s*\(/.test(content),
usesComputed: /\bcomputed\s*[<(]/.test(content),
componentType: components.length > 0 ? components[0].metadata.angularType : undefined,
// NEW: Patterns for the indexer to forward generically
detectedPatterns
},
chunks
};
}
/**
* Detect Angular v17+ modern patterns in the code
*/
private detectModernAngularPatterns(content: string): string[] {
const detected: string[] = [];
for (const [patternName, regex] of Object.entries(this.modernAngularPatterns)) {
if (regex.test(content)) {
detected.push(patternName);
}
}
return detected;
}
private async extractAngularComponent(
classNode: TSESTree.ClassDeclaration,
content: string
): Promise<CodeComponent | null> {
if (!classNode.id || !classNode.decorators || classNode.decorators.length === 0) {
return null;
}
const decorator = classNode.decorators[0];
const expr = decorator.expression;
const decoratorName: string =
expr.type === 'CallExpression' && expr.callee.type === 'Identifier'
? expr.callee.name
: expr.type === 'Identifier'
? expr.name
: '';
let componentType: string | undefined;
let angularType: string | undefined;
// Determine Angular component type
if (decoratorName === 'Component') {
componentType = 'component';
angularType = 'component';
} else if (decoratorName === 'Directive') {
componentType = 'directive';
angularType = 'directive';
} else if (decoratorName === 'Pipe') {
componentType = 'pipe';
angularType = 'pipe';
} else if (decoratorName === 'NgModule') {
componentType = 'module';
angularType = 'module';
} else if (decoratorName === 'Injectable') {
// For @Injectable, check if it's actually a guard/interceptor/resolver/validator
// before defaulting to 'service'
const classContent = content.substring(classNode.range[0], classNode.range[1]);
if (this.angularPatterns.guard.test(classContent)) {
componentType = 'guard';
angularType = 'guard';
} else if (this.angularPatterns.interceptor.test(classContent)) {
componentType = 'interceptor';
angularType = 'interceptor';
} else if (this.angularPatterns.resolver.test(classContent)) {
componentType = 'resolver';
angularType = 'resolver';
} else if (this.angularPatterns.validator.test(classContent)) {
componentType = 'validator';
angularType = 'validator';
} else {
// Default to service if no specific pattern matches
componentType = 'service';
angularType = 'service';
}
}
// If still no type, check patterns one more time (for classes without decorators)
if (!componentType) {
const classContent = content.substring(classNode.range[0], classNode.range[1]);
if (this.angularPatterns.guard.test(classContent)) {
componentType = 'guard';
angularType = 'guard';
} else if (this.angularPatterns.interceptor.test(classContent)) {
componentType = 'interceptor';
angularType = 'interceptor';
} else if (this.angularPatterns.resolver.test(classContent)) {
componentType = 'resolver';
angularType = 'resolver';
} else if (this.angularPatterns.validator.test(classContent)) {
componentType = 'validator';
angularType = 'validator';
}
}
// Extract decorator metadata
const decoratorMetadata = this.extractDecoratorMetadata(decorator);
// Extract lifecycle hooks
const lifecycle = this.extractLifecycleHooks(classNode);
// Extract injected dependencies
const injectedServices = this.extractInjectedServices(classNode);
// Extract inputs and outputs
const inputs = this.extractInputs(classNode);
const outputs = this.extractOutputs(classNode);
return {
name: classNode.id.name,
type: 'class',
componentType,
startLine: classNode.loc.start.line,
endLine: classNode.loc.end.line,
decorators: [
{
name: decoratorName,
properties: decoratorMetadata
}
],
lifecycle,
dependencies: injectedServices,
properties: [...inputs, ...outputs],
metadata: {
angularType,
selector: decoratorMetadata.selector,
providedIn: decoratorMetadata.providedIn,
isStandalone: decoratorMetadata.standalone === true,
template: decoratorMetadata.template,
templateUrl: decoratorMetadata.templateUrl,
styleUrls: decoratorMetadata.styleUrls,
imports: decoratorMetadata.imports,
declarations: decoratorMetadata.declarations,
pipeName: decoratorMetadata.name,
inputs: inputs.map((i) => i.name),
outputs: outputs.map((o) => o.name)
}
};
}
private extractDecoratorMetadata(decorator: TSESTree.Decorator): Record<string, unknown> {
const metadata: Record<string, unknown> = {};
try {
if (decorator.expression.type === 'CallExpression' && decorator.expression.arguments[0]) {
const arg = decorator.expression.arguments[0];
if (arg.type === 'ObjectExpression') {
for (const prop of arg.properties) {
if (prop.type !== 'Property') continue;
const keyNode = prop.key as { name?: string; value?: unknown };
const key = keyNode.name ?? String(keyNode.value ?? '');
if (!key) continue;
if (prop.value.type === 'Literal') {
metadata[key] = prop.value.value;
} else if (prop.value.type === 'ArrayExpression') {
metadata[key] = prop.value.elements
.map((el) => (el && el.type === 'Literal' ? el.value : null))
.filter(Boolean);
} else if (prop.value.type === 'Identifier') {
metadata[key] = prop.value.name;
}
}
}
}
} catch (error) {
console.warn('Failed to extract decorator metadata:', error);
}
return metadata;
}
private extractLifecycleHooks(classNode: TSESTree.ClassDeclaration): string[] {
const hooks: string[] = [];
const lifecycleHooks = [
'ngOnChanges',
'ngOnInit',
'ngDoCheck',
'ngAfterContentInit',
'ngAfterContentChecked',
'ngAfterViewInit',
'ngAfterViewChecked',
'ngOnDestroy'
];
if (classNode.body && classNode.body.body) {
for (const member of classNode.body.body) {
if (member.type === 'MethodDefinition' && member.key && member.key.type === 'Identifier') {
const methodName = member.key.name;
if (lifecycleHooks.includes(methodName)) {
hooks.push(methodName);
}
}
}
}
return hooks;
}
private extractInjectedServices(classNode: TSESTree.ClassDeclaration): string[] {
const services: string[] = [];
// Look for constructor parameters
if (classNode.body && classNode.body.body) {
for (const member of classNode.body.body) {
if (member.type === 'MethodDefinition' && member.kind === 'constructor') {
if (member.value.params) {
for (const param of member.value.params) {
const typedParam = param as TSESTree.Identifier;
if (typedParam.typeAnnotation?.typeAnnotation?.type === 'TSTypeReference') {
const typeRef = typedParam.typeAnnotation.typeAnnotation as TSESTree.TSTypeReference;
if (typeRef.typeName.type === 'Identifier') {
services.push(typeRef.typeName.name);
}
}
}
}
}
}
}
return services;
}
private extractInputs(classNode: TSESTree.ClassDeclaration): AngularInput[] {
const inputs: AngularInput[] = [];
if (classNode.body && classNode.body.body) {
for (const member of classNode.body.body) {
if (member.type === 'PropertyDefinition') {
// Check for decorator-based @Input()
if (member.decorators) {
const hasInput = member.decorators.some((d: TSESTree.Decorator) => {
const expr = d.expression;
return (
(expr.type === 'CallExpression' &&
expr.callee.type === 'Identifier' &&
expr.callee.name === 'Input') ||
(expr.type === 'Identifier' && expr.name === 'Input')
);
});
if (hasInput && member.key && 'name' in member.key) {
inputs.push({
name: member.key.name,
type: (member.typeAnnotation?.typeAnnotation?.type as string | undefined) || 'unknown',
style: 'decorator'
});
}
}
// Check for signal-based input() (Angular v17.1+)
if (member.value && member.key && 'name' in member.key) {
const callee = member.value.type === 'CallExpression'
? (member.value.callee as { type: string; name?: string; object?: { name?: string }; property?: { name?: string } })
: null;
const valueStr = callee?.name ?? callee?.object?.name ?? null;
if (valueStr === 'input') {
inputs.push({
name: member.key.name,
type: 'InputSignal',
style: 'signal',
required: callee?.property?.name === 'required'
});
}
}
}
}
}
return inputs;
}
private extractOutputs(classNode: TSESTree.ClassDeclaration): AngularOutput[] {
const outputs: AngularOutput[] = [];
if (classNode.body && classNode.body.body) {
for (const member of classNode.body.body) {
if (member.type === 'PropertyDefinition') {
// Check for decorator-based @Output()
if (member.decorators) {
const hasOutput = member.decorators.some((d: TSESTree.Decorator) => {
const expr = d.expression;
return (
(expr.type === 'CallExpression' &&
expr.callee.type === 'Identifier' &&
expr.callee.name === 'Output') ||
(expr.type === 'Identifier' && expr.name === 'Output')
);
});
if (hasOutput && member.key && 'name' in member.key) {
outputs.push({
name: member.key.name,
type: 'EventEmitter',
style: 'decorator'
});
}
}
// Check for signal-based output() (Angular v17.1+)
if (member.value && member.key && 'name' in member.key) {
const callee = member.value.type === 'CallExpression'
? (member.value.callee as { type: string; name?: string })
: null;
const valueStr = callee?.name ?? null;
if (valueStr === 'output') {
outputs.push({
name: member.key.name,
type: 'OutputEmitterRef',
style: 'signal'
});
}
}
}
}
}
return outputs;
}
private async analyzeTemplateFile(
filePath: string,
content: string,
relativePath: string
): Promise<AnalysisResult> {
// Find corresponding component file
const componentPath = filePath.replace(/\.html$/, '.ts');
// Detect legacy vs modern control flow
const hasLegacyDirectives = /\*ng(?:If|For|Switch)/.test(content);
const hasModernControlFlow = /@(?:if|for|switch|defer)\s*[({]/.test(content);
return {
filePath,
language: 'html',
framework: 'angular',
components: [],
imports: [],
exports: [],
dependencies: [],
metadata: {
analyzer: this.name,
type: 'template',
componentPath,
hasLegacyDirectives,
hasModernControlFlow,
hasBindings: /\[|\(|{{/.test(content),
hasDefer: /@defer\s*[({]/.test(content)
},
chunks: await createChunksFromCode(content, filePath, relativePath, 'html', [])
};
}
private async analyzeStyleFile(
filePath: string,
content: string,
relativePath: string
): Promise<AnalysisResult> {
const ext = path.extname(filePath).toLowerCase();
const language = ext.substring(1); // Remove the dot
return {
filePath,
language,
framework: 'angular',
components: [],
imports: [],
exports: [],
dependencies: [],
metadata: {
analyzer: this.name,
type: 'style'
},
chunks: await createChunksFromCode(content, filePath, relativePath, language, [])
};
}
private detectStateManagement(content: string): string | undefined {
for (const [pattern, regex] of Object.entries(this.stateManagementPatterns)) {
if (regex.test(content)) {
return pattern;
}
}
return undefined;
}
private determineLayer(filePath: string, components: CodeComponent[]): ArchitecturalLayer {
const lowerPath = filePath.toLowerCase();
// Check path-based patterns
if (
lowerPath.includes('/component') ||
lowerPath.includes('/view') ||
lowerPath.includes('/page')
) {
return 'presentation';
}
if (lowerPath.includes('/service')) {
return 'business';
}
if (
lowerPath.includes('/data') ||
lowerPath.includes('/repository') ||
lowerPath.includes('/api')
) {
return 'data';
}
if (
lowerPath.includes('/store') ||
lowerPath.includes('/state') ||
lowerPath.includes('/ngrx')
) {
return 'state';
}
if (lowerPath.includes('/core')) {
return 'core';
}
if (lowerPath.includes('/shared')) {
return 'shared';
}
if (lowerPath.includes('/feature')) {
return 'feature';
}
// Check component types
for (const component of components) {
if (
component.componentType === 'component' ||
component.componentType === 'directive' ||
component.componentType === 'pipe'
) {
return 'presentation';
}
if (component.componentType === 'service') {
return lowerPath.includes('http') || lowerPath.includes('api') ? 'data' : 'business';
}
if (component.componentType === 'guard' || component.componentType === 'interceptor') {
return 'core';
}
}
return 'unknown';
}
private categorizeDependency(name: string): DependencyCategory {
if (name.startsWith('@angular/')) {
return 'framework';
}
if (name.includes('ngrx') || name.includes('akita') || name.includes('elf')) {
return 'state';
}
if (name.includes('material') || name.includes('primeng') || name.includes('ng-bootstrap')) {
return 'ui';
}
if (name.includes('router')) {
return 'routing';
}
if (name.includes('http') || name.includes('common/http')) {
return 'http';
}
if (
name.includes('test') ||
name.includes('jest') ||
name.includes('jasmine') ||
name.includes('karma')
) {
return 'testing';
}
return 'other';
}
async detectCodebaseMetadata(rootPath: string): Promise<CodebaseMetadata> {
const metadata: CodebaseMetadata = {
name: path.basename(rootPath),
rootPath,
languages: [],
dependencies: [],
architecture: {
type: 'feature-based',
layers: {
presentation: 0,
business: 0,
data: 0,
state: 0,
core: 0,
shared: 0,
feature: 0,
infrastructure: 0,
unknown: 0
},
patterns: []
},
styleGuides: [],
documentation: [],
projectStructure: {
type: 'single-app'
},
statistics: {
totalFiles: 0,
totalLines: 0,
totalComponents: 0,
componentsByType: {},
componentsByLayer: {
presentation: 0,
business: 0,
data: 0,
state: 0,
core: 0,
shared: 0,
feature: 0,
infrastructure: 0,
unknown: 0
}
},
customMetadata: {}
};
try {
// Read package.json
const packageJsonPath = path.join(rootPath, 'package.json');
const packageJson = JSON.parse(await fs.readFile(packageJsonPath, 'utf-8'));
metadata.name = packageJson.name || metadata.name;
// Extract Angular version and dependencies
const allDeps = {
...packageJson.dependencies,
...packageJson.devDependencies
};
const angularVersion = allDeps['@angular/core']?.replace(/[\^~]/, '') || 'unknown';
// Detect state management
const stateManagement: string[] = [];
if (allDeps['@ngrx/store']) stateManagement.push('ngrx');
if (allDeps['@datorama/akita']) stateManagement.push('akita');
if (allDeps['@ngneat/elf']) stateManagement.push('elf');
// Detect UI libraries
const uiLibraries: string[] = [];
if (allDeps['@angular/material']) uiLibraries.push('Angular Material');
if (allDeps['primeng']) uiLibraries.push('PrimeNG');
if (allDeps['@ng-bootstrap/ng-bootstrap']) uiLibraries.push('ng-bootstrap');
// Detect testing frameworks
const testingFrameworks: string[] = [];
if (allDeps['jasmine-core']) testingFrameworks.push('Jasmine');
if (allDeps['karma']) testingFrameworks.push('Karma');
if (allDeps['jest']) testingFrameworks.push('Jest');
metadata.framework = {
name: 'Angular',
version: angularVersion,
type: 'angular',
variant: 'unknown', // Will be determined during analysis
stateManagement,
uiLibraries,
testingFrameworks
};
// Convert dependencies
metadata.dependencies = Object.entries(allDeps).map(([name, version]) => ({
name,
version: version as string,
category: this.categorizeDependency(name)
}));
} catch (error) {
console.warn('Failed to read Angular project metadata:', error);
}
// Calculate statistics from existing index if available
try {
const indexPath = path.join(rootPath, CODEBASE_CONTEXT_DIRNAME, KEYWORD_INDEX_FILENAME);
const indexContent = await fs.readFile(indexPath, 'utf-8');
const parsed = JSON.parse(indexContent) as unknown;
// Legacy index.json is an array — do not consume it (missing version/meta headers).
if (Array.isArray(parsed)) {
return metadata;
}
const parsedObj = parsed as { chunks?: unknown };
const chunks = parsedObj && Array.isArray(parsedObj.chunks) ? (parsedObj.chunks as Array<{ filePath?: string; startLine?: number; endLine?: number; componentType?: string; layer?: string }>) : null;
if (Array.isArray(chunks) && chunks.length > 0) {
console.error(`Loading statistics from ${indexPath}: ${chunks.length} chunks`);
metadata.statistics.totalFiles = new Set(chunks.map((c) => c.filePath)).size;
metadata.statistics.totalLines = chunks.reduce(
(sum, c) => sum + ((c.endLine ?? 0) - (c.startLine ?? 0) + 1),
0
);
// Count components by type
const componentCounts: Record<string, number> = {};
const layerCounts: Record<string, number> = {
presentation: 0,
business: 0,
data: 0,
state: 0,
core: 0,
shared: 0,
feature: 0,
infrastructure: 0,
unknown: 0
};
for (const chunk of chunks) {
if (chunk.componentType) {
componentCounts[chunk.componentType] = (componentCounts[chunk.componentType] || 0) + 1;
metadata.statistics.totalComponents++;
}
if (chunk.layer) {
layerCounts[chunk.layer as keyof typeof layerCounts] =
(layerCounts[chunk.layer as keyof typeof layerCounts] || 0) + 1;
}
}
metadata.statistics.componentsByType = componentCounts;
metadata.statistics.componentsByLayer = layerCounts;
metadata.architecture.layers = layerCounts;
}
} catch (error) {
// Index doesn't exist yet, keep statistics at 0
console.warn('Failed to calculate statistics from index:', error);
}
return metadata;
}
/**
* Generate Angular-specific summary for a code chunk
*/
summarize(chunk: CodeChunk): string {
const { componentType, metadata, content } = chunk;
const fileName = path.basename(chunk.filePath);
// Extract class/component name
const classMatch = content.match(/(?:export\s+)?class\s+(\w+)/);
const className = classMatch ? classMatch[1] : fileName;
switch (componentType) {
case 'component': {
const selector = metadata?.selector || 'unknown';
const inputs = Array.isArray(metadata?.inputs) ? metadata.inputs.length : 0;
const outputs = Array.isArray(metadata?.outputs) ? metadata.outputs.length : 0;
const lifecycle = this.extractLifecycleMethods(content);