@nera-static/stan 1.0.1 → 1.1.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.
Files changed (34) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +147 -15
  3. package/canonical/editorconfig +12 -0
  4. package/canonical/github/FUNDING.yml +13 -0
  5. package/canonical/github/dependabot.yml +20 -0
  6. package/canonical/github/workflows/publish.yml +64 -0
  7. package/canonical/github/workflows/test.yml +37 -0
  8. package/canonical/husky/pre-push +1 -0
  9. package/canonical/variants/chokidar-major/github/dependabot.yml +25 -0
  10. package/canonical/variants/desktop-release/github/workflows/publish.yml +104 -0
  11. package/canonical/variants/dist-check/github/workflows/test.yml +43 -0
  12. package/canonical/variants/image-cache/github/workflows/publish.yml +73 -0
  13. package/canonical/variants/image-cache/github/workflows/test.yml +46 -0
  14. package/canonical/variants/validate-templates/github/workflows/publish.yml +64 -0
  15. package/canonical/variants/validate-templates/github/workflows/test.yml +40 -0
  16. package/canonical/variants/windows-smoke/github/workflows/test.yml +57 -0
  17. package/canonical/vitest.config.js +3 -0
  18. package/package.json +24 -12
  19. package/src/bem.js +35 -0
  20. package/src/checks/canonical.js +368 -0
  21. package/src/checks/css.js +131 -0
  22. package/src/checks/docs.js +405 -0
  23. package/src/checks/package.js +352 -0
  24. package/src/checks/pug.js +369 -0
  25. package/src/checks/tree.js +544 -0
  26. package/src/cli.js +49 -39
  27. package/src/eslint/check.js +64 -0
  28. package/src/eslint/config.js +45 -28
  29. package/src/eslint/files.js +37 -0
  30. package/src/markdown.js +60 -0
  31. package/src/repo-files.js +62 -1
  32. package/src/settings.js +136 -0
  33. package/src/stylelint/config.js +122 -0
  34. package/src/stylelint/index.js +15 -0
