@nera-static/stan 1.0.0 → 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 +22 -0
  2. package/README.md +153 -13
  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,405 @@
1
+ import { existsSync, readFileSync } from 'node:fs'
2
+ import path from 'node:path'
3
+
4
+ import { isPlainObject } from '@nera-static/plugin-utils/values'
5
+
6
+ import { kindOf } from '../kind.js'
7
+ import { headingOf, headings, proseLines } from '../markdown.js'
8
+ import { isDirectory } from '../repo-files.js'
9
+ import { STRUCTURE_PREFIX } from './package.js'
10
+ import { FIRST_STEPS } from './tree.js'
11
+
12
+ /** The rule ids the docs check reports. */
13
+ export const DOCS_RULES = Object.freeze({
14
+ readmeBadges: `${STRUCTURE_PREFIX}readme-badges`,
15
+ readmeOutline: `${STRUCTURE_PREFIX}readme-outline`,
16
+ changelogFormat: `${STRUCTURE_PREFIX}changelog-format`,
17
+ license: `${STRUCTURE_PREFIX}license`,
18
+ })
19
+
20
+ /**
21
+ * The H2 sections of a README per repo kind, in order. A section is `{ title }`, with
22
+ * `optional: true` when it may be absent and `views: true` when it belongs to a plugin with
23
+ * `views/` only (required there, wrong without). `{ slot: 'feature' }` (plugin, 2-plugin-anatomy
24
+ * §4.5: plain headings without emoji) and `{ slot: 'extra' }` (starter, 4-tooling-themes §2.2)
25
+ * take any other heading at that place. Theme: 4-tooling-themes §2.1, plus theme-business's
26
+ * `app.business` section, the contract every business theme takes over. A starter's last H2,
27
+ * `## First steps`, is `structure/starter-tree`'s.
28
+ */
29
+ export const README_OUTLINES = Object.freeze({
30
+ plugin: Object.freeze([
31
+ { title: '✨ Features' },
32
+ { title: '🚀 Installation' },
33
+ { title: '🧩 Usage' },
34
+ { title: '⚙️ Configuration' },
35
+ { slot: 'feature' },
36
+ { title: '🛠️ Template Publishing', views: true },
37
+ { title: '🎨 Styling', views: true },
38
+ { title: '📊 Generated Output' },
39
+ { title: '⚠️ Warnings', optional: true },
40
+ { title: 'Known limitations', optional: true },
41
+ { title: '🧩 Compatibility' },
42
+ { title: '🧪 Development' },
43
+ { title: '🤝 Contributing' },
44
+ { title: '📦 License' },
45
+ ]),
46
+ theme: Object.freeze([
47
+ { title: 'Installation' },
48
+ { title: 'Page types' },
49
+ { title: 'Business facts: `app.business`', optional: true },
50
+ { title: 'Seams: where plugin output goes' },
51
+ { title: 'What a post may contain', optional: true },
52
+ { title: 'External links in a new tab', optional: true },
53
+ { title: 'Search', optional: true },
54
+ { title: 'Configuration: `config/theme.yaml`' },
55
+ { title: 'Translations' },
56
+ { title: 'Overriding the theme' },
57
+ { title: 'What your site must do' },
58
+ { title: 'Switching between the blog themes', optional: true },
59
+ { title: 'Accessibility and privacy' },
60
+ { title: 'Versioning' },
61
+ { title: 'Development' },
62
+ { title: 'License' },
63
+ ]),
64
+ starter: Object.freeze([
65
+ { title: 'Usage' },
66
+ { title: 'What you get' },
67
+ { slot: 'extra' },
68
+ { title: 'Requirements' },
69
+ { title: 'License' },
70
+ ]),
71
+ })
72
+
73
+ /** The `###` groups of Keep a Changelog; `### Migration from vX.x` joins them on a major (§4.6). */
74
+ export const CHANGELOG_GROUPS = Object.freeze(['Added', 'Changed', 'Deprecated', 'Removed', 'Fixed', 'Security'])
75
+
76
+ /** The holder every Nera LICENSE names. */
77
+ export const LICENSE_HOLDER = 'Michael Becker'
78
+
79
+ const README = 'README.md'
80
+ const CHANGELOG = 'CHANGELOG.md'
81
+ const LICENSE = 'LICENSE'
82
+ const MIT_TITLE = 'MIT License'
83
+ const CHANGELOG_TITLE = 'Changelog'
84
+ const UNRELEASED = '[Unreleased]'
85
+ /** `[x.y.z] - YYYY-MM-DD`, with the ` [YANKED]` mark Keep a Changelog allows. */
86
+ const VERSION_HEADING = /^\[\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?\] - \d{4}-\d{2}-\d{2}(?: \[YANKED\])?$/
87
+ const MIGRATION = /^Migration from v\d+(?:\.(?:\d+|x))*$/
88
+ const LIST_ITEM = /^[-*+]\s+\S/
89
+ const BULLET = /^- {3}\S/
90
+ /** An indented list item; right under a heading it is an indented code block, not a list. */
91
+ const INDENTED_ITEM = /^ {4,}[-*+]\s+\S/
92
+ const COPYRIGHT = /^Copyright \(c\) (\d{4}) (.+)$/
93
+ const EXCERPT_LENGTH = 40
94
+ const PLACEHOLDER = /[[\]{}<>]/
95
+ const EMOJI = /^[\p{Extended_Pictographic}\p{Emoji_Modifier}\u{FE0F}\u{200D}]+\s*/u
96
+ const GITHUB_REPO = /github\.com[/:]([^/]+)\/([^/#]+?)(?:\.git)?(?:[/#].*)?$/
97
+ /** The Test badge of any GitHub repo, the same `owner/repo` in both urls. */
98
+ const ANY_TEST_BADGE = new RegExp(
99
+ String.raw`^\[!\[Test\]\(https://github\.com/([^/]+/[^/]+)/actions/workflows/test\.yml/badge\.svg\)\]` +
100
+ String.raw`\(https://github\.com/\1/actions/workflows/test\.yml\)$`,
101
+ )
102
+
103
+ /**
104
+ * The docs check: the README's badges and H2 outline, the CHANGELOG format and the LICENSE
105
+ * line. A site gets no finding; the badges, a missing CHANGELOG and the LICENSE only concern
106
+ * a package that is published (no `"private": true`). Nothing is fixed: each finding needs
107
+ * text written by hand.
108
+ */
109
+ export const docsCheck = Object.freeze({
110
+ name: 'docs',
111
+
112
+ /**
113
+ * Every rule id this check can report.
114
+ *
115
+ * @returns {string[]}
116
+ */
117
+ rules() {
118
+ return Object.values(DOCS_RULES)
119
+ },
120
+
121
+ /**
122
+ * Check the repo's README, CHANGELOG and LICENSE.
123
+ *
124
+ * @param {{ root: string, pkg: object }} context
125
+ * @returns {{ findings: { file: string, line: number, rule: string, message: string,
126
+ * fixable: boolean }[] }}
127
+ */
128
+ run({ root, pkg }) {
129
+ const kind = kindOf(pkg)
130
+ if (kind === 'site') {
131
+ return { findings: [] }
132
+ }
133
+ const published = pkg.private !== true
134
+ const readme = readText(root, README)
135
+ const outlined = readme !== null && Object.hasOwn(README_OUTLINES, kind)
136
+ const findings = [
137
+ ...(published ? readmeBadges(readme, pkg, kind) : []),
138
+ ...(outlined ? readmeOutline(readme, kind, isDirectory(root, 'views')) : []),
139
+ ...changelogFormat(readText(root, CHANGELOG), published),
140
+ ...(published ? license(readText(root, LICENSE)) : []),
141
+ ]
142
+ return { findings: findings.map((finding) => ({ ...finding, fixable: false })) }
143
+ },
144
+ })
145
+
146
+ /**
147
+ * `structure/readme-badges`: the first two lines under the `# title` (after blank lines)
148
+ * are the Test badge and the npm badge, one per line. A missing README is reported here,
149
+ * except for a starter, whose `structure/starter-tree` reports it.
150
+ */
151
+ function readmeBadges(readme, pkg, kind) {
152
+ const rule = DOCS_RULES.readmeBadges
153
+ if (readme === null) {
154
+ return kind === 'starter'
155
+ ? []
156
+ : [{ file: README, line: 1, rule, message: `"${README}" is missing: write it, starting with the ` +
157
+ `"# ${pkg.name}" title and the Test and npm badges under it` }]
158
+ }
159
+
160
+ const title = headings(readme).find(({ level }) => level === 1)
161
+ if (!title) {
162
+ return [{
163
+ file: README,
164
+ line: 1,
165
+ rule,
166
+ message: `the README has no "# " title: start it with "# ${pkg.name}" and put the Test and npm ` +
167
+ 'badges on the two lines under it',
168
+ }]
169
+ }
170
+
171
+ const lines = readme.split(/\r?\n/)
172
+ let first = title.line
173
+ while (first < lines.length && lines[first].trim() === '') {
174
+ first += 1
175
+ }
176
+ const badges = [testBadge(pkg), npmBadge(pkg.name)]
177
+ return badges.flatMap((badge, offset) => {
178
+ const index = first + offset
179
+ const found = index < lines.length ? lines[index] : undefined
180
+ if (found !== undefined && badge.matches(found)) {
181
+ return []
182
+ }
183
+ const line = found === undefined ? title.line : index + 1
184
+ const what = found === undefined || found.trim() === '' ? 'nothing' : `"${found.trim()}"`
185
+ return [{
186
+ file: README,
187
+ line,
188
+ rule,
189
+ message: `line ${line} must be the ${badge.name} badge ${badge.position}, but holds ${what}: ` +
190
+ `write ${badge.text} there`,
191
+ }]
192
+ })
193
+ }
194
+
195
+ /** The Test badge for the repo named in `repository`, or for any GitHub repo when it names none. */
196
+ function testBadge(pkg) {
197
+ const slug = githubSlug(pkg.repository)
198
+ const target = `https://github.com/${slug ?? '<owner>/<repo>'}/actions/workflows/test.yml`
199
+ const text = `[![Test](${target}/badge.svg)](${target})`
200
+ return {
201
+ name: 'Test',
202
+ position: 'on the first line under the title',
203
+ text,
204
+ matches: (line) => (slug ? line.trimEnd() === text : ANY_TEST_BADGE.test(line.trimEnd())),
205
+ }
206
+ }
207
+
208
+ function npmBadge(name) {
209
+ const text = `[![npm version](https://img.shields.io/npm/v/${name})](https://www.npmjs.com/package/${name})`
210
+ return { name: 'npm', position: 'right under the Test badge', text, matches: (line) => line.trimEnd() === text }
211
+ }
212
+
213
+ /** `owner/repo` of a GitHub `repository` field, `null` for anything else. */
214
+ function githubSlug(repository) {
215
+ const url = isPlainObject(repository) ? repository.url : repository
216
+ const match = typeof url === 'string' ? GITHUB_REPO.exec(url) : null
217
+ return match ? `${match[1]}/${match[2]}` : null
218
+ }
219
+
220
+ /**
221
+ * `structure/readme-outline`: the README's H2 sections follow the kind's outline: known
222
+ * sections in order and spelled as listed (emoji included), each once, required ones
223
+ * present, any other heading only in the kind's slot.
224
+ */
225
+ function readmeOutline(readme, kind, hasViews) {
226
+ const rule = DOCS_RULES.readmeOutline
227
+ const outline = README_OUTLINES[kind]
228
+ const sections = outline.filter((section) => section.title)
229
+ const slot = outline.findIndex((section) => section.slot)
230
+ const h2s = headings(readme)
231
+ .filter(({ level, text }) => level === 2 && !(kind === 'starter' && `## ${text}` === FIRST_STEPS))
232
+ const findings = []
233
+ const seen = new Map()
234
+ let position = -1
235
+
236
+ const finding = (line, message) => findings.push({ file: README, line, rule, message })
237
+ const order = sections.map(({ title }) => title).join(', ')
238
+ const nextSeen = (index) => [...seen.keys()].filter((other) => other > index).sort((a, b) => a - b)[0]
239
+ const label = (index) => {
240
+ const { title, slot: name } = outline[index]
241
+ return title ? `"## ${title}"` : `the ${name} sections`
242
+ }
243
+
244
+ for (const { text, line } of h2s) {
245
+ const index = outline.findIndex((section) => section.title && sectionKey(section.title) === sectionKey(text))
246
+ if (index === -1) {
247
+ if (slot === -1) {
248
+ finding(line, `"## ${text}" is not a section of a ${kind} README: remove it or fold it into one ` +
249
+ `of ${order}`)
250
+ } else if (position < slot - 1 || position > slot) {
251
+ // Only right after the section before the slot, or after another slot section.
252
+ finding(line, `"## ${text}" is no section of the outline, so it is one of ${label(slot)}, ` +
253
+ `which go between ${label(slot - 1)} and ${label(slot + 1)}: move it there`)
254
+ } else {
255
+ if (outline[slot].slot === 'feature' && EMOJI.test(text)) {
256
+ finding(line, `the feature section "## ${text}" has an emoji: write it as a plain heading, ` +
257
+ `"## ${stripEmoji(text)}"`)
258
+ }
259
+ position = slot
260
+ }
261
+ continue
262
+ }
263
+
264
+ const section = outline[index]
265
+ if (section.views && !hasViews) {
266
+ finding(line, `"## ${text}" belongs to a plugin with views/ only, and this one ships none: remove it`)
267
+ }
268
+ if (seen.has(index)) {
269
+ finding(line, `"## ${text}" comes twice (first on line ${seen.get(index)}): merge the two sections`)
270
+ continue
271
+ }
272
+ seen.set(index, line)
273
+ if (index < position) {
274
+ finding(line, `"## ${text}" is out of order: move it before ${label(nextSeen(index) ?? position)}`)
275
+ } else {
276
+ position = index
277
+ }
278
+ if (text !== section.title) {
279
+ finding(line, `the heading "## ${text}" must read "## ${section.title}"`)
280
+ }
281
+ }
282
+
283
+ outline.forEach((section, index) => {
284
+ const required = section.title && !section.optional && (!section.views || hasViews)
285
+ if (!required || seen.has(index)) {
286
+ return
287
+ }
288
+ const next = nextSeen(index)
289
+ const line = next === undefined ? h2s.at(-1)?.line ?? 1 : seen.get(next)
290
+ const where = next === undefined ? 'at its place in the outline' : `before ${label(next)}`
291
+ const why = section.views ? ', since the plugin ships views/' : ''
292
+ finding(line, `the section "## ${section.title}" is missing${why}: add it ${where} (the order is ${order})`)
293
+ })
294
+ return findings
295
+ }
296
+
297
+ /** A heading's identity: without a leading emoji, up to a colon, in lower case. */
298
+ function sectionKey(text) {
299
+ return stripEmoji(text).split(':')[0].trim().toLowerCase()
300
+ }
301
+
302
+ function stripEmoji(text) {
303
+ return text.replace(EMOJI, '')
304
+ }
305
+
306
+ /**
307
+ * `structure/changelog-format`: Keep a Changelog: the `# Changelog` title, version headings
308
+ * `## [x.y.z] - YYYY-MM-DD` (or `## [Unreleased]`), the known `###` groups under them, and
309
+ * list items written `- ` (dash plus three spaces). Code blocks are skipped.
310
+ */
311
+ function changelogFormat(changelog, published) {
312
+ const rule = DOCS_RULES.changelogFormat
313
+ if (changelog === null) {
314
+ return published
315
+ ? [{ file: CHANGELOG, line: 1, rule, message: `"${CHANGELOG}" is missing: write it in the Keep a ` +
316
+ `Changelog format, starting with "# ${CHANGELOG_TITLE}"` }]
317
+ : []
318
+ }
319
+
320
+ const findings = []
321
+ const finding = (line, message) => findings.push({ file: CHANGELOG, line, rule, message })
322
+ const lines = proseLines(changelog).filter(({ text }) => text.trim() !== '')
323
+ let inVersion = false
324
+
325
+ if (lines[0]?.text !== `# ${CHANGELOG_TITLE}`) {
326
+ finding(lines[0]?.line ?? 1, `the CHANGELOG must start with "# ${CHANGELOG_TITLE}": write it as the first line`)
327
+ }
328
+ lines.forEach(({ text, line }, index) => {
329
+ const heading = headingOf(text)
330
+ if (heading?.level === 1) {
331
+ if (line !== lines[0].line) {
332
+ finding(line, `"${text.trim()}" is a second title: the only "# " heading is the first line, ` +
333
+ `"# ${CHANGELOG_TITLE}"; make it a "## " version heading or remove it`)
334
+ }
335
+ } else if (heading?.level === 2) {
336
+ inVersion = true
337
+ if (heading.text !== UNRELEASED && !VERSION_HEADING.test(heading.text)) {
338
+ finding(line, `"## ${heading.text}" is not a version heading: write "## [x.y.z] - YYYY-MM-DD" ` +
339
+ `(or "## ${UNRELEASED}")`)
340
+ }
341
+ } else if (heading?.level === 3) {
342
+ if (!inVersion) {
343
+ finding(line, `"### ${heading.text}" stands before any version: move it under a "## [x.y.z] - ` +
344
+ 'YYYY-MM-DD" heading')
345
+ } else if (!CHANGELOG_GROUPS.includes(heading.text) && !MIGRATION.test(heading.text)) {
346
+ finding(line, `"### ${heading.text}" is not a Keep a Changelog group: use one of ` +
347
+ `${CHANGELOG_GROUPS.join(', ')}, or "### Migration from vX.x" on a major`)
348
+ }
349
+ } else if (LIST_ITEM.test(text) && !BULLET.test(text)) {
350
+ finding(line, `the list item "${excerpt(text)}" must start with "- " (dash plus three spaces), so ` +
351
+ 'its text starts at column 4: replace its marker and the spaces after it with "- "')
352
+ } else if (INDENTED_ITEM.test(text) && headingOf(lines[index - 1]?.text ?? '')) {
353
+ finding(line, `the list item "${excerpt(text)}" is indented right under a heading, so it renders as ` +
354
+ 'a code block: start it at column 0 with "- "')
355
+ }
356
+ })
357
+ return findings
358
+ }
359
+
360
+ /**
361
+ * `structure/license`: the MIT licence, `MIT License` on line 1 and
362
+ * `Copyright (c) <year> Michael Becker` with a real year and no template brackets.
363
+ */
364
+ function license(text) {
365
+ const rule = DOCS_RULES.license
366
+ const expected = `Copyright (c) <first-commit year> ${LICENSE_HOLDER}`
367
+ if (text === null) {
368
+ return [{ file: LICENSE, line: 1, rule, message: `"${LICENSE}" is missing: add the MIT licence text with ` +
369
+ `"${MIT_TITLE}" on line 1 and "${expected}"` }]
370
+ }
371
+
372
+ const lines = text.split(/\r?\n/)
373
+ const findings = []
374
+ if (lines[0].trim() !== MIT_TITLE) {
375
+ findings.push({ file: LICENSE, line: 1, rule, message: `line 1 is "${lines[0].trim()}", but a Nera ` +
376
+ `package is MIT licensed: write "${MIT_TITLE}" there, followed by the MIT text` })
377
+ }
378
+
379
+ const index = lines.findIndex((line) => line.trim().startsWith('Copyright'))
380
+ if (index === -1) {
381
+ findings.push({ file: LICENSE, line: 1, rule, message: `the LICENSE has no copyright line: add "${expected}" ` +
382
+ 'under the title' })
383
+ return findings
384
+ }
385
+ const copyright = lines[index].trim()
386
+ const match = COPYRIGHT.exec(copyright)
387
+ const year = match ? Number(match[1]) : NaN
388
+ if (PLACEHOLDER.test(copyright) || !match || match[2] !== LICENSE_HOLDER || year > new Date().getFullYear()) {
389
+ findings.push({ file: LICENSE, line: index + 1, rule, message: `"${copyright}" is not a filled-in copyright ` +
390
+ `line: write "${expected}", without brackets` })
391
+ }
392
+ return findings
393
+ }
394
+
395
+ /** The start of a line, cut after a few words, for a message. */
396
+ function excerpt(text) {
397
+ const trimmed = text.trim()
398
+ return trimmed.length > EXCERPT_LENGTH ? `${trimmed.slice(0, EXCERPT_LENGTH)}…` : trimmed
399
+ }
400
+
401
+ /** The text of a repo file, `null` when it does not exist. */
402
+ function readText(root, file) {
403
+ const target = path.join(root, file)
404
+ return existsSync(target) ? readFileSync(target, 'utf8') : null
405
+ }