-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathprefer-unicode-codepoint-escapes.ts
57 lines (55 loc) · 2.1 KB
/
prefer-unicode-codepoint-escapes.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import type { RegExpVisitor } from "@eslint-community/regexpp/visitor"
import type { RegExpContext } from "../utils"
import { createRule, defineRegexpVisitor } from "../utils"
export default createRule("prefer-unicode-codepoint-escapes", {
meta: {
docs: {
description: "enforce use of unicode codepoint escapes",
category: "Stylistic Issues",
recommended: true,
},
fixable: "code",
schema: [],
messages: {
disallowSurrogatePair:
"Use Unicode codepoint escapes instead of Unicode escapes using surrogate pairs.",
},
type: "suggestion", // "problem",
},
create(context) {
function createVisitor(
regexpContext: RegExpContext,
): RegExpVisitor.Handlers {
const { node, flags, getRegexpLocation, fixReplaceNode } =
regexpContext
if (!flags.unicode && !flags.unicodeSets) {
return {}
}
return {
onCharacterEnter(cNode) {
if (cNode.value >= 0x10000) {
if (/^(?:\\u[\dA-Fa-f]{4}){2}$/u.test(cNode.raw)) {
context.report({
node,
loc: getRegexpLocation(cNode),
messageId: "disallowSurrogatePair",
fix: fixReplaceNode(cNode, () => {
let text = String.fromCodePoint(cNode.value)
.codePointAt(0)!
.toString(16)
if (/[A-F]/u.test(cNode.raw)) {
text = text.toUpperCase()
}
return `\\u{${text}}`
}),
})
}
}
},
}
}
return defineRegexpVisitor(context, {
createVisitor,
})
},
})