@@ -0,0 +1,369 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import path from 'node:path'
3
+
4
+ import lex from 'pug-lexer'
5
+ import parse from 'pug-parser'
6
+
7
+ import { BEM_HINT, CLASS_NAME } from '../bem.js'
8
+ import { listFiles } from '../eslint/files.js'
9
+ import { OUTSIDE_REPO, repoFile, writeInside } from '../repo-files.js'
10
+
11
+ /** The files the Pug check reads. */
12
+ const PUG_FILES = '**/*.pug'
13
+
14
+ /** The prefix of every Pug rule id (D4). */
15
+ export const PUG_PREFIX = 'pug/'
16
+
17
+ /** The rule ids the Pug check reports. */
18
+ export const PUG_RULES = Object.freeze({
19
+ syntax: `${PUG_PREFIX}syntax`,
20
+ indent: `${PUG_PREFIX}indent`,
21
+ noTabs: `${PUG_PREFIX}no-tabs`,
22
+ quotes: `${PUG_PREFIX}quotes`,
23
+ classPattern: `${PUG_PREFIX}class-pattern`,
24
+ })
25
+
26
+ /** The width of one indentation level. */
27
+ const INDENT = 4
28
+
29
+ /** The level width of the files `--fix` re-indents. */
30
+ const HALF_INDENT = INDENT / 2
31
+
32
+ /** What `--fix` adds to the message of a `pug/indent` finding it removes. */
33
+ const FIX_HINT = `, or run nera-stan --fix to re-indent this ${HALF_INDENT}-space file`
34
+
35
+ /** The AST keys that only say where a node stands, which re-indenting changes. */
36
+ const POSITION_KEYS = new Set(['line', 'column', 'filename'])
37
+
38
+ /** Line breaks, kept by `split` so that re-indenting leaves them as they are. */
39
+ const LINE_BREAK = /(\r\n|\r|\n)/
40
+
41
+ /** Tokens that start a line of Pug structure; the lines of a text block get none of them. */
42
+ const LINE_STARTS = new Set(['indent', 'outdent', 'newline'])
43
+
44
+ /** An attribute value that is one double-quoted string literal and nothing else. */
45
+ const DOUBLE_QUOTED = /^"((?:[^"\\]|\\.)*)"$/
46
+
47
+ /** An attribute value that is one quoted string literal and nothing else. */
48
+ const STRING_LITERAL = /^(['"])((?:(?!\1)[^\\]|\\.)*)\1$/
49
+
50
+ /**
51
+ * The Pug check (D6): every template is lexed and parsed, never linked, so an `include`
52
+ * or `extends` of a file that only a site's theme or vendor layer provides is no finding.
53
+ * On the tokens: indentation a multiple of 4 and without tabs, attribute values in single
54
+ * quotes, class literals BEM. Text blocks (`p.`, `script.`, `style.`, comments), pipe text,
55
+ * dynamic attributes (`class=cls`) and `&attributes` produce no token these rules read.
56
+ * A file that does not parse gets only its `pug/syntax` finding; the other files are still
57
+ * checked. A file whose real path lies outside the repo is not reported. `--fix` re-indents
58
+ * only a file indented by 2 spaces per level (D7, amended), see `reindented`.
59
+ */
60
+ export const pugCheck = Object.freeze({
61
+ name: 'pug',
62
+
63
+ /**
64
+ * Every rule id this check can report.
65
+ *
66
+ * @returns {string[]}
67
+ */
68
+ rules() {
69
+ return Object.values(PUG_RULES)
70
+ },
71
+
72
+ /**
73
+ * Check the repo's Pug templates; with `fix`, re-indent the 2-space ones. With
74
+ * `pug/indent` under `nera-stan.skip`, nothing is re-indented.
75
+ *
76
+ * @param {{ root: string, settings: object, fix?: boolean }} context
77
+ * @returns {Promise<{ findings: { file: string, line: number, column: number, rule: string,
78
+ * message: string, fixable: boolean }[] }>}
79
+ */
80
+ async run({ root, settings, fix = false }) {
81
+ const files = await listFiles({ root, settings }, PUG_FILES)
82
+ const write = fix && !Object.hasOwn(settings.skip, PUG_RULES.indent)
83
+ const findings = files.flatMap((file) => templateFindings(root, file, write)
84
+ .map((finding) => ({ file: repoFile(root, file), fixable: false, ...finding })))
85
+ return { findings }
86
+ },
87
+ })
88
+
89
+ /**
90
+ * The findings of one template file, after re-indenting it when `write` is set and the fix
91
+ * applies. Without `write`, the `pug/indent` findings of a file the fix applies to are fixable.
92
+ */
93
+ function templateFindings(root, file, write) {
94
+ const { findings, fixed } = inspect(readFileSync(file, 'utf8'), file)
95
+ if (fixed === null) {
96
+ return findings
97
+ }
98
+ const isIndent = (finding) => finding.rule === PUG_RULES.indent
99
+ if (!write) {
100
+ return findings.map((finding) => isIndent(finding)
101
+ ? { ...finding, fixable: true, message: `${finding.message}${FIX_HINT}` }
102
+ : finding)
103
+ }
104
+ if (!writeInside(root, repoFile(root, file), fixed)) {
105
+ return findings.map((finding) => isIndent(finding)
106
+ ? { ...finding, message: `${finding.message}, but ${OUTSIDE_REPO}` }
107
+ : finding)
108
+ }
109
+ return checkTemplate(fixed, file)
110
+ }
111
+
112
+ /**
113
+ * The findings of one template.
114
+ *
115
+ * @param {string} source - The template's text.
116
+ * @param {string} filename - Its path, for Pug's error messages.
117
+ * @returns {{ line: number, column: number, rule: string, message: string }[]}
118
+ */
119
+ export function checkTemplate(source, filename) {
120
+ return inspect(source, filename).findings
121
+ }
122
+
123
+ /**
124
+ * The findings of one template, and its re-indented text when it has a `pug/indent`
125
+ * finding the fix removes, else `null`.
126
+ */
127
+ function inspect(source, filename) {
128
+ let parsed
129
+ try {
130
+ parsed = parseTemplate(source, filename)
131
+ } catch (error) {
132
+ return { findings: [syntaxFinding(error)], fixed: null }
133
+ }
134
+ const findings = [...indentFindings(source, parsed.tokens), ...tokenFindings(parsed.tokens)]
135
+ const fixed = findings.some((finding) => finding.rule === PUG_RULES.indent)
136
+ ? reindented(source, parsed, filename)
137
+ : null
138
+ return { findings, fixed }
139
+ }
140
+
141
+ /** The template's tokens and its AST; throws Pug's error when it does not lex or parse. */
142
+ function parseTemplate(source, filename) {
143
+ const tokens = lex(source, { filename })
144
+ const ast = parse(tokens.map(withDefaultExtension), { filename, src: source })
145
+ return { tokens, ast }
146
+ }
147
+
148
+ /**
149
+ * The template re-indented from 2 to 4 spaces per level, or `null` when the fix does not
150
+ * apply. It applies when every line of Pug structure is indented with spaces only and every
151
+ * nested level lies exactly 2 spaces deeper than its parent. A structure line's indentation
152
+ * doubles; a continuation line of an attribute list moves with its structure line; the lines
153
+ * of a text block (`p.`, `script.`, a filter, a `//` comment, a `-` code block) move by the
154
+ * block's own indentation, so the block's base doubles like a code line and the whitespace
155
+ * inside it stays as it was. A fix whose result does not parse to the same tree as the
156
+ * template, positions aside, is no fix: the result is `null`.
157
+ *
158
+ * @param {string} source - The template's text.
159
+ * @param {{ tokens: object[], ast: object }} parsed - From `parseTemplate(source)`.
160
+ * @param {string} filename - Its path, for Pug's error messages.
161
+ * @returns {string | null}
162
+ */
163
+ function reindented(source, { tokens, ast }, filename) {
164
+ const parts = source.split(LINE_BREAK)
165
+ const lines = lineTexts(parts)
166
+ const { starts, blocks } = lineRoles(tokens)
167
+ if (!isHalfIndented(lines, starts)) {
168
+ return null
169
+ }
170
+
171
+ const shifts = new Map()
172
+ let shift = 0
173
+ for (const [index, text] of lines.entries()) {
174
+ const line = index + 1
175
+ if (starts.has(line) && text.trim() !== '') {
176
+ shift = leadingWhitespace(text).length
177
+ }
178
+ shifts.set(line, shift)
179
+ }
180
+ for (const block of blocks) {
181
+ const base = Math.min(...block.filter((line) => lines[line - 1].trim() !== '')
182
+ .map((line) => /^ */.exec(lines[line - 1])[0].length))
183
+ block.forEach((line) => shifts.set(line, Number.isFinite(base) ? base : 0))
184
+ }
185
+
186
+ const textLines = new Set(blocks.flat())
187
+ const text = parts.map((part, index) => {
188
+ const line = index / 2 + 1
189
+ const isBlankCode = part.trim() === '' && !textLines.has(line)
190
+ return index % 2 === 1 || part === '' || isBlankCode ? part : ' '.repeat(shifts.get(line)) + part
191
+ }).join('')
192
+ try {
193
+ return sameTree(parseTemplate(text, filename).ast, ast) ? text : null
194
+ } catch {
195
+ return null
196
+ }
197
+ }
198
+
199
+ /**
200
+ * The lines that start a line of Pug structure, and the lines of each text block.
201
+ *
202
+ * @returns {{ starts: Set<number>, blocks: number[][] }}
203
+ */
204
+ function lineRoles(tokens) {
205
+ const starts = new Set()
206
+ const blocks = []
207
+ let block = null
208
+ for (const token of tokens) {
209
+ const line = token.loc.start.line
210
+ if (token.type === 'start-pipeless-text') {
211
+ block = []
212
+ } else if (token.type === 'end-pipeless-text') {
213
+ blocks.push(block)
214
+ block = null
215
+ } else if (block !== null) {
216
+ if (token.type === 'text') {
217
+ block.push(line)
218
+ }
219
+ } else if (LINE_STARTS.has(token.type)) {
220
+ starts.add(line)
221
+ }
222
+ }
223
+ return { starts, blocks }
224
+ }
225
+
226
+ /** Whether every structure line is indented with spaces, each level 2 deeper than its parent. */
227
+ function isHalfIndented(lines, starts) {
228
+ const levels = [0]
229
+ for (const line of [...starts].sort((a, b) => a - b)) {
230
+ const text = lines[line - 1] ?? ''
231
+ const indent = leadingWhitespace(text)
232
+ if (indent === text) {
233
+ continue
234
+ }
235
+ if (indent.includes('\t')) {
236
+ return false
237
+ }
238
+ while (levels.at(-1) > indent.length) {
239
+ levels.pop()
240
+ }
241
+ if (indent.length > levels.at(-1)) {
242
+ if (indent.length - levels.at(-1) !== HALF_INDENT) {
243
+ return false
244
+ }
245
+ levels.push(indent.length)
246
+ }
247
+ }
248
+ return true
249
+ }
250
+
251
+ /** The lines of a source split by `LINE_BREAK`, without the line breaks between them. */
252
+ function lineTexts(parts) {
253
+ return parts.filter((_, index) => index % 2 === 0)
254
+ }
255
+
256
+ /** The spaces and tabs a line starts with. */
257
+ function leadingWhitespace(text) {
258
+ return /^[ \t]*/.exec(text)[0]
259
+ }
260
+
261
+ /** Whether two Pug ASTs are the same tree, ignoring where their nodes stand. */
262
+ function sameTree(a, b) {
263
+ const withoutPositions = (key, value) => (POSITION_KEYS.has(key) ? undefined : value)
264
+ return JSON.stringify(a, withoutPositions) === JSON.stringify(b, withoutPositions)
265
+ }
266
+
267
+ /**
268
+ * A copy of the token, with `.pug` added to an `include` or `extends` path without an
269
+ * extension, as Pug's own compiler does before it parses; without it the parser takes
270
+ * `include ./setup` for a raw include. The copy also keeps the parser, which consumes
271
+ * the tokens it is given, off the array the rules read.
272
+ */
273
+ function withDefaultExtension(token) {
274
+ if (token.type === 'path' && path.extname(token.val) === '') {
275
+ return { ...token, val: `${token.val}.pug` }
276
+ }
277
+ return { ...token }
278
+ }
279
+
280
+ function syntaxFinding(error) {
281
+ const what = error.msg ? `${error.msg} (${error.code})` : error.message
282
+ return {
283
+ line: error.line ?? 1,
284
+ column: error.column ?? 1,
285
+ rule: PUG_RULES.syntax,
286
+ message: `Pug cannot parse the template: ${what}: fix the template at this line`,
287
+ }
288
+ }
289
+
290
+ /** One finding per line of Pug structure whose indentation has a tab or is no multiple of 4. */
291
+ function indentFindings(source, tokens) {
292
+ const lines = lineTexts(source.split(LINE_BREAK))
293
+ const seen = new Set()
294
+ const findings = []
295
+ let inText = false
296
+ for (const token of tokens) {
297
+ if (token.type === 'start-pipeless-text' || token.type === 'end-pipeless-text') {
298
+ inText = token.type === 'start-pipeless-text'
299
+ continue
300
+ }
301
+ const line = token.loc.start.line
302
+ if (inText || !LINE_STARTS.has(token.type) || seen.has(line)) {
303
+ continue
304
+ }
305
+ seen.add(line)
306
+ const text = lines[line - 1] ?? ''
307
+ const indent = leadingWhitespace(text)
308
+ if (indent === text) {
309
+ continue
310
+ }
311
+ if (indent.includes('\t')) {
312
+ findings.push({
313
+ line,
314
+ column: indent.indexOf('\t') + 1,
315
+ rule: PUG_RULES.noTabs,
316
+ message: `Indentation uses a tab: indent with ${INDENT} spaces per level`,
317
+ })
318
+ } else if (indent.length % INDENT !== 0) {
319
+ findings.push({
320
+ line,
321
+ column: 1,
322
+ rule: PUG_RULES.indent,
323
+ message: `Indentation of ${indent.length} spaces is not a multiple of ${INDENT}: ` +
324
+ `indent each level by ${INDENT} spaces`,
325
+ })
326
+ }
327
+ }
328
+ return findings
329
+ }
330
+
331
+ /** The quote and class findings of the attribute and class tokens. */
332
+ function tokenFindings(tokens) {
333
+ const findings = []
334
+ for (const token of tokens) {
335
+ const { line, column } = token.loc.start
336
+ if (token.type === 'class') {
337
+ findings.push(...classFindings([token.val], line, column, `.${token.val}`))
338
+ }
339
+ if (token.type !== 'attribute' || typeof token.val !== 'string') {
340
+ continue
341
+ }
342
+ const double = DOUBLE_QUOTED.exec(token.val)
343
+ if (double && !double[1].includes('\'')) {
344
+ findings.push({
345
+ line,
346
+ column,
347
+ rule: PUG_RULES.quotes,
348
+ message: `Attribute "${token.name}" has the double-quoted value ${token.val}: ` +
349
+ 'write it in single quotes, double quotes only around a value that contains a single quote',
350
+ })
351
+ }
352
+ const literal = token.name === 'class' && STRING_LITERAL.exec(token.val)
353
+ if (literal) {
354
+ const names = literal[2].split(/\s+/).filter(Boolean)
355
+ findings.push(...classFindings(names, line, column, `class=${token.val}`))
356
+ }
357
+ }
358
+ return findings
359
+ }
360
+
361
+ function classFindings(names, line, column, written) {
362
+ return names.filter((name) => !CLASS_NAME.test(name)).map((name) => ({
363
+ line,
364
+ column,
365
+ rule: PUG_RULES.classPattern,
366
+ message: `Expected class "${name}" (${written}) to be BEM, ${BEM_HINT}: ` +
367
+ 'rename the class (renaming a published class is a major release)',
368
+ }))
369
+ }