-
-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathrule-utils.ts
More file actions
1068 lines (904 loc) · 31.8 KB
/
rule-utils.ts
File metadata and controls
1068 lines (904 loc) · 31.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
import {
Visitor,
Position,
Location,
getStaticAttributeName,
hasDynamicAttributeName as hasNodeDynamicAttributeName,
getCombinedAttributeName,
hasERBOutput,
getStaticContentFromNodes,
hasStaticContent,
isEffectivelyStatic,
getValidatableStaticContent
} from "@herb-tools/core"
import type {
ERBContentNode,
HTMLAttributeNameNode,
HTMLAttributeNode,
HTMLAttributeValueNode,
HTMLElementNode,
HTMLOpenTagNode,
LiteralNode,
LexResult,
Token,
Node
} from "@herb-tools/core"
import { DEFAULT_LINT_CONTEXT } from "../types.js"
import type * as Nodes from "@herb-tools/core"
import type { LintOffense, LintSeverity, LintContext, BaseAutofixContext } from "../types.js"
export enum ControlFlowType {
CONDITIONAL,
LOOP
}
/**
* Base visitor class that provides common functionality for rule visitors
*/
export abstract class BaseRuleVisitor<TAutofixContext extends BaseAutofixContext = BaseAutofixContext> extends Visitor {
public readonly offenses: LintOffense<TAutofixContext>[] = []
protected ruleName: string
protected context: LintContext
constructor(ruleName: string, context?: Partial<LintContext>) {
super()
this.ruleName = ruleName
this.context = { ...DEFAULT_LINT_CONTEXT, ...context }
}
/**
* Helper method to create a lint offense
*/
protected createOffense(message: string, location: Location, severity: LintSeverity = "error", autofixContext?: TAutofixContext): LintOffense<TAutofixContext> {
return {
rule: this.ruleName,
code: this.ruleName,
source: "Herb Linter",
message,
location,
severity,
autofixContext,
}
}
/**
* Helper method to add an offense to the offenses array
*/
protected addOffense(message: string, location: Location, severity: LintSeverity = "error", autofixContext?: TAutofixContext): void {
this.offenses.push(this.createOffense(message, location, severity, autofixContext))
}
}
/**
* Mixin that adds control flow tracking capabilities to rule visitors
* This allows rules to track state across different control flow structures
* like if/else branches, loops, etc.
*
* @template TAutofixContext - Type for autofix context (node + custom data)
* @template TControlFlowState - Type for state passed between onEnterControlFlow and onExitControlFlow
* @template TBranchState - Type for state passed between onEnterBranch and onExitBranch
*/
export abstract class ControlFlowTrackingVisitor<TAutofixContext extends BaseAutofixContext = BaseAutofixContext, TControlFlowState = any, TBranchState = any> extends BaseRuleVisitor<TAutofixContext> {
protected isInControlFlow: boolean = false
protected currentControlFlowType: ControlFlowType | null = null
/**
* Handle visiting a control flow node with proper scope management
*/
protected handleControlFlowNode(node: Node, controlFlowType: ControlFlowType, visitChildren: () => void): void {
const wasInControlFlow = this.isInControlFlow
const previousControlFlowType = this.currentControlFlowType
this.isInControlFlow = true
this.currentControlFlowType = controlFlowType
const stateToRestore = this.onEnterControlFlow(controlFlowType, wasInControlFlow)
visitChildren()
this.onExitControlFlow(controlFlowType, wasInControlFlow, stateToRestore)
this.isInControlFlow = wasInControlFlow
this.currentControlFlowType = previousControlFlowType
}
/**
* Handle visiting a branch node (like else, when) with proper scope management
*/
protected startNewBranch(visitChildren: () => void): void {
const stateToRestore = this.onEnterBranch()
visitChildren()
this.onExitBranch(stateToRestore)
}
visitERBIfNode(node: Nodes.ERBIfNode): void {
this.handleControlFlowNode(node, ControlFlowType.CONDITIONAL, () => super.visitERBIfNode(node))
}
visitERBUnlessNode(node: Nodes.ERBUnlessNode): void {
this.handleControlFlowNode(node, ControlFlowType.CONDITIONAL, () => super.visitERBUnlessNode(node))
}
visitERBCaseNode(node: Nodes.ERBCaseNode): void {
this.handleControlFlowNode(node, ControlFlowType.CONDITIONAL, () => super.visitERBCaseNode(node))
}
visitERBCaseMatchNode(node: Nodes.ERBCaseMatchNode): void {
this.handleControlFlowNode(node, ControlFlowType.CONDITIONAL, () => super.visitERBCaseMatchNode(node))
}
visitERBWhileNode(node: Nodes.ERBWhileNode): void {
this.handleControlFlowNode(node, ControlFlowType.LOOP, () => super.visitERBWhileNode(node))
}
visitERBForNode(node: Nodes.ERBForNode): void {
this.handleControlFlowNode(node, ControlFlowType.LOOP, () => super.visitERBForNode(node))
}
visitERBUntilNode(node: Nodes.ERBUntilNode): void {
this.handleControlFlowNode(node, ControlFlowType.LOOP, () => super.visitERBUntilNode(node))
}
visitERBBlockNode(node: Nodes.ERBBlockNode): void {
this.handleControlFlowNode(node, ControlFlowType.CONDITIONAL, () => super.visitERBBlockNode(node))
}
visitERBElseNode(node: Nodes.ERBElseNode): void {
this.startNewBranch(() => super.visitERBElseNode(node))
}
visitERBWhenNode(node: Nodes.ERBWhenNode): void {
this.startNewBranch(() => super.visitERBWhenNode(node))
}
protected abstract onEnterControlFlow(controlFlowType: ControlFlowType, wasAlreadyInControlFlow: boolean): TControlFlowState
protected abstract onExitControlFlow(controlFlowType: ControlFlowType, wasAlreadyInControlFlow: boolean, stateToRestore: TControlFlowState): void
protected abstract onEnterBranch(): TBranchState
protected abstract onExitBranch(stateToRestore: TBranchState): void
}
/**
* Gets attributes from an HTMLOpenTagNode
*/
export function getAttributes(node: HTMLOpenTagNode): HTMLAttributeNode[] {
return node.children.filter(node => node.type === "AST_HTML_ATTRIBUTE_NODE") as HTMLAttributeNode[]
}
/**
* Gets the tag name from an HTML tag node (lowercased)
*/
export function getTagName(node: HTMLElementNode | HTMLOpenTagNode | null | undefined): string | null {
if (!node) return null
return node.tag_name?.value.toLowerCase() || null
}
/**
* Gets the attribute name from an HTMLAttributeNode (lowercased)
* Returns null if the attribute name contains dynamic content (ERB)
*/
export function getAttributeName(attributeNode: HTMLAttributeNode, lowercase = true): string | null {
if (attributeNode.name?.type === "AST_HTML_ATTRIBUTE_NAME_NODE") {
const nameNode = attributeNode.name as HTMLAttributeNameNode
const staticName = getStaticAttributeName(nameNode)
if (!lowercase) return staticName
return staticName ? staticName.toLowerCase() : null
}
return null
}
/**
* Checks if an attribute has a dynamic (ERB-containing) name
*/
export function hasDynamicAttributeName(attributeNode: HTMLAttributeNode): boolean {
if (attributeNode.name?.type === "AST_HTML_ATTRIBUTE_NAME_NODE") {
const nameNode = attributeNode.name as HTMLAttributeNameNode
return hasNodeDynamicAttributeName(nameNode)
}
return false
}
/**
* Gets the combined string representation of an attribute name (for debugging)
* This includes both static content and ERB syntax
*/
export function getCombinedAttributeNameString(attributeNode: HTMLAttributeNode): string {
if (attributeNode.name?.type === "AST_HTML_ATTRIBUTE_NAME_NODE") {
const nameNode = attributeNode.name as HTMLAttributeNameNode
return getCombinedAttributeName(nameNode)
}
return ""
}
/**
* Checks if an attribute value contains only static content (no ERB)
*/
export function hasStaticAttributeValue(attributeNode: HTMLAttributeNode): boolean {
const valueNode = attributeNode.value as HTMLAttributeValueNode | null
if (!valueNode?.children) return false
return valueNode.children.every(child => child.type === "AST_LITERAL_NODE")
}
/**
* Checks if an attribute value contains dynamic content (ERB)
*/
export function hasDynamicAttributeValue(attributeNode: HTMLAttributeNode): boolean {
const valueNode = attributeNode.value as HTMLAttributeValueNode | null
if (!valueNode?.children) return false
return valueNode.children.some(child => child.type === "AST_ERB_CONTENT_NODE")
}
/**
* Gets the static string value of an attribute (returns null if it contains ERB)
*/
export function getStaticAttributeValue(attributeNode: HTMLAttributeNode): string | null {
if (!hasStaticAttributeValue(attributeNode)) return null
const valueNode = attributeNode.value as HTMLAttributeValueNode
const result = valueNode.children
?.filter(child => child.type === "AST_LITERAL_NODE")
.map(child => (child as LiteralNode).content)
.join("") || ""
return result
}
/**
* Gets the value nodes array for dynamic inspection
*/
export function getAttributeValueNodes(attributeNode: HTMLAttributeNode): Node[] {
const valueNode = attributeNode.value as HTMLAttributeValueNode | null
return valueNode?.children || []
}
/**
* Checks if an attribute value contains any static content (for validation purposes)
*/
export function hasStaticAttributeValueContent(attributeNode: HTMLAttributeNode): boolean {
const valueNodes = getAttributeValueNodes(attributeNode)
return hasStaticContent(valueNodes)
}
/**
* Gets the static content of an attribute value (all literal parts combined)
* Returns the concatenated literal content, or null if no literal nodes exist
*/
export function getStaticAttributeValueContent(attributeNode: HTMLAttributeNode): string | null {
const valueNodes = getAttributeValueNodes(attributeNode)
return getStaticContentFromNodes(valueNodes)
}
/**
* Gets the attribute value content from an HTMLAttributeValueNode
*/
export function getAttributeValue(attributeNode: HTMLAttributeNode): string | null {
const valueNode: HTMLAttributeValueNode | null = attributeNode.value as HTMLAttributeValueNode
if (valueNode === null) return null
if (valueNode.type !== "AST_HTML_ATTRIBUTE_VALUE_NODE" || !valueNode.children?.length) {
return null
}
let result = ""
for (const child of valueNode.children) {
switch (child.type) {
case "AST_ERB_CONTENT_NODE": {
const erbNode = child as ERBContentNode
if (erbNode.content) {
result += `${erbNode.tag_opening?.value}${erbNode.content.value}${erbNode.tag_closing?.value}`
}
break
}
case "AST_LITERAL_NODE": {
result += (child as LiteralNode).content
break
}
}
}
return result
}
/**
* Checks if an attribute has a value
*/
export function hasAttributeValue(attributeNode: HTMLAttributeNode): boolean {
return attributeNode.value?.type === "AST_HTML_ATTRIBUTE_VALUE_NODE"
}
/**
* Gets the quote type used for an attribute value
*/
export function getAttributeValueQuoteType(nodeOrAttribute: HTMLAttributeNode | HTMLAttributeValueNode): "single" | "double" | "none" | null {
let valueNode: HTMLAttributeValueNode | undefined
if (nodeOrAttribute.type === "AST_HTML_ATTRIBUTE_NODE") {
const attributeNode = nodeOrAttribute as HTMLAttributeNode
if (attributeNode.value?.type === "AST_HTML_ATTRIBUTE_VALUE_NODE") {
valueNode = attributeNode.value as HTMLAttributeValueNode
}
} else if (nodeOrAttribute.type === "AST_HTML_ATTRIBUTE_VALUE_NODE") {
valueNode = nodeOrAttribute as HTMLAttributeValueNode
}
if (valueNode) {
if (valueNode.quoted && valueNode.open_quote) {
return valueNode.open_quote.value === '"' ? "double" : "single"
}
return "none"
}
return null
}
/**
* Finds an attribute by name in a list of attributes
*/
export function findAttributeByName(attributes: Node[], attributeName: string): HTMLAttributeNode | null {
for (const child of attributes) {
if (child.type === "AST_HTML_ATTRIBUTE_NODE") {
const attributeNode = child as HTMLAttributeNode
const name = getAttributeName(attributeNode)
if (name === attributeName.toLowerCase()) {
return attributeNode
}
}
}
return null
}
/**
* Checks if a tag has a specific attribute
*/
export function hasAttribute(node: HTMLOpenTagNode, attributeName: string): boolean {
return getAttribute(node, attributeName) !== null
}
/**
* Checks if a tag has a specific attribute
*/
export function getAttribute(node: HTMLOpenTagNode, attributeName: string): HTMLAttributeNode | null {
const attributes = getAttributes(node)
return findAttributeByName(attributes, attributeName)
}
/**
* Common HTML element categorization
*/
export const HTML_INLINE_ELEMENTS = new Set([
"a", "abbr", "acronym", "b", "bdo", "big", "br", "button", "cite", "code",
"dfn", "em", "i", "img", "input", "kbd", "label", "map", "object", "output",
"q", "samp", "script", "select", "small", "span", "strong", "sub", "sup",
"textarea", "time", "tt", "var"
])
export const HTML_BLOCK_ELEMENTS = new Set([
"address", "article", "aside", "blockquote", "canvas", "dd", "div", "dl",
"dt", "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2",
"h3", "h4", "h5", "h6", "header", "hr", "li", "main", "nav", "noscript",
"ol", "p", "pre", "section", "table", "tfoot", "ul", "video"
])
export const HTML_VOID_ELEMENTS = new Set([
"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta",
"param", "source", "track", "wbr",
])
export const HTML_BOOLEAN_ATTRIBUTES = new Set([
"autofocus", "autoplay", "checked", "controls", "defer", "disabled", "hidden",
"loop", "multiple", "muted", "readonly", "required", "reversed", "selected",
"open", "default", "formnovalidate", "novalidate", "itemscope", "scoped",
"seamless", "allowfullscreen", "async", "compact", "declare", "nohref",
"noresize", "noshade", "nowrap", "sortable", "truespeed", "typemustmatch"
])
export const HEADING_TAGS = new Set(["h1", "h2", "h3", "h4", "h5", "h6"])
/**
* SVG elements that use camelCase naming
*/
export const SVG_CAMEL_CASE_ELEMENTS = new Set([
"animateMotion",
"animateTransform",
"clipPath",
"feBlend",
"feColorMatrix",
"feComponentTransfer",
"feComposite",
"feConvolveMatrix",
"feDiffuseLighting",
"feDisplacementMap",
"feDistantLight",
"feDropShadow",
"feFlood",
"feFuncA",
"feFuncB",
"feFuncG",
"feFuncR",
"feGaussianBlur",
"feImage",
"feMerge",
"feMergeNode",
"feMorphology",
"feOffset",
"fePointLight",
"feSpecularLighting",
"feSpotLight",
"feTile",
"feTurbulence",
"foreignObject",
"glyphRef",
"linearGradient",
"radialGradient",
"textPath"
])
/**
* Mapping from lowercase SVG element names to their correct camelCase versions
* Generated dynamically from SVG_CAMEL_CASE_ELEMENTS
*/
export const SVG_LOWERCASE_TO_CAMELCASE = new Map(
Array.from(SVG_CAMEL_CASE_ELEMENTS).map(element => [element.toLowerCase(), element])
)
export const VALID_ARIA_ROLES = new Set([
"banner", "complementary", "contentinfo", "form", "main", "navigation", "region", "search",
"article", "cell", "columnheader", "definition", "directory", "document", "feed", "figure",
"group", "heading", "img", "list", "listitem", "math", "none", "note", "presentation",
"row", "rowgroup", "rowheader", "separator", "table", "term", "tooltip",
"alert", "alertdialog", "button", "checkbox", "combobox", "dialog", "grid", "gridcell", "link",
"listbox", "menu", "menubar", "menuitem", "menuitemcheckbox", "menuitemradio", "option",
"progressbar", "radio", "radiogroup", "scrollbar", "searchbox", "slider", "spinbutton",
"status", "switch", "tab", "tablist", "tabpanel", "textbox", "timer", "toolbar", "tree",
"treegrid", "treeitem",
"log", "marquee"
]);
/**
* Parameter types for AttributeVisitorMixin methods
*/
export interface StaticAttributeStaticValueParams {
attributeName: string
attributeValue: string
attributeNode: HTMLAttributeNode
originalAttributeName: string
parentNode: HTMLOpenTagNode
}
export interface StaticAttributeDynamicValueParams {
attributeName: string
valueNodes: Node[]
attributeNode: HTMLAttributeNode
originalAttributeName: string
parentNode: HTMLOpenTagNode
combinedValue?: string | null
}
export interface DynamicAttributeStaticValueParams {
nameNodes: Node[]
attributeValue: string
attributeNode: HTMLAttributeNode
parentNode: HTMLOpenTagNode
combinedName?: string
}
export interface DynamicAttributeDynamicValueParams {
nameNodes: Node[]
valueNodes: Node[]
attributeNode: HTMLAttributeNode
parentNode: HTMLOpenTagNode
combinedName?: string
combinedValue?: string | null
}
export const ARIA_ATTRIBUTES = new Set([
'aria-activedescendant',
'aria-atomic',
'aria-autocomplete',
'aria-busy',
'aria-checked',
'aria-colcount',
'aria-colindex',
'aria-colspan',
'aria-controls',
'aria-current',
'aria-describedby',
'aria-details',
'aria-disabled',
'aria-dropeffect',
'aria-errormessage',
'aria-expanded',
'aria-flowto',
'aria-grabbed',
'aria-haspopup',
'aria-hidden',
'aria-invalid',
'aria-keyshortcuts',
'aria-label',
'aria-labelledby',
'aria-level',
'aria-live',
'aria-modal',
'aria-multiline',
'aria-multiselectable',
'aria-orientation',
'aria-owns',
'aria-placeholder',
'aria-posinset',
'aria-pressed',
'aria-readonly',
'aria-relevant',
'aria-required',
'aria-roledescription',
'aria-rowcount',
'aria-rowindex',
'aria-rowspan',
'aria-selected',
'aria-setsize',
'aria-sort',
'aria-valuemax',
'aria-valuemin',
'aria-valuenow',
'aria-valuetext',
])
/**
* Helper function to create a location at the end of the source with a 1-character range
*/
export function createEndOfFileLocation(source: string): Location {
const lines = source.split('\n')
const lastLineNumber = lines.length
const lastLine = lines[lines.length - 1]
const lastColumnNumber = lastLine.length
const startColumn = lastColumnNumber > 0 ? lastColumnNumber - 1 : 0
const start = new Position(lastLineNumber, startColumn)
const end = new Position(lastLineNumber, lastColumnNumber)
return new Location(start, end)
}
/**
* Checks if an element is inline
*/
export function isInlineElement(tagName: string): boolean {
return HTML_INLINE_ELEMENTS.has(tagName.toLowerCase())
}
/**
* Checks if an element is block-level
*/
export function isBlockElement(tagName: string): boolean {
return HTML_BLOCK_ELEMENTS.has(tagName.toLowerCase())
}
/**
* Checks if an element is a void element
*/
export function isVoidElement(tagName: string): boolean {
return HTML_VOID_ELEMENTS.has(tagName.toLowerCase())
}
/**
* Checks if an attribute is a boolean attribute
*/
export function isBooleanAttribute(attributeName: string): boolean {
return HTML_BOOLEAN_ATTRIBUTES.has(attributeName.toLowerCase())
}
/**
* Attribute visitor that provides granular processing based on both
* attribute name type (static/dynamic) and value type (static/dynamic)
*
* This gives you 4 distinct methods to override:
* - checkStaticAttributeStaticValue() - name="class" value="foo"
* - checkStaticAttributeDynamicValue() - name="class" value="<%= css_class %>"
* - checkDynamicAttributeStaticValue() - name="data-<%= key %>" value="foo"
* - checkDynamicAttributeDynamicValue() - name="data-<%= key %>" value="<%= value %>"
*/
export abstract class AttributeVisitorMixin<TAutofixContext extends BaseAutofixContext = BaseAutofixContext> extends BaseRuleVisitor<TAutofixContext> {
constructor(ruleName: string, context?: Partial<LintContext>) {
super(ruleName, context)
}
visitHTMLOpenTagNode(node: HTMLOpenTagNode): void {
this.checkAttributesOnNode(node)
super.visitHTMLOpenTagNode(node)
}
private checkAttributesOnNode(node: HTMLOpenTagNode): void {
forEachAttribute(node, (attributeNode) => {
const staticAttributeName = getAttributeName(attributeNode)
const originalAttributeName = getAttributeName(attributeNode, false) || ""
const isDynamicName = hasDynamicAttributeName(attributeNode)
const staticAttributeValue = getStaticAttributeValue(attributeNode)
const valueNodes = getAttributeValueNodes(attributeNode)
const hasOutputERB = hasERBOutput(valueNodes)
const isEffectivelyStaticValue = isEffectivelyStatic(valueNodes)
if (staticAttributeName && staticAttributeValue !== null) {
this.checkStaticAttributeStaticValue({
attributeName: staticAttributeName,
attributeValue: staticAttributeValue,
attributeNode,
originalAttributeName,
parentNode: node
})
} else if (staticAttributeName && isEffectivelyStaticValue && !hasOutputERB) {
const validatableContent = getValidatableStaticContent(valueNodes) || ""
this.checkStaticAttributeStaticValue({ attributeName: staticAttributeName, attributeValue: validatableContent, attributeNode, originalAttributeName, parentNode: node })
} else if (staticAttributeName && hasOutputERB) {
const combinedValue = getAttributeValue(attributeNode)
this.checkStaticAttributeDynamicValue({ attributeName: staticAttributeName, valueNodes, attributeNode, parentNode: node, originalAttributeName, combinedValue })
} else if (isDynamicName && staticAttributeValue !== null) {
const nameNode = attributeNode.name as HTMLAttributeNameNode
const nameNodes = nameNode.children || []
const combinedName = getCombinedAttributeNameString(attributeNode)
this.checkDynamicAttributeStaticValue({ nameNodes, attributeValue: staticAttributeValue, attributeNode, parentNode: node, combinedName })
} else if (isDynamicName) {
const nameNode = attributeNode.name as HTMLAttributeNameNode
const nameNodes = nameNode.children || []
const combinedName = getCombinedAttributeNameString(attributeNode)
const combinedValue = getAttributeValue(attributeNode)
this.checkDynamicAttributeDynamicValue({ nameNodes, valueNodes, attributeNode, parentNode: node, combinedName, combinedValue })
}
})
}
/**
* Static attribute name with static value: class="container"
*/
protected checkStaticAttributeStaticValue(_params: StaticAttributeStaticValueParams): void {
// Default implementation does nothing
}
/**
* Static attribute name with dynamic value: class="<%= css_class %>"
*/
protected checkStaticAttributeDynamicValue(_params: StaticAttributeDynamicValueParams): void {
// Default implementation does nothing
}
/**
* Dynamic attribute name with static value: data-<%= key %>="foo"
*/
protected checkDynamicAttributeStaticValue(_params: DynamicAttributeStaticValueParams): void {
// Default implementation does nothing
}
/**
* Dynamic attribute name with dynamic value: data-<%= key %>="<%= value %>"
*/
protected checkDynamicAttributeDynamicValue(_params: DynamicAttributeDynamicValueParams): void {
// Default implementation does nothing
}
}
/**
* Checks if an attribute value is quoted
*/
export function isAttributeValueQuoted(attributeNode: HTMLAttributeNode): boolean {
if (attributeNode.value?.type === "AST_HTML_ATTRIBUTE_VALUE_NODE") {
const valueNode = attributeNode.value as HTMLAttributeValueNode
return !!valueNode.quoted
}
return false
}
/**
* Iterates over all attributes of a tag node, calling the callback for each attribute
*/
export function forEachAttribute(
node: HTMLOpenTagNode,
callback: (attributeNode: HTMLAttributeNode) => void
): void {
const attributes = getAttributes(node)
for (const child of attributes) {
if (child.type === "AST_HTML_ATTRIBUTE_NODE") {
callback(child as HTMLAttributeNode)
}
}
}
/**
* Base lexer visitor class that provides common functionality for lexer-based rule visitors
*/
export abstract class BaseLexerRuleVisitor<TAutofixContext extends BaseAutofixContext = BaseAutofixContext> {
public readonly offenses: LintOffense<TAutofixContext>[] = []
protected ruleName: string
protected context: LintContext
constructor(ruleName: string, context?: Partial<LintContext>) {
this.ruleName = ruleName
this.context = { ...DEFAULT_LINT_CONTEXT, ...context }
}
/**
* Helper method to create a lint offense for lexer rules
*/
protected createOffense(message: string, location: Location, severity: LintSeverity = "error", autofixContext?: TAutofixContext): LintOffense<TAutofixContext> {
return {
rule: this.ruleName,
code: this.ruleName,
source: "Herb Linter",
message,
location,
severity,
autofixContext,
}
}
/**
* Helper method to add an offense to the offenses array
*/
protected addOffense(message: string, location: Location, severity: LintSeverity = "error", autofixContext?: TAutofixContext): void {
this.offenses.push(this.createOffense(message, location, severity, autofixContext))
}
/**
* Main entry point for lexer rule visitors
* @param lexResult - The lexer result containing tokens and source
*/
visit(lexResult: LexResult): void {
this.visitTokens(lexResult.value.tokens)
}
/**
* Visit all tokens
* Override this method to implement token-level checks
*/
protected visitTokens(tokens: Token[]): void {
for (const token of tokens) {
this.visitToken(token)
}
}
/**
* Visit individual tokens
* Override this method to implement per-token checks
*/
protected visitToken(_token: Token): void {
// Default implementation does nothing
}
}
/**
* Base source visitor class that provides common functionality for source-based rule visitors
*/
export abstract class BaseSourceRuleVisitor<TAutofixContext extends BaseAutofixContext = BaseAutofixContext> {
public readonly offenses: LintOffense<TAutofixContext>[] = []
protected ruleName: string
protected context: LintContext
constructor(ruleName: string, context?: Partial<LintContext>) {
this.ruleName = ruleName
this.context = { ...DEFAULT_LINT_CONTEXT, ...context }
}
/**
* Helper method to create a lint offense for source rules
*/
protected createOffense(message: string, location: Location, severity: LintSeverity = "error", autofixContext?: TAutofixContext): LintOffense<TAutofixContext> {
return {
rule: this.ruleName,
code: this.ruleName,
source: "Herb Linter",
message,
location,
severity,
autofixContext,
}
}
/**
* Helper method to add an offense to the offenses array
*/
protected addOffense(message: string, location: Location, severity: LintSeverity = "error", autofixContext?: TAutofixContext): void {
this.offenses.push(this.createOffense(message, location, severity, autofixContext))
}
/**
* Main entry point for source rule visitors
* @param source - The raw source code
*/
visit(source: string): void {
this.visitSource(source)
}
/**
* Visit the source code directly
* Override this method to implement source-level checks
*/
protected abstract visitSource(source: string): void
}
/**
* Autofix utilities for applying string replacements
*/
/**
* Checks if two locations are equal
* @param a - First location
* @param b - Second location
* @returns true if locations are equal
*/
export function locationsEqual(a: Location, b: Location): boolean {
return a.start.line === b.start.line &&
a.start.column === b.start.column &&
a.end.line === b.end.line &&
a.end.column === b.end.column
}
/**
* Finds a node in the AST that has a specific location
* Uses direct recursive traversal for reliability
* @param root - The root node to search from
* @param location - The location to match
* @param predicate - Optional predicate function to filter nodes (e.g., isERBNode)
* @returns The matching node or null if not found
*/
export function findNodeByLocation(root: Node, location: Location, predicate?: (node: Node) => boolean): any {
const visited = new Set<any>()
function search(node: any): any {
if (!node || visited.has(node)) return null
visited.add(node)
if (node.location && locationsEqual(node.location, location)) {
if (!predicate || predicate(node)) {
return node
}
}
const propsToCheck = ['tag_opening', 'tag_closing', 'tag_name', 'name', 'equals', 'value', 'content']
for (const prop of propsToCheck) {
if (node[prop]?.location && locationsEqual(node[prop].location, location)) {
if (!predicate || predicate(node)) {
return node
}
}
}
if (typeof node.compactChildNodes === 'function') {
for (const child of node.compactChildNodes()) {
const found = search(child)
if (found) return found
}
} else {
if (node.children && Array.isArray(node.children)) {
for (const child of node.children) {
const found = search(child)
if (found) return found
}
}
if (node.body && Array.isArray(node.body)) {
for (const child of node.body) {
const found = search(child)
if (found) return found
}
}
}
return null
}
return search(root)
}
/**
* AST Navigation Utilities
* These utilities help navigate the AST tree for complex autofix operations
*/
/**
* Finds the parent node of a given child node in the AST
* @param root - The root node to search from (typically the document node)
* @param target - The child node to find the parent of
* @returns The parent node, or null if not found
*
* @example
* const parent = findParent(result.value, offense.autofixContext.node)
* if (parent?.type === "AST_HTML_ELEMENT_NODE") {
* // Modify parent...
* }
*/
export function findParent(root: Node, target: Node): Node | null {
let parentNode: Node | null = null
const search = (node: Node, _parent: Node | null = null): void => {
if (parentNode) return
const nodeAny = node as any
if (nodeAny.children) {
for (const child of nodeAny.children) {
if (child === target) {
parentNode = node
return
}
}
}
const propsToCheck = ['open_tag', 'close_tag', 'body', 'name', 'value']
for (const prop of propsToCheck) {
const value = (node as any)[prop]
if (value === target) {
parentNode = node
return
}
if (Array.isArray(value) && value.includes(target)) {
parentNode = node
return
}
}
if (nodeAny.children) {
for (const child of nodeAny.children) {
search(child, node)
if (parentNode) return
}
}
for (const prop of propsToCheck) {
const value = (node as any)[prop]
if (Array.isArray(value)) {
for (const item of value) {
if (item && typeof item === 'object' && 'type' in item) {
search(item, node)
if (parentNode) return
}
}
} else if (value && typeof value === 'object' && 'type' in value) {
search(value, node)
if (parentNode) return
}
}
}
search(root)
return parentNode
}