@nera-static/test-utils 0.0.0-stage → 1.0.1
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.
- package/CHANGELOG.md +28 -0
- package/LICENSE +21 -0
- package/README.md +479 -2
- package/package.json +71 -5
- package/src/cli.js +182 -0
- package/src/console.js +24 -0
- package/src/contrast.js +34 -0
- package/src/core.js +26 -0
- package/src/files.js +128 -0
- package/src/html.js +126 -0
- package/src/index.js +10 -0
- package/src/publish-template.js +295 -0
- package/src/site.js +179 -0
- package/src/theme/contract.js +399 -0
- package/src/theme/coupling.js +136 -0
- package/src/theme/fixture.js +202 -0
- package/src/theme/index.js +9 -0
- package/src/theme/override.js +114 -0
- package/src/theme/plugin-classes.js +115 -0
- package/src/theme/subdirectory.js +165 -0
- package/src/theme/suite.js +150 -0
- package/src/theme/tokens.js +228 -0
- package/src/vitest.js +49 -0
- package/src/yaml.js +75 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
// Temporary mirrors of a theme repo's fixture site, the variant builds made
|
|
2
|
+
// from them and the `globalSetup` that builds them once per run, as the
|
|
3
|
+
// themes' `test/helpers/site.js` and `test/global-setup.js` do.
|
|
4
|
+
//
|
|
5
|
+
// A mirror is a fresh temp dir holding symlinks to the repo's `views/`,
|
|
6
|
+
// `assets/`, `config/`, `package.json` and `node_modules/` and a copy of the
|
|
7
|
+
// fixture at the same relative path (`test/site` by default), so the
|
|
8
|
+
// fixture's `theme: ../..` and its plugin lookups resolve exactly as in the
|
|
9
|
+
// repo, and the fixture's own `public/` is never touched.
|
|
10
|
+
import fs from 'node:fs'
|
|
11
|
+
import path from 'node:path'
|
|
12
|
+
import { isPlainObject } from '@nera-static/plugin-utils/values'
|
|
13
|
+
import { tempDir } from '../files.js'
|
|
14
|
+
import { nera } from '../cli.js'
|
|
15
|
+
|
|
16
|
+
const LINKED = Object.freeze(['views', 'assets', 'config', 'package.json', 'node_modules'])
|
|
17
|
+
const NOT_COPIED = new Set(['public', 'node_modules', '.nera-cache'])
|
|
18
|
+
// plugin-search's indexes, which a direct `nera build` of the fixture leaves
|
|
19
|
+
// in its assets: every mirror's build writes its own, or none.
|
|
20
|
+
const SEARCH_INDEX = /^theme\/assets\/search-index[^/]*\.json$/
|
|
21
|
+
const CACHE = '.nera-cache'
|
|
22
|
+
|
|
23
|
+
function checkRoot(helper, root) {
|
|
24
|
+
if (typeof root !== 'string' || !path.isAbsolute(root) || !fs.existsSync(root)) {
|
|
25
|
+
throw new TypeError(`${helper} expects root as the absolute path of the theme repo, got ${JSON.stringify(root)}. Anchor it on the test file: path.resolve(import.meta.dirname, '..').`)
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function fixtureDir(helper, root, fixture) {
|
|
30
|
+
const dir = typeof fixture === 'string' ? path.resolve(root, fixture) : root
|
|
31
|
+
const inside = path.relative(root, dir)
|
|
32
|
+
if (inside === '' || inside.startsWith('..') || path.isAbsolute(inside)) {
|
|
33
|
+
throw new TypeError(`${helper} expects fixture as a path inside the repo, e.g. 'test/site', got ${JSON.stringify(fixture)}.`)
|
|
34
|
+
}
|
|
35
|
+
if (!fs.existsSync(dir)) throw new Error(`${helper}: the fixture ${dir} does not exist.`)
|
|
36
|
+
return dir
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Copy the theme's fixture site into a fresh temp mirror of the repo, then
|
|
41
|
+
* let `mutate(site)` change the copy.
|
|
42
|
+
*
|
|
43
|
+
* Not copied: the fixture's `public/` and `node_modules/`, plugin-search's
|
|
44
|
+
* `theme/assets/search-index*.json` and, unless `cache` is set, the
|
|
45
|
+
* plugin-images cache `.nera-cache/`. A repo entry that does not exist is
|
|
46
|
+
* not linked. Inside a test file the mirror is removed after the file; from a
|
|
47
|
+
* `globalSetup`, remove `base` in its teardown (`themeGlobalSetup` does).
|
|
48
|
+
*
|
|
49
|
+
* @param {{ root: string, name: string, mutate?: (site: string) => void, fixture?: string, cache?: boolean }} options
|
|
50
|
+
* `root`: absolute repo root; `name`: names the temp dir; `mutate`: a synchronous change of the copy;
|
|
51
|
+
* `fixture`: the fixture's path in the repo (`'test/site'`); `cache`: copy `.nera-cache/` too
|
|
52
|
+
* @returns {{ base: string, site: string }} the mirror's root and the copied fixture in it
|
|
53
|
+
*/
|
|
54
|
+
export function mirrorFixture({ root, name, mutate, fixture = 'test/site', cache = false } = {}) {
|
|
55
|
+
checkRoot('mirrorFixture({ root })', root)
|
|
56
|
+
if (typeof name !== 'string' || !/^[\w.-]+$/.test(name)) {
|
|
57
|
+
throw new TypeError(`mirrorFixture({ name }) expects a plain name such as 'default' or 'sub', got ${JSON.stringify(name)}.`)
|
|
58
|
+
}
|
|
59
|
+
if (mutate !== undefined && mutate !== null && typeof mutate !== 'function') {
|
|
60
|
+
throw new TypeError(`mirrorFixture({ mutate }) expects a function (site) => void, or null for the fixture as committed, got ${typeof mutate}.`)
|
|
61
|
+
}
|
|
62
|
+
const source = fixtureDir('mirrorFixture({ fixture })', root, fixture)
|
|
63
|
+
|
|
64
|
+
const base = tempDir(`nera-mirror-${name}-`)
|
|
65
|
+
for (const entry of LINKED) {
|
|
66
|
+
if (fs.existsSync(path.join(root, entry))) fs.symlinkSync(path.join(root, entry), path.join(base, entry))
|
|
67
|
+
}
|
|
68
|
+
const site = path.join(base, path.relative(root, source))
|
|
69
|
+
fs.cpSync(source, site, {
|
|
70
|
+
recursive: true,
|
|
71
|
+
filter: (src) => {
|
|
72
|
+
const rel = path.relative(source, src).split(path.sep)
|
|
73
|
+
if (rel[0] === CACHE) return cache
|
|
74
|
+
return !NOT_COPIED.has(rel[0]) && !SEARCH_INDEX.test(rel.join('/'))
|
|
75
|
+
},
|
|
76
|
+
})
|
|
77
|
+
if (mutate) {
|
|
78
|
+
// A mutate that fails leaves no mirror behind, also in a globalSetup.
|
|
79
|
+
try {
|
|
80
|
+
const result = mutate(site)
|
|
81
|
+
if (typeof result?.then === 'function') {
|
|
82
|
+
throw new TypeError(`mirrorFixture({ mutate }) of "${name}" returned a promise. Make it synchronous (fs.*Sync): the copy is built right after it returns.`)
|
|
83
|
+
}
|
|
84
|
+
} catch (err) {
|
|
85
|
+
fs.rmSync(base, { recursive: true, force: true })
|
|
86
|
+
throw err
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return { base, site }
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Append raw YAML to one of a copied site's config files (later keys win).
|
|
94
|
+
*
|
|
95
|
+
* @param {string} site the copied site (from `mirrorFixture`)
|
|
96
|
+
* @param {string} file the file below `config/`, e.g. `'app.yaml'`
|
|
97
|
+
* @param {string} text YAML lines, e.g. `'base_path: /sub'`
|
|
98
|
+
*/
|
|
99
|
+
export function appendYaml(site, file, text) {
|
|
100
|
+
const target = path.join(site, 'config', file)
|
|
101
|
+
if (!fs.existsSync(target)) {
|
|
102
|
+
throw new Error(`appendYaml: ${target} does not exist. Write the whole file with fs.writeFileSync instead.`)
|
|
103
|
+
}
|
|
104
|
+
fs.appendFileSync(target, `\n${text}\n`)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const removeAll = (results) => {
|
|
108
|
+
for (const { base } of results) fs.rmSync(base, { recursive: true, force: true })
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async function buildVariant({ root, fixture, cache }, name, mutate) {
|
|
112
|
+
const { base, site } = mirrorFixture({ root, name, mutate, fixture, cache })
|
|
113
|
+
try {
|
|
114
|
+
const build = await nera(site, ['build'], { root })
|
|
115
|
+
const validate = await nera(site, ['validate', '--json'], { root })
|
|
116
|
+
const check = await nera(site, ['check', '--json'], { root })
|
|
117
|
+
return { name, base, site, public: path.join(site, 'public'), build, validate, check }
|
|
118
|
+
} catch (err) {
|
|
119
|
+
fs.rmSync(base, { recursive: true, force: true })
|
|
120
|
+
throw err
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Build each variant of the fixture in its own mirror: `nera build`, then
|
|
126
|
+
* `nera validate --json` and `nera check --json` on the result. Every result
|
|
127
|
+
* keeps each command's `{ code, stdout, stderr }`; a failing build is a
|
|
128
|
+
* result, not an error.
|
|
129
|
+
*
|
|
130
|
+
* Without `warmCache` all variants build in parallel, without the fixture's
|
|
131
|
+
* `.nera-cache/`. With it (themes whose plugin-images cache takes minutes to
|
|
132
|
+
* fill cold) every mirror gets a copy of the fixture's `.nera-cache/`; the
|
|
133
|
+
* first variant builds alone, its cache is copied back into the fixture (keep
|
|
134
|
+
* it git-ignored, cache it in CI), and the other variants then build from
|
|
135
|
+
* that warm cache, in parallel.
|
|
136
|
+
*
|
|
137
|
+
* When a build cannot run at all, every mirror made so far is removed
|
|
138
|
+
* before the error is thrown.
|
|
139
|
+
*
|
|
140
|
+
* @param {{ root: string, variants: Record<string, ((site: string) => void) | null>, warmCache?: boolean, fixture?: string }} options
|
|
141
|
+
* `variants`: name -> synchronous change of the copy, `null` for the fixture as committed
|
|
142
|
+
* @returns {Promise<Record<string, { name: string, base: string, site: string, public: string, build: object, validate: object, check: object }>>}
|
|
143
|
+
*/
|
|
144
|
+
export async function buildVariants({ root, variants, warmCache = false, fixture = 'test/site' } = {}) {
|
|
145
|
+
checkRoot('buildVariants({ root })', root)
|
|
146
|
+
if (!isPlainObject(variants) || Object.keys(variants).length === 0) {
|
|
147
|
+
throw new TypeError('buildVariants({ variants }) expects an object of { name: mutate | null } with at least one entry, e.g. { default: null, sub: (site) => appendYaml(site, \'app.yaml\', \'base_path: /sub\') }.')
|
|
148
|
+
}
|
|
149
|
+
const source = fixtureDir('buildVariants({ fixture })', root, fixture)
|
|
150
|
+
const entries = Object.entries(variants)
|
|
151
|
+
const done = []
|
|
152
|
+
|
|
153
|
+
const settle = async (batch, cache) => {
|
|
154
|
+
const settled = await Promise.allSettled(batch.map(([name, mutate]) => buildVariant({ root, fixture, cache }, name, mutate)))
|
|
155
|
+
done.push(...settled.filter((s) => s.status === 'fulfilled').map((s) => s.value))
|
|
156
|
+
const failed = settled.find((s) => s.status === 'rejected')
|
|
157
|
+
if (failed) {
|
|
158
|
+
removeAll(done)
|
|
159
|
+
throw failed.reason
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
if (warmCache) {
|
|
164
|
+
await settle(entries.slice(0, 1), true)
|
|
165
|
+
const warm = path.join(done[0].site, CACHE)
|
|
166
|
+
if (fs.existsSync(warm)) {
|
|
167
|
+
fs.rmSync(path.join(source, CACHE), { recursive: true, force: true })
|
|
168
|
+
fs.cpSync(warm, path.join(source, CACHE), { recursive: true })
|
|
169
|
+
}
|
|
170
|
+
await settle(entries.slice(1), true)
|
|
171
|
+
} else {
|
|
172
|
+
await settle(entries, false)
|
|
173
|
+
}
|
|
174
|
+
return Object.fromEntries(done.map((result) => [result.name, result]))
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* A vitest `globalSetup` that builds the variants once per run, before any
|
|
179
|
+
* test file, and hands them to the tests as `inject(key)`; its teardown
|
|
180
|
+
* removes every mirror. In `test/global-setup.js`:
|
|
181
|
+
* `export const { setup, teardown } = themeGlobalSetup({ root, variants })`.
|
|
182
|
+
*
|
|
183
|
+
* @param {{ root: string, variants: Record<string, ((site: string) => void) | null>, warmCache?: boolean, fixture?: string, key?: string }} options
|
|
184
|
+
* as `buildVariants`, plus `key`: the name the tests inject (`'builds'`)
|
|
185
|
+
* @returns {{ setup: (project: { provide: (key: string, value: unknown) => void }) => Promise<void>, teardown: () => void }}
|
|
186
|
+
*/
|
|
187
|
+
export function themeGlobalSetup({ key = 'builds', ...options } = {}) {
|
|
188
|
+
if (typeof key !== 'string' || key === '') {
|
|
189
|
+
throw new TypeError(`themeGlobalSetup({ key }) expects the name the tests inject, e.g. 'builds', got ${JSON.stringify(key)}.`)
|
|
190
|
+
}
|
|
191
|
+
let builds = {}
|
|
192
|
+
return {
|
|
193
|
+
async setup(project) {
|
|
194
|
+
builds = await buildVariants(options)
|
|
195
|
+
project.provide(key, builds)
|
|
196
|
+
},
|
|
197
|
+
teardown() {
|
|
198
|
+
removeAll(Object.values(builds))
|
|
199
|
+
builds = {}
|
|
200
|
+
},
|
|
201
|
+
}
|
|
202
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Entry point `@nera-static/test-utils/theme`: fixture mirror, variant builds,
|
|
2
|
+
// global setup and the theme suites.
|
|
3
|
+
export { mirrorFixture, appendYaml, buildVariants, themeGlobalSetup } from './fixture.js'
|
|
4
|
+
export { contractSuite } from './contract.js'
|
|
5
|
+
export { couplingSuite } from './coupling.js'
|
|
6
|
+
export { overrideSuite } from './override.js'
|
|
7
|
+
export { pluginClassesSuite } from './plugin-classes.js'
|
|
8
|
+
export { subdirectorySuite } from './subdirectory.js'
|
|
9
|
+
export { tokensSuite } from './tokens.js'
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// §S7 "Per-file override" of a theme: the fixture's own copy of a footer
|
|
2
|
+
// partial prints a marker inside the theme's footer on every page, and a
|
|
3
|
+
// build without it falls back to the theme's partial. Modelled on the five
|
|
4
|
+
// themes' `test/override.test.js`.
|
|
5
|
+
import { elementByClass } from '../html.js'
|
|
6
|
+
import { checkClassOption, checkPublicOption, classIndex, isClassName, readPages, registerCases } from './suite.js'
|
|
7
|
+
|
|
8
|
+
const isClassList = (value) => Array.isArray(value) && value.every(isClassName)
|
|
9
|
+
|
|
10
|
+
function normalize({ overridden, fallback, marker, footerClass = 'site-footer', before = [], after = ['site-footer__legal', 'site-footer__copy'], minPages = 1 } = {}) {
|
|
11
|
+
checkPublicOption('overrideSuite({ overridden })', overridden, 'builds.default.public')
|
|
12
|
+
if (fallback !== undefined) checkPublicOption('overrideSuite({ fallback })', fallback, 'builds.noplugins.public')
|
|
13
|
+
if (typeof marker !== 'string' || marker.trim() === '') {
|
|
14
|
+
throw new TypeError(`overrideSuite({ marker }) expects the exact text the fixture's override prints, e.g. '<!-- fixture: footer-extra override-->', got ${JSON.stringify(marker)}.`)
|
|
15
|
+
}
|
|
16
|
+
checkClassOption('overrideSuite({ footerClass })', footerClass)
|
|
17
|
+
if (!isClassList(before)) throw new TypeError(`overrideSuite({ before }) expects class names rendered before the marker inside the footer, e.g. ['address'], got ${JSON.stringify(before)}.`)
|
|
18
|
+
if (!isClassList(after)) throw new TypeError(`overrideSuite({ after }) expects class names rendered after the marker inside the footer, e.g. ['site-footer__legal', 'site-footer__copy'], got ${JSON.stringify(after)}.`)
|
|
19
|
+
if (!Number.isInteger(minPages) || minPages < 1) throw new TypeError(`overrideSuite({ minPages }) expects the least number of pages the build renders (an integer >= 1), got ${JSON.stringify(minPages)}.`)
|
|
20
|
+
return { overridden, fallback, marker, footerClass, before, after, minPages }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Case: every page of the overridden build holds the marker once, inside
|
|
25
|
+
* `footer.<footerClass>`, after each `before` class and before each `after`
|
|
26
|
+
* class, so the theme's footer still renders around it.
|
|
27
|
+
*/
|
|
28
|
+
function rendersOverride({ overridden, marker, footerClass, before, after, minPages }) {
|
|
29
|
+
const { built, problems } = readPages(overridden, 'the build with the override')
|
|
30
|
+
if (problems.length > 0) return problems
|
|
31
|
+
if (built.length < minPages) {
|
|
32
|
+
problems.push(`${overridden} holds ${built.length} pages, expected at least ${minPages}. A page lost its layout or the build stopped early; compare build.stdout with the fixture's pages.`)
|
|
33
|
+
}
|
|
34
|
+
for (const { file, html } of built) {
|
|
35
|
+
const footer = elementByClass(html, 'footer', footerClass)
|
|
36
|
+
if (footer === undefined) {
|
|
37
|
+
problems.push(`${file}: no <footer class="${footerClass}">. The theme's layout must render the footer the override goes into.`)
|
|
38
|
+
continue
|
|
39
|
+
}
|
|
40
|
+
const at = footer.indexOf(marker)
|
|
41
|
+
if (at === -1) {
|
|
42
|
+
problems.push(`${file}: footer.${footerClass} does not contain the marker ${marker}. Include the overridable partial inside the footer, so the site's copy replaces the theme's file per file.`)
|
|
43
|
+
continue
|
|
44
|
+
}
|
|
45
|
+
const count = html.split(marker).length - 1
|
|
46
|
+
if (count !== 1) problems.push(`${file}: the marker ${marker} appears ${count} times, expected once. Include the overridable partial exactly once.`)
|
|
47
|
+
for (const name of before) {
|
|
48
|
+
const index = classIndex(footer, name)
|
|
49
|
+
if (index === -1 || index > at) problems.push(`${file}: .${name} ${index === -1 ? 'is missing from' : 'comes after the marker in'} footer.${footerClass}; it must render before the override.`)
|
|
50
|
+
}
|
|
51
|
+
for (const name of after) {
|
|
52
|
+
const index = classIndex(footer, name)
|
|
53
|
+
if (index === -1 || index < at) problems.push(`${file}: .${name} ${index === -1 ? 'is missing from' : 'comes before the marker in'} footer.${footerClass}; it must render after the override.`)
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return problems
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Case: without the site's copy no page holds the marker, and the theme's
|
|
61
|
+
* footer still renders with each `after` class.
|
|
62
|
+
*/
|
|
63
|
+
function fallsBack({ fallback, marker, footerClass, after }) {
|
|
64
|
+
const { built, problems } = readPages(fallback, 'the build without the override')
|
|
65
|
+
for (const { file, html } of built) {
|
|
66
|
+
if (html.includes(marker)) problems.push(`${file}: holds the marker ${marker} in the build without the override. The theme's own partial must not print it; the fallback build must not keep the site's copy.`)
|
|
67
|
+
const footer = elementByClass(html, 'footer', footerClass)
|
|
68
|
+
if (footer === undefined) {
|
|
69
|
+
problems.push(`${file}: no <footer class="${footerClass}"> without the override. The theme's partial must be a working default.`)
|
|
70
|
+
continue
|
|
71
|
+
}
|
|
72
|
+
for (const name of after) {
|
|
73
|
+
if (classIndex(footer, name) === -1) problems.push(`${file}: .${name} is missing from footer.${footerClass} without the override. The theme's footer must render it on its own.`)
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return problems
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* The cases `overrideSuite` registers, each a name and a `check()` that
|
|
81
|
+
* returns the problems it found (empty when the case holds).
|
|
82
|
+
*
|
|
83
|
+
* @param {object} options see `overrideSuite`
|
|
84
|
+
* @returns {{ name: string, check: () => string[] }[]}
|
|
85
|
+
*/
|
|
86
|
+
export function overrideCases(options) {
|
|
87
|
+
const opts = normalize(options)
|
|
88
|
+
const cases = [{ name: `renders the site's override inside footer.${opts.footerClass} on every page`, check: () => rendersOverride(opts) }]
|
|
89
|
+
if (opts.fallback !== undefined) cases.push({ name: 'falls back to the theme\'s own partial without the override', check: () => fallsBack(opts) })
|
|
90
|
+
return cases
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Register the "Per-file override" cases of a theme (§S7) in a
|
|
95
|
+
* `describe('Per-file override')`, one `it` each, on builds made by
|
|
96
|
+
* `buildVariants`/`themeGlobalSetup`.
|
|
97
|
+
*
|
|
98
|
+
* Cases: renders the site's override inside the footer on every page (once,
|
|
99
|
+
* after each `before` class, before each `after` class, at least `minPages`
|
|
100
|
+
* pages); with `fallback`, falls back to the theme's own partial (no marker,
|
|
101
|
+
* the footer with each `after` class).
|
|
102
|
+
*
|
|
103
|
+
* @param {object} options
|
|
104
|
+
* @param {string} options.overridden public/ dir of the build whose fixture overrides the partial (`builds.default.public`)
|
|
105
|
+
* @param {string} [options.fallback] public/ dir of a build without the override (`builds.noplugins.public`)
|
|
106
|
+
* @param {string} options.marker the exact text the fixture's override prints
|
|
107
|
+
* @param {string} [options.footerClass] the footer's class, default `'site-footer'`
|
|
108
|
+
* @param {string[]} [options.before] classes inside the footer that render before the override, default `[]`
|
|
109
|
+
* @param {string[]} [options.after] classes inside the footer that render after it, default `['site-footer__legal', 'site-footer__copy']`
|
|
110
|
+
* @param {number} [options.minPages] the least number of pages the overridden build renders, default 1
|
|
111
|
+
*/
|
|
112
|
+
export function overrideSuite(options) {
|
|
113
|
+
registerCases('Per-file override', overrideCases(options))
|
|
114
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// §S7 "Plugin classes exist" of a theme: every plugin it styles is
|
|
2
|
+
// installed at the minor of its peer floor, and every class the theme
|
|
3
|
+
// styles is in that package's sources (a class built at render time by the
|
|
4
|
+
// source that builds it, §S8). Modelled on the five themes'
|
|
5
|
+
// `test/plugin-classes.test.js`.
|
|
6
|
+
import fs from 'node:fs'
|
|
7
|
+
import path from 'node:path'
|
|
8
|
+
import { listFiles } from '../files.js'
|
|
9
|
+
import { checkClassList, checkRootOption, escapeRegExp, isPlainObject, registerCases } from './suite.js'
|
|
10
|
+
|
|
11
|
+
const SUITE = 'pluginClassesSuite'
|
|
12
|
+
const RANGE = /^\^(\d+)\.(\d+)\.(\d+)$/
|
|
13
|
+
const PACKAGE = /^(@[a-z0-9-]+\/)?[a-z0-9][\w.-]*$/
|
|
14
|
+
const SOURCES = ['.pug', '.js', '.css']
|
|
15
|
+
|
|
16
|
+
function normalize({ root, plugins, computed = {} } = {}) {
|
|
17
|
+
checkRootOption(SUITE, root)
|
|
18
|
+
if (!isPlainObject(plugins) || Object.keys(plugins).length === 0) {
|
|
19
|
+
throw new TypeError(`${SUITE}({ plugins }) expects the plugins the theme styles, as { '@nera-static/plugin-tags': { range: '^3.4.1', classes: ['tag-cloud'] } }, got ${JSON.stringify(plugins)}.`)
|
|
20
|
+
}
|
|
21
|
+
for (const [name, plugin] of Object.entries(plugins)) {
|
|
22
|
+
if (!PACKAGE.test(name)) throw new TypeError(`${SUITE}({ plugins }) expects package names as keys, got ${JSON.stringify(name)}.`)
|
|
23
|
+
if (!isPlainObject(plugin) || typeof plugin.range !== 'string' || !RANGE.test(plugin.range)) {
|
|
24
|
+
throw new TypeError(`${SUITE}({ plugins }): ${name} expects { range, classes } with a caret peer floor such as '^3.4.1', got ${JSON.stringify(plugin)}.`)
|
|
25
|
+
}
|
|
26
|
+
checkClassList(`${SUITE}({ plugins }): ${name}.classes`, plugin.classes, false)
|
|
27
|
+
}
|
|
28
|
+
if (!isPlainObject(computed) || !Object.values(computed).every((source) => source instanceof RegExp)) {
|
|
29
|
+
throw new TypeError(`${SUITE}({ computed }) expects the classes a plugin builds at render time, each with a RegExp for the source that builds it, e.g. { 'nav__item': /\`\\$\\{navBlock\\}__item\`/ }, got ${JSON.stringify(computed)}.`)
|
|
30
|
+
}
|
|
31
|
+
const known = new Set(Object.values(plugins).flatMap((p) => p.classes))
|
|
32
|
+
const stray = Object.keys(computed).filter((name) => !known.has(name))
|
|
33
|
+
if (stray.length > 0) throw new TypeError(`${SUITE}({ computed }) lists ${stray.join(', ')}, which no plugin's classes list. A computed class is one of them.`)
|
|
34
|
+
return { root, plugins, computed }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// The plugins export only their entry, not ./package.json, so they are read
|
|
38
|
+
// from the theme's node_modules directly.
|
|
39
|
+
const packageDir = (root, name) => path.join(root, 'node_modules', ...name.split('/'))
|
|
40
|
+
|
|
41
|
+
function readVersion(root, name) {
|
|
42
|
+
const file = path.join(packageDir(root, name), 'package.json')
|
|
43
|
+
if (!fs.existsSync(file)) return { problems: [`${name} is not installed: ${file} does not exist. Add it as a devDependency at its peer floor and run npm install.`] }
|
|
44
|
+
return { version: JSON.parse(fs.readFileSync(file, 'utf-8')).version, problems: [] }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Case: the plugin is installed at the major and minor of its floor, with a
|
|
49
|
+
* patch at or above the floor's (the lockfile may resolve a newer patch,
|
|
50
|
+
* and a patch changes no class).
|
|
51
|
+
*/
|
|
52
|
+
function atFloor(opts, name) {
|
|
53
|
+
const { version, problems } = readVersion(opts.root, name)
|
|
54
|
+
if (problems.length > 0) return problems
|
|
55
|
+
const [, major, minor, patch] = RANGE.exec(opts.plugins[name].range)
|
|
56
|
+
const installed = /^(\d+)\.(\d+)\.(\d+)$/.exec(version)
|
|
57
|
+
if (!installed || installed[1] !== major || installed[2] !== minor || Number(installed[3]) < Number(patch)) {
|
|
58
|
+
return [`${name} is installed at ${version}, not at its peer floor ${major}.${minor}.${patch} (any patch from it). Pin the devDependency to the floor, so the test reads the classes the theme promises to support.`]
|
|
59
|
+
}
|
|
60
|
+
return []
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Case: every class the theme styles is in the plugin's .pug/.js/.css
|
|
65
|
+
* sources (its own node_modules aside), a computed one by its source.
|
|
66
|
+
*/
|
|
67
|
+
function hasClasses(opts, name) {
|
|
68
|
+
const dir = packageDir(opts.root, name)
|
|
69
|
+
if (!fs.existsSync(dir)) return [`${name} is not installed: ${dir} does not exist. Add it as a devDependency at its peer floor and run npm install.`]
|
|
70
|
+
const source = listFiles(dir, SOURCES).filter((file) => !file.startsWith('node_modules/'))
|
|
71
|
+
.map((file) => fs.readFileSync(path.join(dir, file), 'utf-8')).join('\n')
|
|
72
|
+
const problems = []
|
|
73
|
+
for (const cls of opts.plugins[name].classes) {
|
|
74
|
+
const pattern = opts.computed[cls] ?? new RegExp(`(^|[^\\w-])${escapeRegExp(cls)}(?![\\w-])`, 'm')
|
|
75
|
+
if (!pattern.test(source)) {
|
|
76
|
+
problems.push(opts.computed[cls]
|
|
77
|
+
? `${name}: no source matches ${pattern}, which builds ${cls}. The plugin changed how it builds the class; update { computed }, or stop styling it.`
|
|
78
|
+
: `${name} has no class ${cls} in its ${SOURCES.join('/')} files. Stop styling it, or raise the peer floor to a version that renders it.`)
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return problems
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The cases `pluginClassesSuite` registers, two per plugin, each a name and
|
|
86
|
+
* a `check()` that returns the problems it found (empty when it holds).
|
|
87
|
+
*
|
|
88
|
+
* @param {object} options see `pluginClassesSuite`
|
|
89
|
+
* @returns {{ name: string, check: () => string[] }[]}
|
|
90
|
+
*/
|
|
91
|
+
export function pluginClassesCases(options) {
|
|
92
|
+
const opts = normalize(options)
|
|
93
|
+
return Object.entries(opts.plugins).flatMap(([name, { range }]) => [
|
|
94
|
+
{ name: `${name}: installed at the peer floor ${range.slice(1)}`, check: () => atFloor(opts, name) },
|
|
95
|
+
{ name: `${name}: every class the theme styles is in the package`, check: () => hasClasses(opts, name) },
|
|
96
|
+
])
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Register the "Plugin classes exist" cases of a theme (§S7, §S8) in a
|
|
101
|
+
* `describe('Plugin classes exist')`, two `it` per plugin, read from the
|
|
102
|
+
* packages in `<root>/node_modules` (the files of their npm tarballs).
|
|
103
|
+
*
|
|
104
|
+
* Cases per plugin: installed at the major.minor of its floor, patch at or
|
|
105
|
+
* above the floor's; every listed class is in its .pug/.js/.css sources as
|
|
106
|
+
* a whole name, a `computed` one matched by its RegExp instead.
|
|
107
|
+
*
|
|
108
|
+
* @param {object} options
|
|
109
|
+
* @param {string} options.root absolute root of the theme repo
|
|
110
|
+
* @param {Record<string, { range: string, classes: string[] }>} options.plugins package → caret peer floor and the classes the theme styles
|
|
111
|
+
* @param {Record<string, RegExp>} [options.computed] classes a plugin builds at render time → the source that builds them
|
|
112
|
+
*/
|
|
113
|
+
export function pluginClassesSuite(options) {
|
|
114
|
+
registerCases('Plugin classes exist', pluginClassesCases(options))
|
|
115
|
+
}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
// §S7 "Subdirectory deploy" of a theme: with `base_path` set, every
|
|
2
|
+
// root-absolute link, the theme's stylesheet and the theme's own links
|
|
3
|
+
// start with the base path, and the fonts the stylesheet names are written
|
|
4
|
+
// where it points. Modelled on the five themes' `test/subdirectory.test.js`.
|
|
5
|
+
import fs from 'node:fs'
|
|
6
|
+
import path from 'node:path'
|
|
7
|
+
import { attr, elementByClass, tags } from '../html.js'
|
|
8
|
+
import { checkClassOption, checkPublicOption, classAttr, escapeRegExp, isPlainObject, isRelative, readPages, registerCases } from './suite.js'
|
|
9
|
+
|
|
10
|
+
// URLs a base path never prefixes: other hosts, inline data, mail, phone, fragments.
|
|
11
|
+
const EXTERNAL = /^(https?:|\/\/|data:|mailto:|tel:|#)/
|
|
12
|
+
// The url(...) of a font file in a stylesheet.
|
|
13
|
+
const FONT_URL = /url\(\s*(['"]?)([^'")]+\.(?:woff2?|ttf|otf|eot)(?:[?#][^'")]*)?)\1\s*\)/g
|
|
14
|
+
// A brand link to the home page of the default or of a language.
|
|
15
|
+
const homePage = (basePath) => new RegExp(`^${escapeRegExp(basePath)}/([a-z]{2,3}(-[A-Za-z0-9]+)?/)?index\\.html$`)
|
|
16
|
+
|
|
17
|
+
function normalize({ publicDir, basePath, minUrls = 1, stylesheet = 'css/theme.css', brandClass = 'site-header__brand', groups = [], fonts } = {}) {
|
|
18
|
+
checkPublicOption('subdirectorySuite({ publicDir })', publicDir, 'builds.sub.public')
|
|
19
|
+
if (typeof basePath !== 'string' || !/^\/[\w.~-]+(\/[\w.~-]+)*$/.test(basePath)) {
|
|
20
|
+
throw new TypeError(`subdirectorySuite({ basePath }) expects the base_path the variant sets, without a trailing slash, e.g. '/sub', got ${JSON.stringify(basePath)}.`)
|
|
21
|
+
}
|
|
22
|
+
if (!Number.isInteger(minUrls) || minUrls < 1) throw new TypeError(`subdirectorySuite({ minUrls }) expects the least number of local href/src values over all pages (an integer >= 1), got ${JSON.stringify(minUrls)}.`)
|
|
23
|
+
if (!isRelative(stylesheet)) throw new TypeError(`subdirectorySuite({ stylesheet }) expects the theme's stylesheet relative to public/, e.g. 'css/theme.css', got ${JSON.stringify(stylesheet)}.`)
|
|
24
|
+
checkClassOption('subdirectorySuite({ brandClass })', brandClass)
|
|
25
|
+
if (!Array.isArray(groups) || !groups.every((group) => isPlainObject(group) && typeof group.tag === 'string' && /^[a-z][a-z0-9]*$/.test(group.tag))) {
|
|
26
|
+
throw new TypeError(`subdirectorySuite({ groups }) expects an array of { tag, className, links?, optional? }, e.g. [{ tag: 'nav', className: 'site-footer__legal', links: 2 }], got ${JSON.stringify(groups)}.`)
|
|
27
|
+
}
|
|
28
|
+
for (const group of groups) {
|
|
29
|
+
checkClassOption('subdirectorySuite({ groups[].className })', group.className)
|
|
30
|
+
if (group.links !== undefined && !(Number.isInteger(group.links) && group.links >= 0)) {
|
|
31
|
+
throw new TypeError(`subdirectorySuite({ groups[].links }) expects the exact number of links in ${group.tag}.${group.className}, got ${JSON.stringify(group.links)}.`)
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
if (fonts !== undefined) {
|
|
35
|
+
if (!isPlainObject(fonts) || !isRelative(fonts.dir) || (fonts.count !== undefined && !(Number.isInteger(fonts.count) && fonts.count >= 1))) {
|
|
36
|
+
throw new TypeError(`subdirectorySuite({ fonts }) expects { dir, count? }: dir relative to public/ (e.g. 'fonts/<theme>'), count the number of font files the stylesheet names, got ${JSON.stringify(fonts)}.`)
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return { publicDir, basePath, minUrls, stylesheet, brandClass, groups, fonts }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Case: every href and src that is not external, and every srcset
|
|
44
|
+
* candidate, starts with `<basePath>/`; there are at least `minUrls` of the
|
|
45
|
+
* former.
|
|
46
|
+
*/
|
|
47
|
+
function prefixesEveryUrl({ publicDir, basePath, minUrls }) {
|
|
48
|
+
const { built, problems } = readPages(publicDir, 'the build with base_path')
|
|
49
|
+
if (built.length === 0) return problems
|
|
50
|
+
const prefix = `${basePath}/`
|
|
51
|
+
let count = 0
|
|
52
|
+
for (const { file, html } of built) {
|
|
53
|
+
for (const [, name, url] of html.matchAll(/\s(href|src)="([^"]*)"/g)) {
|
|
54
|
+
if (EXTERNAL.test(url)) continue
|
|
55
|
+
count++
|
|
56
|
+
if (!url.startsWith(prefix)) problems.push(`${file}: ${name}="${url}" does not start with ${prefix}. Build the URL with app.base_path (or a helper that adds it), never as a literal root path.`)
|
|
57
|
+
}
|
|
58
|
+
for (const [, set] of html.matchAll(/\ssrcset="([^"]*)"/g)) {
|
|
59
|
+
for (const part of set.split(',')) {
|
|
60
|
+
if (!part.trim().startsWith(prefix)) problems.push(`${file}: srcset candidate "${part.trim()}" does not start with ${prefix}. Build every candidate with app.base_path.`)
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (count < minUrls) problems.push(`${publicDir}: ${count} local href/src values (not http(s):, //, data:, mailto:, tel: or #) over all pages, expected at least ${minUrls}. Fewer links than the fixture renders means pages or navigation went missing.`)
|
|
65
|
+
return problems
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Case: the first stylesheet is `<basePath>/<stylesheet>`, the brand link
|
|
70
|
+
* goes to a home page under the base path, and every link of each group
|
|
71
|
+
* starts with it.
|
|
72
|
+
*/
|
|
73
|
+
function linksTheme({ publicDir, basePath, stylesheet, brandClass, groups }) {
|
|
74
|
+
const { built, problems } = readPages(publicDir, 'the build with base_path')
|
|
75
|
+
const prefix = `${basePath}/`
|
|
76
|
+
const home = homePage(basePath)
|
|
77
|
+
for (const { file, html } of built) {
|
|
78
|
+
const first = tags(html, 'link').filter((a) => attr(a, 'rel') === 'stylesheet').map((a) => attr(a, 'href'))[0]
|
|
79
|
+
if (first !== `${prefix}${stylesheet}`) problems.push(`${file}: the first stylesheet is ${JSON.stringify(first)}, expected "${prefix}${stylesheet}". Link the theme's stylesheet first, through app.base_path.`)
|
|
80
|
+
const brand = tags(html, 'a').find((a) => classAttr(brandClass).test(a))
|
|
81
|
+
if (brand === undefined) problems.push(`${file}: no <a class="${brandClass}">. The theme's header must link the home page.`)
|
|
82
|
+
else if (!home.test(attr(brand, 'href') ?? '')) problems.push(`${file}: a.${brandClass} links ${JSON.stringify(attr(brand, 'href'))}, expected ${prefix}index.html or ${prefix}<lang>/index.html.`)
|
|
83
|
+
for (const { tag, className, links, optional = false } of groups) {
|
|
84
|
+
const element = elementByClass(html, tag, className)
|
|
85
|
+
if (element === undefined) {
|
|
86
|
+
if (!optional) problems.push(`${file}: no <${tag} class="${className}">. Render it, or mark the group { optional: true } when not every page has it.`)
|
|
87
|
+
continue
|
|
88
|
+
}
|
|
89
|
+
const hrefs = tags(element, 'a').map((a) => attr(a, 'href'))
|
|
90
|
+
if (links !== undefined && hrefs.length !== links) problems.push(`${file}: ${tag}.${className} holds ${hrefs.length} links, expected ${links}.`)
|
|
91
|
+
for (const href of hrefs) {
|
|
92
|
+
if (!(href ?? '').startsWith(prefix)) problems.push(`${file}: ${tag}.${className} links ${JSON.stringify(href)}, which does not start with ${prefix}.`)
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return problems
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Case: every font file the built stylesheet names resolves, relative to
|
|
101
|
+
* the stylesheet, to an existing file below `public/<fonts.dir>/`; with
|
|
102
|
+
* `fonts.count`, it names exactly that many.
|
|
103
|
+
*/
|
|
104
|
+
function writesFonts({ publicDir, stylesheet, fonts }) {
|
|
105
|
+
const cssFile = path.join(publicDir, stylesheet)
|
|
106
|
+
if (!fs.existsSync(cssFile)) return [`${cssFile} does not exist. The build must copy the theme's stylesheet to public/${stylesheet}.`]
|
|
107
|
+
const urls = [...fs.readFileSync(cssFile, 'utf-8').matchAll(FONT_URL)].map((match) => match[2])
|
|
108
|
+
const problems = []
|
|
109
|
+
if (fonts.count !== undefined && urls.length !== fonts.count) {
|
|
110
|
+
problems.push(`${stylesheet} names ${urls.length} font files, expected ${fonts.count}. Update { fonts: { count } } when the theme adds or drops a font, or restore the missing @font-face.`)
|
|
111
|
+
}
|
|
112
|
+
const dir = path.join(publicDir, fonts.dir)
|
|
113
|
+
for (const url of urls) {
|
|
114
|
+
if (url.startsWith('/') || /^[a-z]+:/i.test(url)) {
|
|
115
|
+
problems.push(`${stylesheet}: url(${url}) is not relative. Name the font relative to the stylesheet (e.g. ../${fonts.dir}/…), so it works under base_path and from the theme's own host.`)
|
|
116
|
+
continue
|
|
117
|
+
}
|
|
118
|
+
const target = path.resolve(path.dirname(cssFile), url.replace(/[?#].*$/, ''))
|
|
119
|
+
if (!target.startsWith(dir + path.sep)) problems.push(`${stylesheet}: url(${url}) points outside public/${fonts.dir}/. Ship the theme's fonts there.`)
|
|
120
|
+
else if (!fs.existsSync(target)) problems.push(`${stylesheet}: url(${url}) names ${path.relative(publicDir, target)}, which the build did not write. Ship the font in the theme's assets.`)
|
|
121
|
+
}
|
|
122
|
+
return problems
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* The cases `subdirectorySuite` registers, each a name and a `check()` that
|
|
127
|
+
* returns the problems it found (empty when the case holds).
|
|
128
|
+
*
|
|
129
|
+
* @param {object} options see `subdirectorySuite`
|
|
130
|
+
* @returns {{ name: string, check: () => string[] }[]}
|
|
131
|
+
*/
|
|
132
|
+
export function subdirectoryCases(options) {
|
|
133
|
+
const opts = normalize(options)
|
|
134
|
+
const cases = [
|
|
135
|
+
{ name: `prefixes every root-absolute href, src and srcset with ${opts.basePath}/`, check: () => prefixesEveryUrl(opts) },
|
|
136
|
+
{ name: `links the theme's stylesheet and the theme's own links under ${opts.basePath}/`, check: () => linksTheme(opts) },
|
|
137
|
+
]
|
|
138
|
+
if (opts.fonts !== undefined) cases.push({ name: `writes every font the stylesheet names under public/${opts.fonts.dir}/`, check: () => writesFonts(opts) })
|
|
139
|
+
return cases
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Register the "Subdirectory deploy" cases of a theme (§S7) in a
|
|
144
|
+
* `describe('Subdirectory deploy')`, one `it` each, on a build with
|
|
145
|
+
* `base_path` set (made by `buildVariants`/`themeGlobalSetup`).
|
|
146
|
+
*
|
|
147
|
+
* Cases: prefixes every root-absolute href, src and srcset with the base
|
|
148
|
+
* path (`http(s):`, `mailto:`, `tel:` and `#` links excepted; at least
|
|
149
|
+
* `minUrls`); links the theme's stylesheet first and the brand link and
|
|
150
|
+
* each group's links under the base path; with `fonts`, writes every font
|
|
151
|
+
* the stylesheet names under `public/<fonts.dir>/`.
|
|
152
|
+
*
|
|
153
|
+
* @param {object} options
|
|
154
|
+
* @param {string} options.publicDir public/ dir of the build with `base_path` (`builds.sub.public`)
|
|
155
|
+
* @param {string} options.basePath the variant's `base_path`, e.g. `'/sub'`
|
|
156
|
+
* @param {number} [options.minUrls] the least number of local href/src values over all pages, default 1
|
|
157
|
+
* @param {string} [options.stylesheet] the theme's stylesheet relative to public/, default `'css/theme.css'`
|
|
158
|
+
* @param {string} [options.brandClass] the class of the header's home link, default `'site-header__brand'`
|
|
159
|
+
* @param {{ tag: string, className: string, links?: number, optional?: boolean }[]} [options.groups]
|
|
160
|
+
* elements whose links must all start with the base path; `links` their exact number, `optional` when not every page has the element
|
|
161
|
+
* @param {{ dir: string, count?: number }} [options.fonts] where the theme's fonts land below public/ and how many the stylesheet names
|
|
162
|
+
*/
|
|
163
|
+
export function subdirectorySuite(options) {
|
|
164
|
+
registerCases('Subdirectory deploy', subdirectoryCases(options))
|
|
165
|
+
}
|