@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,399 @@
|
|
|
1
|
+
// §S7 "Contract present" of a theme, read from its sources: every view,
|
|
2
|
+
// seam, page type and block, the helpers and nothing else at the top level,
|
|
3
|
+
// no views/vendor/, every key, token and default of config/theme.yaml, every
|
|
4
|
+
// public class and t() key in views/, and nothing the theme withdrew or
|
|
5
|
+
// must not read. Modelled on the five themes' `test/contract.test.js`; what
|
|
6
|
+
// a theme renders with Pug (business's shell and page types) stays its own.
|
|
7
|
+
import fs from 'node:fs'
|
|
8
|
+
import path from 'node:path'
|
|
9
|
+
import { isDeepStrictEqual } from 'node:util'
|
|
10
|
+
import { listFiles } from '../files.js'
|
|
11
|
+
import { loadYaml } from '../yaml.js'
|
|
12
|
+
import { checkClassList, checkRootOption, classInSource, classSelector, escapeRegExp, isPlainObject, isRelative, readText, registerCases } from './suite.js'
|
|
13
|
+
|
|
14
|
+
const SUITE = 'contractSuite'
|
|
15
|
+
const IDENTIFIER = /^[A-Za-z_$][\w$]*$/
|
|
16
|
+
const PUG_VIEW = (value) => isRelative(value) && value.endsWith('.pug')
|
|
17
|
+
|
|
18
|
+
// A `- const` line, or a declaration at the first indent of a `-` block.
|
|
19
|
+
const TOP_LEVEL = /^(?:- *| {4})(?:const|let|var|function) +([A-Za-z_$][\w$]*)/gm
|
|
20
|
+
// The lines that may mention `content` without parsing it: the page loop's
|
|
21
|
+
// destructuring, the skip link's string and a `content=` attribute.
|
|
22
|
+
const CONTENT_MENTION = /\{ content, meta \}|'Skip to content'|\bcontent=/
|
|
23
|
+
// What a theme does with `content`: output it, or test it for being empty.
|
|
24
|
+
const CONTENT_USE = /^(!= content|if String\(content \|\| ''\)\.trim\(\))$/
|
|
25
|
+
|
|
26
|
+
const json = (value) => JSON.stringify(value, (_key, v) => (v instanceof RegExp ? String(v) : v))
|
|
27
|
+
|
|
28
|
+
function list(option, value, { check, example, required = true }) {
|
|
29
|
+
if (value === undefined && !required) return []
|
|
30
|
+
if (!Array.isArray(value) || (required && value.length === 0) || !value.every(check)) {
|
|
31
|
+
throw new TypeError(`${SUITE}({ ${option} }) expects ${required ? 'a non-empty' : 'an'} array such as ${example}, got ${json(value)}.`)
|
|
32
|
+
}
|
|
33
|
+
return value
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const viewList = (option, value, required = true) => list(option, value, { check: PUG_VIEW, example: '[\'partials/header.pug\'], paths relative to views/', required })
|
|
37
|
+
const nameList = (option, value, example, required = true) => list(option, value, { check: (v) => typeof v === 'string' && IDENTIFIER.test(v), example, required })
|
|
38
|
+
const textList = (option, value, example, required = true) => list(option, value, { check: (v) => typeof v === 'string' && v !== '', example, required })
|
|
39
|
+
|
|
40
|
+
function checkTokens(tokens) {
|
|
41
|
+
if (!isPlainObject(tokens) || Object.keys(tokens).length === 0 || !Object.values(tokens).every((names) => Array.isArray(names) && names.length > 0 && names.every((n) => typeof n === 'string' && n !== ''))) {
|
|
42
|
+
throw new TypeError(`${SUITE}({ tokens }) expects the token names per group, e.g. { color: ['bg', 'text'], size: ['base'] }, got ${json(tokens)}.`)
|
|
43
|
+
}
|
|
44
|
+
return tokens
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function checkValues(values) {
|
|
48
|
+
if (values === undefined) return {}
|
|
49
|
+
if (!isPlainObject(values) || !Object.keys(values).every((key) => /^[\w-]+(\.[\w-]+)*$/.test(key))) {
|
|
50
|
+
throw new TypeError(`${SUITE}({ values }) expects config defaults by dotted key, each a value or a RegExp, e.g. { label: 'Stack', 'tokens.font.body': /^'Inter', / }, got ${json(values)}.`)
|
|
51
|
+
}
|
|
52
|
+
return values
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function checkComputed(computed) {
|
|
56
|
+
if (computed === undefined) return {}
|
|
57
|
+
const isEvidence = (v) => v instanceof RegExp || (typeof v === 'string' && v !== '')
|
|
58
|
+
if (!isPlainObject(computed) || !Object.entries(computed).every(([name, evidence]) => /^[\w-]+$/.test(name) && (isEvidence(evidence) || (Array.isArray(evidence) && evidence.length > 0 && evidence.every(isEvidence))))) {
|
|
59
|
+
throw new TypeError(`${SUITE}({ computedClasses }) expects the source that builds each class, a string or RegExp (or a list of them) found in views/, e.g. { 'post-card__cover--red': ['post-card__cover--\${', '\\'red\\''] }, got ${json(computed)}.`)
|
|
60
|
+
}
|
|
61
|
+
return Object.fromEntries(Object.entries(computed).map(([name, evidence]) => [name, [evidence].flat()]))
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function normalize({
|
|
65
|
+
root,
|
|
66
|
+
views,
|
|
67
|
+
seams,
|
|
68
|
+
filledSeams = [],
|
|
69
|
+
withdrawnSeams,
|
|
70
|
+
pageTypes,
|
|
71
|
+
layout = 'layouts/layout.pug',
|
|
72
|
+
blocks,
|
|
73
|
+
helpers,
|
|
74
|
+
helpersFile = 'partials/helpers.pug',
|
|
75
|
+
globals,
|
|
76
|
+
keys,
|
|
77
|
+
tokens,
|
|
78
|
+
values,
|
|
79
|
+
tKeys,
|
|
80
|
+
classes,
|
|
81
|
+
computedClasses,
|
|
82
|
+
absentClasses,
|
|
83
|
+
pluginData,
|
|
84
|
+
contentOutputOnly = false,
|
|
85
|
+
config = 'config/theme.yaml',
|
|
86
|
+
css = 'assets/css/theme.css',
|
|
87
|
+
} = {}) {
|
|
88
|
+
checkRootOption(SUITE, root)
|
|
89
|
+
const opts = {
|
|
90
|
+
root,
|
|
91
|
+
viewsDir: path.join(root, 'views'),
|
|
92
|
+
views: viewList('views', views),
|
|
93
|
+
seams: viewList('seams', seams),
|
|
94
|
+
filledSeams: viewList('filledSeams', filledSeams, false),
|
|
95
|
+
withdrawnSeams: viewList('withdrawnSeams', withdrawnSeams, false),
|
|
96
|
+
pageTypes: viewList('pageTypes', pageTypes),
|
|
97
|
+
blocks: nameList('blocks', blocks, '[\'head\', \'main\']'),
|
|
98
|
+
helpers: nameList('helpers', helpers, '[\'pageLang\', \'hrefFor\']'),
|
|
99
|
+
globals: nameList('globals', globals, '[\'themeStack\']', false),
|
|
100
|
+
keys: textList('keys', keys, '[\'label\', \'tokens\']'),
|
|
101
|
+
tokens: checkTokens(tokens),
|
|
102
|
+
values: checkValues(values),
|
|
103
|
+
tKeys: textList('tKeys', tKeys, '[\'Skip to content\']'),
|
|
104
|
+
classes,
|
|
105
|
+
computedClasses: checkComputed(computedClasses),
|
|
106
|
+
absentClasses: absentClasses ?? [],
|
|
107
|
+
pluginData: nameList('pluginData', pluginData, '[\'tagLinks\', \'nav\']', false),
|
|
108
|
+
contentOutputOnly,
|
|
109
|
+
layout,
|
|
110
|
+
helpersFile,
|
|
111
|
+
config,
|
|
112
|
+
configFile: path.join(root, config),
|
|
113
|
+
cssName: css,
|
|
114
|
+
css: path.join(root, css),
|
|
115
|
+
}
|
|
116
|
+
checkClassList(`${SUITE}({ classes })`, classes, false)
|
|
117
|
+
checkClassList(`${SUITE}({ absentClasses })`, opts.absentClasses)
|
|
118
|
+
for (const [option, value] of [['layout', layout], ['helpersFile', helpersFile]]) {
|
|
119
|
+
if (!PUG_VIEW(value)) throw new TypeError(`${SUITE}({ ${option} }) expects a .pug file relative to views/, e.g. '${option === 'layout' ? 'layouts/layout.pug' : 'partials/helpers.pug'}', got ${json(value)}.`)
|
|
120
|
+
}
|
|
121
|
+
for (const [option, value] of [['config', config], ['css', css]]) {
|
|
122
|
+
if (!isRelative(value)) throw new TypeError(`${SUITE}({ ${option} }) expects a file relative to root, e.g. '${option === 'config' ? 'config/theme.yaml' : 'assets/css/theme.css'}', got ${json(value)}.`)
|
|
123
|
+
}
|
|
124
|
+
if (typeof contentOutputOnly !== 'boolean') throw new TypeError(`${SUITE}({ contentOutputOnly }) expects true or false, got ${json(contentOutputOnly)}.`)
|
|
125
|
+
const stray = filledSeams.filter((seam) => !opts.seams.includes(seam))
|
|
126
|
+
if (stray.length > 0) throw new TypeError(`${SUITE}({ filledSeams }) lists ${stray.join(', ')}, which { seams } does not. A filled seam is one of the seams.`)
|
|
127
|
+
const strayComputed = Object.keys(opts.computedClasses).filter((name) => !classes.includes(name))
|
|
128
|
+
if (strayComputed.length > 0) throw new TypeError(`${SUITE}({ computedClasses }) lists ${strayComputed.join(', ')}, which { classes } does not. A computed class is one of the public classes.`)
|
|
129
|
+
return opts
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const exists = (opts, view) => fs.existsSync(path.join(opts.viewsDir, view))
|
|
133
|
+
const read = (opts, view) => readText(path.join(opts.viewsDir, view), `Ship it in views/, or drop it from the ${SUITE} options.`)
|
|
134
|
+
|
|
135
|
+
// Every .pug source below views/, joined, with or without its comment lines.
|
|
136
|
+
function allViews(opts) {
|
|
137
|
+
if (!fs.existsSync(opts.viewsDir)) return ''
|
|
138
|
+
return listFiles(opts.viewsDir, ['.pug']).map((file) => fs.readFileSync(path.join(opts.viewsDir, file), 'utf-8')).join('\n')
|
|
139
|
+
}
|
|
140
|
+
const withoutComments = (source) => source.split('\n').filter((line) => !line.trim().startsWith('//')).join('\n')
|
|
141
|
+
|
|
142
|
+
const missing = (opts, list) => list.filter((view) => !exists(opts, view)).map((view) => `views/${view} does not exist. Ship it, or drop it from the ${SUITE} options.`)
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Case: every view and partial exists.
|
|
146
|
+
*/
|
|
147
|
+
const shipsViews = (opts) => missing(opts, opts.views)
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Case: every seam exists and holds only `//-` comments (a filled seam
|
|
151
|
+
* only exists), and no withdrawn seam exists.
|
|
152
|
+
*/
|
|
153
|
+
function shipsSeams(opts) {
|
|
154
|
+
const problems = missing(opts, opts.seams)
|
|
155
|
+
for (const seam of opts.seams.filter((s) => !opts.filledSeams.includes(s) && exists(opts, s))) {
|
|
156
|
+
const code = read(opts, seam).text.split('\n').filter((line) => line.trim() && !line.trim().startsWith('//-'))
|
|
157
|
+
if (code.length > 0) problems.push(`views/${seam} holds markup (${JSON.stringify(code[0].trim())}). A seam ships empty, with //- comments only; list it under { filledSeams } if its default is contract.`)
|
|
158
|
+
}
|
|
159
|
+
for (const seam of opts.withdrawnSeams.filter((s) => exists(opts, s))) {
|
|
160
|
+
problems.push(`views/${seam} exists, but the seam was withdrawn. Remove it.`)
|
|
161
|
+
}
|
|
162
|
+
return problems
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Case: every page type extends the layout and fills `block main`.
|
|
167
|
+
*/
|
|
168
|
+
function shipsPageTypes(opts) {
|
|
169
|
+
const problems = missing(opts, opts.pageTypes)
|
|
170
|
+
for (const type of opts.pageTypes.filter((t) => exists(opts, t))) {
|
|
171
|
+
const source = read(opts, type).text
|
|
172
|
+
const relative = path.posix.relative(path.posix.dirname(type), opts.layout)
|
|
173
|
+
if (!new RegExp(`^extends (${escapeRegExp(relative)}|/${escapeRegExp(opts.layout)})$`, 'm').test(source)) {
|
|
174
|
+
problems.push(`views/${type} does not extend the layout. Start it with: extends ${relative}`)
|
|
175
|
+
}
|
|
176
|
+
if (!/^block main$/m.test(source)) problems.push(`views/${type} does not fill block main. Put the page's markup under: block main`)
|
|
177
|
+
}
|
|
178
|
+
return problems
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Case: the layout defines every block.
|
|
183
|
+
*/
|
|
184
|
+
function definesBlocks(opts) {
|
|
185
|
+
const { text, problems } = read(opts, opts.layout)
|
|
186
|
+
if (problems.length > 0) return problems
|
|
187
|
+
return opts.blocks.filter((block) => !new RegExp(`^\\s*block ${block}$`, 'm').test(text))
|
|
188
|
+
.map((block) => `views/${opts.layout} does not define block ${block}. Add a line: block ${block}`)
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Case: the helpers file defines every helper, and no view declares
|
|
193
|
+
* another top-level name than the helpers and `globals`.
|
|
194
|
+
*/
|
|
195
|
+
function definesHelpers(opts) {
|
|
196
|
+
const { text, problems } = read(opts, opts.helpersFile)
|
|
197
|
+
for (const helper of opts.helpers) {
|
|
198
|
+
if (problems.length === 0 && !new RegExp(`function ${helper}\\(`).test(text)) problems.push(`views/${opts.helpersFile} does not define function ${helper}(…). Define it there.`)
|
|
199
|
+
}
|
|
200
|
+
const allowed = new Set([...opts.helpers, ...opts.globals])
|
|
201
|
+
const declared = [...new Set([...allViews(opts).matchAll(TOP_LEVEL)].map((match) => match[1]))].sort()
|
|
202
|
+
for (const name of declared.filter((n) => !allowed.has(n))) {
|
|
203
|
+
problems.push(`views/ declares the top-level name ${name}, which is neither a helper nor one of { globals } (${[...opts.globals].join(', ') || 'none'}). Scope it inside the theme's global object, or list it.`)
|
|
204
|
+
}
|
|
205
|
+
return problems
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Case: views/vendor/ does not exist; a theme publishes no plugin views.
|
|
210
|
+
*/
|
|
211
|
+
const shipsNoVendor = (opts) => (fs.existsSync(path.join(opts.viewsDir, 'vendor')) ? ['views/vendor/ exists. A theme ships no plugin views; style the plugins\' own markup through its classes instead.'] : [])
|
|
212
|
+
|
|
213
|
+
function readConfig(opts) {
|
|
214
|
+
if (!fs.existsSync(opts.configFile)) return { config: undefined, problems: [`${opts.configFile} does not exist. Pass the theme's config file as { config }, relative to ${opts.root}.`] }
|
|
215
|
+
const config = loadYaml(opts.configFile)
|
|
216
|
+
return isPlainObject(config) ? { config, problems: [] } : { config: undefined, problems: [`${opts.config} is not a mapping. Declare the theme's keys and tokens in it.`] }
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Case: config/theme.yaml declares every key, and per token group exactly
|
|
221
|
+
* the listed names, each a non-empty string or number without `<>{};`.
|
|
222
|
+
*/
|
|
223
|
+
function declaresKeys(opts) {
|
|
224
|
+
const { config, problems } = readConfig(opts)
|
|
225
|
+
if (!config) return problems
|
|
226
|
+
for (const key of opts.keys.filter((k) => !Object.hasOwn(config, k))) problems.push(`${opts.config} has no key ${key}. Declare it with its default.`)
|
|
227
|
+
for (const [group, names] of Object.entries(opts.tokens)) {
|
|
228
|
+
const declared = isPlainObject(config.tokens?.[group]) ? config.tokens[group] : undefined
|
|
229
|
+
if (!declared) {
|
|
230
|
+
problems.push(`${opts.config} has no token group tokens.${group}. Declare ${names.join(', ')} under it.`)
|
|
231
|
+
continue
|
|
232
|
+
}
|
|
233
|
+
for (const name of names.filter((n) => !Object.hasOwn(declared, n))) problems.push(`${opts.config} has no token tokens.${group}.${name}. Declare it with its default.`)
|
|
234
|
+
for (const name of Object.keys(declared).filter((n) => !names.includes(n))) problems.push(`${opts.config} declares tokens.${group}.${name}, which the contract does not list. Remove it, or add it to { tokens }.`)
|
|
235
|
+
for (const name of names.filter((n) => Object.hasOwn(declared, n))) {
|
|
236
|
+
const value = declared[name]
|
|
237
|
+
if (!['string', 'number'].includes(typeof value) || String(value) === '' || /[<>{};]/.test(String(value))) {
|
|
238
|
+
problems.push(`${opts.config}: tokens.${group}.${name} is ${JSON.stringify(value)}. A token's default is a non-empty string or number without < > { } ;.`)
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
return problems
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const valueAt = (config, key) => key.split('.').reduce((value, part) => (isPlainObject(value) && Object.hasOwn(value, part) ? value[part] : undefined), config)
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Case: each `values` key of config/theme.yaml equals its value, or
|
|
249
|
+
* matches its RegExp.
|
|
250
|
+
*/
|
|
251
|
+
function holdsValues(opts) {
|
|
252
|
+
const { config, problems } = readConfig(opts)
|
|
253
|
+
if (!config) return problems
|
|
254
|
+
for (const [key, expected] of Object.entries(opts.values)) {
|
|
255
|
+
const actual = valueAt(config, key)
|
|
256
|
+
const ok = expected instanceof RegExp ? actual !== undefined && expected.test(String(actual)) : isDeepStrictEqual(actual, expected)
|
|
257
|
+
if (!ok) problems.push(`${opts.config}: ${key} is ${JSON.stringify(actual)}, expected ${expected instanceof RegExp ? `a value matching ${expected}` : JSON.stringify(expected)}. Restore the theme's default.`)
|
|
258
|
+
}
|
|
259
|
+
return problems
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Case: every public class is written in views/ (`.name` or quoted), a
|
|
264
|
+
* computed one by every piece of source that builds it.
|
|
265
|
+
*/
|
|
266
|
+
function usesClasses(opts) {
|
|
267
|
+
const source = allViews(opts)
|
|
268
|
+
const problems = []
|
|
269
|
+
for (const name of opts.classes) {
|
|
270
|
+
const evidence = opts.computedClasses[name]
|
|
271
|
+
if (evidence) {
|
|
272
|
+
for (const piece of evidence.filter((p) => !(p instanceof RegExp ? p.test(source) : source.includes(p)))) {
|
|
273
|
+
problems.push(`views/ lacks ${piece instanceof RegExp ? piece : JSON.stringify(piece)}, the source that builds the computed class ${name}. Restore it, or update { computedClasses }.`)
|
|
274
|
+
}
|
|
275
|
+
} else if (!classInSource(name).test(source)) {
|
|
276
|
+
problems.push(`views/ never uses the public class ${name}. Render it (.${name} or '${name}'), or drop it from { classes } with a major release.`)
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
return problems
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Case: no absent class is written in views/ (comment lines aside) or
|
|
284
|
+
* selected in the stylesheet.
|
|
285
|
+
*/
|
|
286
|
+
function usesNoAbsentClass(opts) {
|
|
287
|
+
const code = withoutComments(allViews(opts))
|
|
288
|
+
const { text: css, problems } = readText(opts.css, `Pass the theme's stylesheet as { css } relative to ${opts.root}.`)
|
|
289
|
+
for (const name of opts.absentClasses) {
|
|
290
|
+
if (classInSource(name).test(code)) problems.push(`views/ renders ${name}, a class the theme leaves out. Remove it from the markup.`)
|
|
291
|
+
if (classSelector(name).test(css)) problems.push(`${opts.cssName} styles .${name}, a class the theme leaves out. Remove the rule.`)
|
|
292
|
+
}
|
|
293
|
+
return problems
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Case: no view reads `meta.<name>`, `app.<name>`, `item.meta.<name>` or
|
|
298
|
+
* `page.meta.<name>` for a plugin's data (comment lines aside).
|
|
299
|
+
*/
|
|
300
|
+
function readsNoPluginData(opts) {
|
|
301
|
+
const code = withoutComments(allViews(opts))
|
|
302
|
+
return opts.pluginData.filter((name) => new RegExp(`(meta|app|item\\.meta|page\\.meta)\\.${name}\\b`).test(code))
|
|
303
|
+
.map((name) => `views/ reads ${name}, a plugin's data. A theme renders plugin output through its seams only; read nothing a plugin writes.`)
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* Case: `content` is only output (`!= content`) or tested for being empty,
|
|
308
|
+
* never parsed (comment lines aside).
|
|
309
|
+
*/
|
|
310
|
+
function outputsContentOnly(opts) {
|
|
311
|
+
const lines = withoutComments(allViews(opts)).split('\n').filter((line) => /\bcontent\b/.test(line) && !CONTENT_MENTION.test(line))
|
|
312
|
+
if (lines.length === 0) return ['views/ never outputs content. The layout or a page type must render it with: != content']
|
|
313
|
+
return lines.filter((line) => !CONTENT_USE.test(line.trim()))
|
|
314
|
+
.map((line) => `views/ uses content in ${JSON.stringify(line.trim())}. Only output it (!= content) or test it (if String(content || '').trim()); never parse it.`)
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* Case: every UI string key is passed through `t('<key>')` in views/.
|
|
319
|
+
*/
|
|
320
|
+
function translatesKeys(opts) {
|
|
321
|
+
const source = allViews(opts)
|
|
322
|
+
return opts.tKeys.filter((key) => !source.includes(`t('${key}')`))
|
|
323
|
+
.map((key) => `views/ never calls t('${key}'). Pass the UI string through t() with exactly this key.`)
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* The cases `contractSuite` registers, each a name and a `check()` that
|
|
328
|
+
* returns the problems it found (empty when the case holds).
|
|
329
|
+
*
|
|
330
|
+
* @param {object} options see `contractSuite`
|
|
331
|
+
* @returns {{ name: string, check: () => string[] }[]}
|
|
332
|
+
*/
|
|
333
|
+
export function contractCases(options) {
|
|
334
|
+
const opts = normalize(options)
|
|
335
|
+
const cases = [
|
|
336
|
+
{ name: 'ships every view and partial', check: () => shipsViews(opts) },
|
|
337
|
+
{ name: `ships every seam empty${opts.withdrawnSeams.length > 0 ? ', and no withdrawn seam' : ''}`, check: () => shipsSeams(opts) },
|
|
338
|
+
{ name: 'ships every page type, each extending the layout and filling block main', check: () => shipsPageTypes(opts) },
|
|
339
|
+
{ name: `defines every block in views/${opts.layout}`, check: () => definesBlocks(opts) },
|
|
340
|
+
{ name: `defines the helpers and no other top-level name than ${opts.globals.length > 0 ? opts.globals.join(', ') : 'them'}`, check: () => definesHelpers(opts) },
|
|
341
|
+
{ name: 'ships no views/vendor/', check: () => shipsNoVendor(opts) },
|
|
342
|
+
{ name: `declares every key and token in ${opts.config}`, check: () => declaresKeys(opts) },
|
|
343
|
+
]
|
|
344
|
+
if (Object.keys(opts.values).length > 0) cases.push({ name: `keeps the defaults of ${opts.config}`, check: () => holdsValues(opts) })
|
|
345
|
+
cases.push({ name: 'uses every public class in views/', check: () => usesClasses(opts) })
|
|
346
|
+
if (opts.absentClasses.length > 0) cases.push({ name: `uses no class it leaves out, in views/ or ${opts.cssName}`, check: () => usesNoAbsentClass(opts) })
|
|
347
|
+
if (opts.pluginData.length > 0) cases.push({ name: 'reads no plugin data', check: () => readsNoPluginData(opts) })
|
|
348
|
+
if (opts.contentOutputOnly) cases.push({ name: 'outputs content without parsing it', check: () => outputsContentOnly(opts) })
|
|
349
|
+
cases.push({ name: 'passes every UI string through t()', check: () => translatesKeys(opts) })
|
|
350
|
+
return cases
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Register the "Contract present" cases of a theme (§S7) in a
|
|
355
|
+
* `describe('Contract present')`, one `it` each, read from the theme's
|
|
356
|
+
* sources: `views/`, `config/theme.yaml` (core's YAML parser) and the
|
|
357
|
+
* stylesheet. Every list is the theme's own contract; nothing is a default
|
|
358
|
+
* but the file locations.
|
|
359
|
+
*
|
|
360
|
+
* Cases: ships every view; ships every seam with `//-` comments only
|
|
361
|
+
* (`filledSeams` only exist) and no `withdrawnSeams`; every page type
|
|
362
|
+
* extends the layout and fills `block main`; the layout defines every
|
|
363
|
+
* block; the helpers file defines every helper and views/ declares no
|
|
364
|
+
* other top-level name than the helpers and `globals`; no views/vendor/;
|
|
365
|
+
* the config declares every key and exactly the listed tokens per group
|
|
366
|
+
* (non-empty scalars without `<>{};`); with `values`, the config keeps
|
|
367
|
+
* those defaults; every public class is written in views/ (a computed one
|
|
368
|
+
* by its source); with `absentClasses`, none of them is rendered or
|
|
369
|
+
* styled; with `pluginData`, no view reads that plugin data; with
|
|
370
|
+
* `contentOutputOnly`, `content` is only output or tested; every `tKeys`
|
|
371
|
+
* key goes through `t()`.
|
|
372
|
+
*
|
|
373
|
+
* @param {object} options
|
|
374
|
+
* @param {string} options.root absolute root of the theme repo
|
|
375
|
+
* @param {string[]} options.views views and partials that must exist, relative to views/
|
|
376
|
+
* @param {string[]} options.seams seams that must exist, each with `//-` comments only
|
|
377
|
+
* @param {string[]} [options.filledSeams] seams of `seams` whose default markup is contract (Stack's tag-overview)
|
|
378
|
+
* @param {string[]} [options.withdrawnSeams] seams that must not exist
|
|
379
|
+
* @param {string[]} options.pageTypes page types relative to views/, e.g. `'pages/home.pug'`
|
|
380
|
+
* @param {string[]} options.blocks blocks the layout defines, e.g. `['head', 'header', 'main', 'footer', 'scripts']`
|
|
381
|
+
* @param {string[]} options.helpers functions the helpers file defines
|
|
382
|
+
* @param {string[]} [options.globals] other top-level names views/ may declare, e.g. `['themeStack']`
|
|
383
|
+
* @param {string[]} options.keys top-level keys of the config
|
|
384
|
+
* @param {Record<string, string[]>} options.tokens the token names per group, exactly
|
|
385
|
+
* @param {Record<string, unknown>} [options.values] defaults by dotted key (`'tokens.color'`), each deep-equal to its value or matching its RegExp
|
|
386
|
+
* @param {string[]} options.tKeys UI string keys passed through `t()`
|
|
387
|
+
* @param {string[]} options.classes public classes written in views/
|
|
388
|
+
* @param {Record<string, string | RegExp | (string | RegExp)[]>} [options.computedClasses] classes of `classes` built at render time, by the source in views/ that builds them
|
|
389
|
+
* @param {string[]} [options.absentClasses] classes neither rendered in views/ (comment lines aside) nor styled
|
|
390
|
+
* @param {string[]} [options.pluginData] plugin data names no view reads as `meta.`/`app.`/`item.meta.`/`page.meta.<name>`
|
|
391
|
+
* @param {boolean} [options.contentOutputOnly] whether `content` may only be output or tested, default false
|
|
392
|
+
* @param {string} [options.layout] the layout, default `'layouts/layout.pug'`
|
|
393
|
+
* @param {string} [options.helpersFile] the helpers, default `'partials/helpers.pug'`
|
|
394
|
+
* @param {string} [options.config] the config relative to root, default `'config/theme.yaml'`
|
|
395
|
+
* @param {string} [options.css] the stylesheet relative to root, default `'assets/css/theme.css'`
|
|
396
|
+
*/
|
|
397
|
+
export function contractSuite(options) {
|
|
398
|
+
registerCases('Contract present', contractCases(options))
|
|
399
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// §S7 "No unlisted plugin coupling" of a theme: every class selector in its
|
|
2
|
+
// stylesheet is a public class or a plugin class it lists, a plugin's block
|
|
3
|
+
// is styled only under the theme element that holds it, and the plugin
|
|
4
|
+
// classes that must stay unstyled are never reached. Modelled on the five
|
|
5
|
+
// themes' `test/coupling.test.js`.
|
|
6
|
+
import path from 'node:path'
|
|
7
|
+
import { checkClassList, checkRootOption, classSelector, escapeRegExp, isClassName, isPlainObject, isRelative, readText, registerCases } from './suite.js'
|
|
8
|
+
|
|
9
|
+
const SUITE = 'couplingSuite'
|
|
10
|
+
|
|
11
|
+
// The stylesheet without comments, as the rule preludes (the text before
|
|
12
|
+
// each `{`, at-rules left out) and their single selectors.
|
|
13
|
+
function readSelectors(opts) {
|
|
14
|
+
const { text, problems } = readText(opts.css, `Pass the theme's stylesheet as { css } relative to ${opts.root}.`)
|
|
15
|
+
const css = text.replace(/\/\*[\s\S]*?\*\//g, '')
|
|
16
|
+
const preludes = [...css.matchAll(/([^{}]+)\{/g)].map((m) => m[1].trim()).filter((p) => !p.startsWith('@'))
|
|
17
|
+
return { css, preludes, selectors: preludes.flatMap((p) => p.split(',').map((s) => s.trim())), problems }
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// The plugin classes a theme lists, flat: `plugins` is the `{ range,
|
|
21
|
+
// classes }` map `pluginClassesSuite` takes too, or a plain array.
|
|
22
|
+
const pluginClassNames = (plugins) => (Array.isArray(plugins) ? plugins : Object.values(plugins).flatMap((p) => p.classes))
|
|
23
|
+
|
|
24
|
+
function normalize({ root, classes, plugins = [], minClasses = 1, scopes = {}, unstyled = [], css = 'assets/css/theme.css' } = {}) {
|
|
25
|
+
checkRootOption(SUITE, root)
|
|
26
|
+
checkClassList(`${SUITE}({ classes })`, classes, false)
|
|
27
|
+
if (!Array.isArray(plugins) && !(isPlainObject(plugins) && Object.values(plugins).every((p) => isPlainObject(p) && Array.isArray(p.classes)))) {
|
|
28
|
+
throw new TypeError(`${SUITE}({ plugins }) expects the plugin classes the theme styles, as { '<package>': { range, classes } } (the map pluginClassesSuite takes) or an array of class names, got ${JSON.stringify(plugins)}.`)
|
|
29
|
+
}
|
|
30
|
+
checkClassList(`${SUITE}({ plugins })`, pluginClassNames(plugins))
|
|
31
|
+
if (!Number.isInteger(minClasses) || minClasses < 1) throw new TypeError(`${SUITE}({ minClasses }) expects a positive integer, the fewest classes the stylesheet selects, got ${JSON.stringify(minClasses)}.`)
|
|
32
|
+
if (!isPlainObject(scopes) || !Object.entries(scopes).every(([block, under]) => isClassName(block) && typeof under === 'string' && /^\.[\w-]+$/.test(under))) {
|
|
33
|
+
throw new TypeError(`${SUITE}({ scopes }) expects plugin blocks and the theme class they are styled under, e.g. { nav: '.site-header__nav', 'social-media-links': '.site-footer' }, got ${JSON.stringify(scopes)}.`)
|
|
34
|
+
}
|
|
35
|
+
checkClassList(`${SUITE}({ unstyled })`, unstyled)
|
|
36
|
+
const bare = unstyled.filter((name) => !name.includes('__'))
|
|
37
|
+
if (bare.length > 0) throw new TypeError(`${SUITE}({ unstyled }) expects BEM elements such as 'contact-form__decoy', got ${bare.join(', ')}: the suite guards their block.`)
|
|
38
|
+
if (!isRelative(css)) throw new TypeError(`${SUITE}({ css }) expects the theme's stylesheet relative to root, e.g. 'assets/css/theme.css', got ${JSON.stringify(css)}.`)
|
|
39
|
+
return { root, classes, plugins: pluginClassNames(plugins), minClasses, scopes, unstyled, cssName: css, css: path.join(root, css) }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Case: the stylesheet selects at least `minClasses` classes, each a
|
|
44
|
+
* public class or a listed plugin class.
|
|
45
|
+
*/
|
|
46
|
+
function usesListedClasses(opts) {
|
|
47
|
+
const { preludes, problems } = readSelectors(opts)
|
|
48
|
+
if (problems.length > 0) return problems
|
|
49
|
+
const allowed = new Set([...opts.classes, ...opts.plugins])
|
|
50
|
+
const found = [...new Set(preludes.flatMap((p) => [...p.matchAll(/\.([A-Za-z_][\w-]*)/g)].map((m) => m[1])))].sort()
|
|
51
|
+
if (found.length < opts.minClasses) problems.push(`${opts.cssName} selects ${found.length} classes, fewer than { minClasses: ${opts.minClasses} }. Check that the stylesheet is the theme's, or lower the floor.`)
|
|
52
|
+
for (const name of found.filter((n) => !allowed.has(n))) {
|
|
53
|
+
problems.push(`${opts.cssName} styles .${name}, which is neither a public class nor a listed plugin class. Use a public class, or list the plugin class with its package.`)
|
|
54
|
+
}
|
|
55
|
+
return problems
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Case: every selector holding a class of a scoped plugin block (`.block`,
|
|
60
|
+
* `.block--…`, `.block__…`) starts with its theme class.
|
|
61
|
+
*/
|
|
62
|
+
function scopesPluginBlocks(opts) {
|
|
63
|
+
const { selectors, problems } = readSelectors(opts)
|
|
64
|
+
if (problems.length > 0) return problems
|
|
65
|
+
for (const [block, under] of Object.entries(opts.scopes)) {
|
|
66
|
+
const ofBlock = new RegExp(`\\.${escapeRegExp(block)}(?![\\w-])|\\.${escapeRegExp(block)}(--|__)`)
|
|
67
|
+
for (const selector of selectors.filter((s) => ofBlock.test(s) && !s.startsWith(`${under} `))) {
|
|
68
|
+
problems.push(`${opts.cssName}: "${selector}" styles the plugin block ${block} outside ${under}. Start the selector with "${under} ", where the theme places the plugin's markup.`)
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return problems
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Case: no unstyled class is in the stylesheet, and no rule below its
|
|
76
|
+
* block reaches an element through a classless subject.
|
|
77
|
+
*/
|
|
78
|
+
function leavesUnstyled(opts) {
|
|
79
|
+
const { css, selectors, problems } = readSelectors(opts)
|
|
80
|
+
if (problems.length > 0) return problems
|
|
81
|
+
for (const name of opts.unstyled.filter((n) => css.includes(n))) {
|
|
82
|
+
problems.push(`${opts.cssName} names ${name}, which must stay unstyled (the plugin hides it). Remove the rule.`)
|
|
83
|
+
}
|
|
84
|
+
for (const block of [...new Set(opts.unstyled.map((name) => name.split('__')[0]))]) {
|
|
85
|
+
const below = new RegExp(`${classSelector(block).source}\\s*[\\s>+~]`)
|
|
86
|
+
for (const selector of selectors.filter((s) => below.test(s))) {
|
|
87
|
+
const subject = selector.split(/\s*[\s>+~]\s*/).pop()
|
|
88
|
+
if (!subject.startsWith(`.${block}__`)) {
|
|
89
|
+
problems.push(`${opts.cssName}: "${selector}" reaches below .${block} with the subject "${subject}", which could style ${opts.unstyled.filter((n) => n.startsWith(`${block}__`)).join(' or ')}. Name the .${block}__… class the rule styles.`)
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return problems
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* The cases `couplingSuite` registers, each a name and a `check()` that
|
|
98
|
+
* returns the problems it found (empty when the case holds).
|
|
99
|
+
*
|
|
100
|
+
* @param {object} options see `couplingSuite`
|
|
101
|
+
* @returns {{ name: string, check: () => string[] }[]}
|
|
102
|
+
*/
|
|
103
|
+
export function couplingCases(options) {
|
|
104
|
+
const opts = normalize(options)
|
|
105
|
+
const cases = [{ name: 'uses only public classes and listed plugin classes', check: () => usesListedClasses(opts) }]
|
|
106
|
+
const scoped = Object.entries(opts.scopes)
|
|
107
|
+
if (scoped.length > 0) {
|
|
108
|
+
cases.push({ name: `styles ${scoped.map(([block, under]) => `${block} only under ${under}`).join(' and ')}`, check: () => scopesPluginBlocks(opts) })
|
|
109
|
+
}
|
|
110
|
+
if (opts.unstyled.length > 0) cases.push({ name: `never styles ${opts.unstyled.join(' or ')}`, check: () => leavesUnstyled(opts) })
|
|
111
|
+
return cases
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Register the "No unlisted plugin coupling" cases of a theme (§S7) in a
|
|
116
|
+
* `describe('No unlisted plugin coupling')`, one `it` each, read from the
|
|
117
|
+
* theme's stylesheet (comments and at-rule preludes aside).
|
|
118
|
+
*
|
|
119
|
+
* Cases: the stylesheet selects at least `minClasses` classes, each a
|
|
120
|
+
* public class or a listed plugin class; with `scopes`, every selector of
|
|
121
|
+
* a plugin block starts with its theme class; with `unstyled`, those
|
|
122
|
+
* classes never appear and no rule below their block has a classless
|
|
123
|
+
* subject.
|
|
124
|
+
*
|
|
125
|
+
* @param {object} options
|
|
126
|
+
* @param {string} options.root absolute root of the theme repo
|
|
127
|
+
* @param {string[]} options.classes the theme's public classes
|
|
128
|
+
* @param {Record<string, { classes: string[] }> | string[]} [options.plugins] the plugin classes the theme styles: the `pluginClassesSuite` map, or a list
|
|
129
|
+
* @param {number} [options.minClasses] the fewest classes the stylesheet selects, default 1
|
|
130
|
+
* @param {Record<string, string>} [options.scopes] plugin block → the theme class it is styled under, e.g. `{ nav: '.site-header__nav' }`
|
|
131
|
+
* @param {string[]} [options.unstyled] plugin elements that must stay unstyled, e.g. `['contact-form__decoy']`
|
|
132
|
+
* @param {string} [options.css] the stylesheet relative to root, default `'assets/css/theme.css'`
|
|
133
|
+
*/
|
|
134
|
+
export function couplingSuite(options) {
|
|
135
|
+
registerCases('No unlisted plugin coupling', couplingCases(options))
|
|
136
|
+
}
|