@emberbox/lint 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,27 @@
1
+ import {mkdirSync, writeFileSync} from 'node:fs'
2
+ import {join, resolve} from 'node:path'
3
+ import {createJiti} from 'jiti'
4
+
5
+ /** The one file the catalogue is written to, so a renamed catalogue leaves no stale keys behind. */
6
+ const SNAPSHOT = 'catalogue.json'
7
+
8
+ /**
9
+ * A catalogue module as `@intlify/eslint-plugin-vue-i18n` reads it.
10
+ *
11
+ * <p>The plugin loads messages from JSON, YAML or CommonJS files only, and the catalogues of the
12
+ * Emberbox projects are TypeScript modules. So the module is evaluated and written out as JSON
13
+ * below `node_modules/.cache/emberbox-lint/locales` of the directory ESLint runs in, for the plugin's
14
+ * `localeDir`.
15
+ *
16
+ * @param catalogue the catalogue module, relative to `cwd`
17
+ * @param cwd the directory ESLint runs in
18
+ * @returns the snapshot file, for the plugin's `localeDir` setting
19
+ */
20
+ export async function localeSnapshots(catalogue, cwd) {
21
+ const snapshots = resolve(cwd, 'node_modules/.cache/emberbox-lint/locales')
22
+ const jiti = createJiti(import.meta.url, {moduleCache: false})
23
+ const messages = await jiti.import(resolve(cwd, catalogue), {default: true})
24
+ mkdirSync(snapshots, {recursive: true})
25
+ writeFileSync(join(snapshots, SNAPSHOT), JSON.stringify(messages))
26
+ return join(snapshots, SNAPSHOT)
27
+ }
@@ -0,0 +1,41 @@
1
+ import {createParser} from '@intlify/message-compiler'
2
+ import * as jsonc from 'jsonc-eslint-parser'
3
+
4
+ /** The node type vue-i18n's message compiler gives a message it reads as plural choices. */
5
+ const PLURAL = 1
6
+
7
+ /**
8
+ * Refuses a message vue-i18n reads as plural choices.
9
+ *
10
+ * <p>A bare `|` splits a message into choices, and `t()` then shows the first of them unless a
11
+ * count is passed, so a pipe written as text silently cuts the sentence short. In a project that
12
+ * passes no counts to pick a plural form, every such message is a pipe that wanted escaping as
13
+ * `{'|'}`; a project that uses plural messages turns this rule off with the config's `plurals`
14
+ * option.
15
+ * The message is read by the compiler vue-i18n itself uses, not by pattern.
16
+ *
17
+ * @type {import('eslint').Rule.RuleModule}
18
+ */
19
+ export default {
20
+ meta: {
21
+ type: 'problem',
22
+ docs: {description: 'disallow messages vue-i18n splits into plural choices'},
23
+ schema: [],
24
+ messages: {
25
+ plural: "This message has a bare '|', which vue-i18n reads as plural choices. Escape it as {'|'}.",
26
+ },
27
+ },
28
+ create(context) {
29
+ if (!context.sourceCode.parserServices?.isJSON) return {}
30
+ const parser = createParser({onError() {}})
31
+ return {
32
+ JSONProperty(property) {
33
+ const value = property.value
34
+ if (value.type === 'JSONObjectExpression' || value.type === 'JSONArrayExpression') return
35
+ const message = jsonc.getStaticJSONValue(value)
36
+ if (typeof message !== 'string') return
37
+ if (parser.parse(message).body.type === PLURAL) context.report({node: value, messageId: 'plural'})
38
+ },
39
+ }
40
+ },
41
+ }
@@ -0,0 +1,99 @@
1
+ import {resolve} from 'node:path'
2
+ import {definedProperties, germanKeys, localeFiles} from './catalogue.mjs'
3
+ import {collectUsage, isReferenced} from './usage.mjs'
4
+
5
+ const LOCALE_ENTRY = {
6
+ type: 'object',
7
+ properties: {file: {type: 'string'}, prefix: {type: 'string'}},
8
+ required: ['file'],
9
+ additionalProperties: false,
10
+ }
11
+
12
+ /**
13
+ * Reports every message nothing refers to, at the property that defines it.
14
+ *
15
+ * <p>Runs on the locale file, parsed by the locale parser. What counts as a reference is what
16
+ * `collectUsage` finds in the sources. `enableFix` lets `--fix` delete what it reports, for a
17
+ * deliberate clean-up; it is off by default, so an ordinary fix run never removes a message.
18
+ *
19
+ * @type {import('eslint').Rule.RuleModule}
20
+ */
21
+ export default {
22
+ meta: {
23
+ type: 'suggestion',
24
+ docs: {description: 'disallow messages nothing refers to'},
25
+ fixable: 'code',
26
+ schema: [{
27
+ type: 'object',
28
+ properties: {
29
+ sources: {type: 'string'},
30
+ german: {type: 'array', items: LOCALE_ENTRY},
31
+ enableFix: {type: 'boolean'},
32
+ },
33
+ required: ['sources', 'german'],
34
+ additionalProperties: false,
35
+ }],
36
+ messages: {
37
+ unused: "i18n key '{{key}}' is never referenced.",
38
+ },
39
+ },
40
+ create(context) {
41
+ const options = context.options[0]
42
+ const files = localeFiles(context, options)
43
+ const current = resolve(context.filename)
44
+ const german = files.german.find(entry => entry.file === current)
45
+ if (!german) return {}
46
+
47
+ return {
48
+ 'Program:exit'(program) {
49
+ const sorted = [...germanKeys(files.german, current, program)].sort()
50
+ const excluded = new Set(files.german.map(entry => entry.file))
51
+ const usage = collectUsage(resolve(context.cwd, options.sources), excluded)
52
+ const definesPrefix = head => leadsIntoKeys(sorted, head)
53
+
54
+ for (const [key, property] of definedProperties(program, german.prefix)) {
55
+ if (isReferenced(usage, key, definesPrefix)) continue
56
+ const fix = options.enableFix ? fixer => fixer.removeRange(removalRange(context.sourceCode.text, property)) : null
57
+ context.report({node: property.key, messageId: 'unused', data: {key}, fix})
58
+ }
59
+ },
60
+ }
61
+ },
62
+ }
63
+
64
+ /**
65
+ * The text a property takes up, with its comma, and with its whole line where it stands alone on
66
+ * it, so that removing it leaves no gap behind.
67
+ *
68
+ * @param text the file's source
69
+ * @param property the JSON AST property
70
+ * @returns the range to remove
71
+ */
72
+ function removalRange(text, property) {
73
+ let [start, end] = property.range
74
+ if (text[end] === ',') end++
75
+ const lineStart = text.lastIndexOf('\n', start - 1) + 1
76
+ const lineEnd = text.indexOf('\n', end)
77
+ const alone = text.slice(lineStart, start).trim() === '' && text.slice(end, lineEnd === -1 ? text.length : lineEnd).trim() === ''
78
+ return alone ? [lineStart, lineEnd === -1 ? text.length : lineEnd + 1] : [start, end]
79
+ }
80
+
81
+ /**
82
+ * Whether at least one defined key starts with the given text. The static head of a template
83
+ * literal only counts as a prefix when it leads into the key space, which keeps unrelated literals
84
+ * such as addresses and file names from reaching anything.
85
+ *
86
+ * @param sorted the defined keys, sorted
87
+ * @param text the head
88
+ * @returns true when a key starts with it
89
+ */
90
+ function leadsIntoKeys(sorted, text) {
91
+ let low = 0
92
+ let high = sorted.length
93
+ while (low < high) {
94
+ const middle = (low + high) >> 1
95
+ if (sorted[middle] < text) low = middle + 1
96
+ else high = middle
97
+ }
98
+ return low < sorted.length && sorted[low].startsWith(text)
99
+ }
@@ -0,0 +1,267 @@
1
+ import {readdirSync, readFileSync} from 'node:fs'
2
+ import {join, resolve} from 'node:path'
3
+ import * as typescriptParser from '@typescript-eslint/parser'
4
+ import {parseForESLint as parseVue} from 'vue-eslint-parser'
5
+
6
+ const TRANSLATE = new Set(['t', 'te', 'tc', 'tm', '$t', '$te', '$tc', '$tm'])
7
+ const SUBTREE = new Set(['tm', '$tm'])
8
+ const KEY_SHAPE = /^[A-Za-z][\w-]*(?:\.[\w-]+)+$/
9
+ const PREFIX_SHAPE = /^[A-Za-z][\w-]*(?:\.[\w-]*)+$/
10
+ const TAIL_SHAPE = /^(?:\.[\w-]+)+$/
11
+ const PREFIX_VALUE_SHAPE = /^[A-Za-z][\w-]*(?:\.[\w-]+)*$/
12
+ const PREFIX_ATTRIBUTE = /^i18n[-_]?prefix$/i
13
+ const SKIPPED = new Set(['parent', 'loc', 'range', 'tokens', 'comments', 'errors', 'references', 'variables', 'templateBody'])
14
+
15
+ const cache = new Map()
16
+
17
+ /**
18
+ * How the sources refer to translation keys, collected once per process from every `.ts` and
19
+ * `.vue` file under a directory.
20
+ *
21
+ * <p>Keys are handed around in more ways than a call to `t()`, and each of these counts:
22
+ * <ul>
23
+ * <li>`t`, `te`, `tc`, `tm` and their `$` forms called with a key, and a key built from a
24
+ * string and a `+` or from a template literal reaches every key below its static head;</li>
25
+ * <li>`tm` reaches the whole subtree below its key;</li>
26
+ * <li>a template literal anywhere whose static head leads into the key space reaches every key
27
+ * below it, because help pages and error mappers build the key into a local first;</li>
28
+ * <li>a template literal that is only an interpolation and a static tail, such as
29
+ * `${props.i18nPrefix}.form.title`, pairs with the values callers pass to an `i18n-prefix`
30
+ * attribute, and one that goes on into a second interpolation, such as
31
+ * `${props.i18nPrefix}.form.types.${type}`, reaches every key below the pair;</li>
32
+ * <li>a string that spells a key, in the script or as an attribute value, because route tables,
33
+ * error maps and props pass keys around as data;</li>
34
+ * <li>the `keypath` of an `<i18n-t>`.</li>
35
+ * </ul>
36
+ *
37
+ * @param directory the absolute directory to read
38
+ * @param excluded absolute paths of files to leave out, the locale files themselves
39
+ * @returns the references found
40
+ */
41
+ export function collectUsage(directory, excluded) {
42
+ const cacheKey = `${directory}\n${[...excluded].sort().join('\n')}`
43
+ if (cache.has(cacheKey)) return cache.get(cacheKey)
44
+ const usage = {exact: new Set(), prefixes: new Set(), heads: new Set(), prefixValues: new Set(), tails: new Set(), openTails: new Set()}
45
+ for (const file of sourceFiles(directory)) {
46
+ if (excluded.has(file)) continue
47
+ for (const root of parseSource(file)) walk(root, node => visit(node, usage))
48
+ }
49
+ cache.set(cacheKey, usage)
50
+ return usage
51
+ }
52
+
53
+ /**
54
+ * Whether a key counts as referenced by what {@link collectUsage} found.
55
+ *
56
+ * @param usage the references
57
+ * @param key the dotted key
58
+ * @param definesPrefix whether a static template head leads into the key space, which is what
59
+ * keeps unrelated literals such as addresses out of the prefixes
60
+ * @returns true when something refers to it
61
+ */
62
+ export function isReferenced(usage, key, definesPrefix) {
63
+ if (usage.exact.has(key)) return true
64
+ for (const prefix of usage.prefixes) {
65
+ if (key.startsWith(prefix)) return true
66
+ }
67
+ for (const head of usage.heads) {
68
+ const prefix = head.replace(/\.+$/, '')
69
+ if (prefix.length > 0 && key.startsWith(prefix) && definesPrefix(head)) return true
70
+ }
71
+ for (const value of usage.prefixValues) {
72
+ for (const tail of usage.tails) {
73
+ if (value + tail === key) return true
74
+ }
75
+ for (const tail of usage.openTails) {
76
+ if (key.startsWith(`${value}${tail}.`)) return true
77
+ }
78
+ }
79
+ return false
80
+ }
81
+
82
+ /**
83
+ * Every `.ts` and `.vue` file below a directory, declarations left out.
84
+ *
85
+ * @param directory the absolute directory
86
+ * @returns absolute paths
87
+ */
88
+ function sourceFiles(directory) {
89
+ const found = []
90
+ for (const entry of readdirSync(directory, {withFileTypes: true})) {
91
+ const path = join(directory, entry.name)
92
+ if (entry.isDirectory()) found.push(...sourceFiles(path))
93
+ else if (entry.name.endsWith('.vue') || (entry.name.endsWith('.ts') && !entry.name.endsWith('.d.ts'))) found.push(resolve(path))
94
+ }
95
+ return found
96
+ }
97
+
98
+ /**
99
+ * The syntax trees of one source file: the script, and the template of a component.
100
+ *
101
+ * @param file the absolute path
102
+ * @returns the roots to walk
103
+ */
104
+ function parseSource(file) {
105
+ const code = readFileSync(file, 'utf-8')
106
+ if (file.endsWith('.vue')) {
107
+ const {ast} = parseVue(code, {parser: typescriptParser, sourceType: 'module', ecmaVersion: 'latest', filePath: file})
108
+ return ast.templateBody ? [ast, ast.templateBody] : [ast]
109
+ }
110
+ return [typescriptParser.parse(code, {sourceType: 'module', filePath: file})]
111
+ }
112
+
113
+ /**
114
+ * Visits every node below a root, in no particular order.
115
+ *
116
+ * @param root the root
117
+ * @param visitor called with each node
118
+ */
119
+ function walk(root, visitor) {
120
+ const pending = [root]
121
+ while (pending.length > 0) {
122
+ const node = pending.pop()
123
+ visitor(node)
124
+ for (const [name, value] of Object.entries(node)) {
125
+ if (SKIPPED.has(name) || value === null || typeof value !== 'object') continue
126
+ if (Array.isArray(value)) {
127
+ for (const item of value) if (item && typeof item.type === 'string') pending.push(item)
128
+ } else if (typeof value.type === 'string') {
129
+ pending.push(value)
130
+ }
131
+ }
132
+ }
133
+ }
134
+
135
+ /**
136
+ * Records what one node says about keys.
137
+ *
138
+ * @param node the node
139
+ * @param usage the references collected so far
140
+ */
141
+ function visit(node, usage) {
142
+ switch (node.type) {
143
+ case 'CallExpression':
144
+ visitCall(node, usage)
145
+ break
146
+ case 'Literal':
147
+ if (typeof node.value === 'string' && KEY_SHAPE.test(node.value)) usage.exact.add(node.value)
148
+ break
149
+ case 'TemplateLiteral':
150
+ visitTemplate(node, usage)
151
+ break
152
+ case 'VAttribute':
153
+ visitAttribute(node, usage)
154
+ break
155
+ default:
156
+ break
157
+ }
158
+ }
159
+
160
+ /**
161
+ * A call to one of the translation functions.
162
+ *
163
+ * @param node the call
164
+ * @param usage the references collected so far
165
+ */
166
+ function visitCall(node, usage) {
167
+ const name = calleeName(node.callee)
168
+ if (!TRANSLATE.has(name) || node.arguments.length === 0) return
169
+ const argument = node.arguments[0]
170
+ const whole = staticString(argument)
171
+ if (whole !== null) {
172
+ if (!whole.includes('.')) return
173
+ usage.exact.add(whole)
174
+ if (SUBTREE.has(name)) usage.prefixes.add(whole)
175
+ return
176
+ }
177
+ if (argument.type === 'TemplateLiteral') {
178
+ if (!argument.quasis.some(quasi => quasi.value.cooked.includes('.'))) return
179
+ addPrefix(usage, argument.quasis[0].value.cooked)
180
+ return
181
+ }
182
+ if (argument.type === 'BinaryExpression' && argument.operator === '+') {
183
+ const head = staticString(leftmost(argument))
184
+ if (head !== null) addPrefix(usage, head)
185
+ }
186
+ }
187
+
188
+ /**
189
+ * A template literal, which may be a key built from a static head or a tail after a prefix.
190
+ *
191
+ * @param node the template literal
192
+ * @param usage the references collected so far
193
+ */
194
+ function visitTemplate(node, usage) {
195
+ if (node.expressions.length === 0) {
196
+ const value = node.quasis[0].value.cooked
197
+ if (KEY_SHAPE.test(value)) usage.exact.add(value)
198
+ return
199
+ }
200
+ const head = node.quasis[0].value.cooked
201
+ if (PREFIX_SHAPE.test(head)) usage.heads.add(head)
202
+ if (head !== '') return
203
+ const middle = node.quasis[1].value.cooked
204
+ if (node.quasis.length === 2 && TAIL_SHAPE.test(middle)) usage.tails.add(middle)
205
+ if (node.quasis.length > 2 && TAIL_SHAPE.test(middle.replace(/\.$/, ''))) usage.openTails.add(middle.replace(/\.$/, ''))
206
+ }
207
+
208
+ /**
209
+ * A static attribute of a template: a key written out, a key path or a prefix handed down.
210
+ *
211
+ * @param node the attribute
212
+ * @param usage the references collected so far
213
+ */
214
+ function visitAttribute(node, usage) {
215
+ if (node.directive || !node.value) return
216
+ const name = node.key.rawName ?? node.key.name
217
+ const value = node.value.value
218
+ if (PREFIX_ATTRIBUTE.test(name) && PREFIX_VALUE_SHAPE.test(value)) usage.prefixValues.add(value)
219
+ if (KEY_SHAPE.test(value) || name === 'keypath') usage.exact.add(value)
220
+ }
221
+
222
+ /**
223
+ * Adds a static head as a prefix every key below it counts under.
224
+ *
225
+ * @param usage the references collected so far
226
+ * @param head the static text before the dynamic part
227
+ */
228
+ function addPrefix(usage, head) {
229
+ const prefix = head.replace(/\.+$/, '')
230
+ if (prefix.length > 0) usage.prefixes.add(prefix)
231
+ }
232
+
233
+ /**
234
+ * The name a call is made through, whether plain or as a member.
235
+ *
236
+ * @param callee the callee
237
+ * @returns the name, or an empty string
238
+ */
239
+ function calleeName(callee) {
240
+ if (callee.type === 'Identifier') return callee.name
241
+ if (callee.type === 'MemberExpression' && !callee.computed && callee.property.type === 'Identifier') return callee.property.name
242
+ return ''
243
+ }
244
+
245
+ /**
246
+ * The value of a string literal or a template literal without substitutions.
247
+ *
248
+ * @param node the expression
249
+ * @returns the string, or null for anything else
250
+ */
251
+ function staticString(node) {
252
+ if (node.type === 'Literal' && typeof node.value === 'string') return node.value
253
+ if (node.type === 'TemplateLiteral' && node.expressions.length === 0) return node.quasis[0].value.cooked
254
+ return null
255
+ }
256
+
257
+ /**
258
+ * The first operand of a chain of `+`.
259
+ *
260
+ * @param node the expression
261
+ * @returns the operand furthest to the left
262
+ */
263
+ function leftmost(node) {
264
+ let current = node
265
+ while (current.type === 'BinaryExpression' && current.operator === '+') current = current.left
266
+ return current
267
+ }
package/src/plugin.mjs ADDED
@@ -0,0 +1,20 @@
1
+ import noPluralMessages from './i18n/no-plural-messages.mjs'
2
+ import unusedKeys from './i18n/unused-keys.mjs'
3
+ import maxFunctionLines from './rules/max-function-lines.mjs'
4
+ import repeatedClassPattern from './rules/repeated-class-pattern.mjs'
5
+ import templateBlockSize from './rules/template-block-size.mjs'
6
+
7
+ /**
8
+ * The rules the Emberbox projects hold their frontends to that no published plugin knows about,
9
+ * registered under the `emberbox` prefix.
10
+ */
11
+ export default {
12
+ meta: {name: 'emberbox'},
13
+ rules: {
14
+ 'i18n-no-plural-messages': noPluralMessages,
15
+ 'i18n-unused-keys': unusedKeys,
16
+ 'max-function-lines': maxFunctionLines,
17
+ 'repeated-class-pattern': repeatedClassPattern,
18
+ 'template-block-size': templateBlockSize,
19
+ },
20
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * An object type written inline in `ref<>`: a state's shape is worth a name, which the code that
3
+ * reads the state can then refer to.
4
+ */
5
+ export const INLINE_STATE_TYPE = {
6
+ selector: "CallExpression[callee.name='ref']:matches([typeArguments.params.0.type='TSTypeLiteral'], [typeArguments.params.0.types.0.type='TSTypeLiteral'])",
7
+ message: 'Inline object type in ref<>: give the type a name.',
8
+ }
9
+
10
+ /**
11
+ * The `no-restricted-syntax` rules for scripts and for Vue templates alike.
12
+ *
13
+ * @param restrictions the selectors with their messages
14
+ * @returns the rule entries
15
+ */
16
+ export function restrictSyntax(...restrictions) {
17
+ return {
18
+ 'no-restricted-syntax': ['error', ...restrictions],
19
+ 'vue/no-restricted-syntax': ['error', ...restrictions],
20
+ }
21
+ }
@@ -0,0 +1,77 @@
1
+ import {basename, sep} from 'node:path'
2
+
3
+ /**
4
+ * Functions that span too many lines, the composables excepted.
5
+ *
6
+ * <p>The same measure as ESLint's own `max-lines-per-function`, first line to last, with one
7
+ * exception it cannot express: a composable. `useSomething` in a file of its own, or in the
8
+ * composables folder, is a wrapper whose body is the whole feature it provides, a scope for its
9
+ * state and the functions it returns, so its length says how much it offers rather than that one
10
+ * function does too much. The functions inside it are measured like any other.
11
+ *
12
+ * @type {import('eslint').Rule.RuleModule}
13
+ */
14
+ export default {
15
+ meta: {
16
+ type: 'suggestion',
17
+ docs: {description: 'Enforce a maximum number of lines per function, composable wrappers excepted'},
18
+ schema: [{
19
+ type: 'object',
20
+ properties: {max: {type: 'integer', minimum: 1}},
21
+ additionalProperties: false,
22
+ }],
23
+ messages: {
24
+ tooLong: "Function '{{name}}' spans {{lines}} lines (at most {{max}}). Extract helpers.",
25
+ },
26
+ },
27
+ create(context) {
28
+ const max = context.options[0]?.max ?? 79
29
+
30
+ /**
31
+ * Reports a function longer than the maximum unless it is a composable wrapper.
32
+ *
33
+ * @param node the function
34
+ */
35
+ function check(node) {
36
+ const lines = node.loc.end.line - node.loc.start.line + 1
37
+ if (lines <= max) return
38
+ const name = functionName(node)
39
+ if (isComposableWrapper(context.filename, name)) return
40
+ context.report({node, messageId: 'tooLong', data: {name: name ?? 'anonymous', lines, max}})
41
+ }
42
+
43
+ return {
44
+ FunctionDeclaration: check,
45
+ FunctionExpression: check,
46
+ ArrowFunctionExpression: check,
47
+ }
48
+ },
49
+ }
50
+
51
+ /**
52
+ * The name a function is known by: its own, or that of the variable or property it is assigned to.
53
+ *
54
+ * @param node the function
55
+ * @returns the name, or null for an anonymous callback
56
+ */
57
+ function functionName(node) {
58
+ if (node.id) return node.id.name
59
+ const parent = node.parent
60
+ if (parent?.type === 'VariableDeclarator' && parent.id.type === 'Identifier') return parent.id.name
61
+ if (parent?.type === 'Property' && parent.key.type === 'Identifier') return parent.key.name
62
+ return null
63
+ }
64
+
65
+ /**
66
+ * Whether a function is the wrapper of a composable: named `use` and a capital, in the composables
67
+ * folder or in a file named after a composable.
68
+ *
69
+ * @param filename the file the function is in
70
+ * @param name the function's name
71
+ * @returns true for a composable wrapper
72
+ */
73
+ function isComposableWrapper(filename, name) {
74
+ if (!name || !/^use[A-Z]/.test(name)) return false
75
+ if (filename.includes(`${sep}composables${sep}`)) return true
76
+ return /^use[A-Z]\w*\.(?:ts|vue)$/.test(basename(filename))
77
+ }