@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,295 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import { spawnSync } from 'node:child_process'
|
|
4
|
+
import { describe, expect, it } from 'vitest'
|
|
5
|
+
import { isPlainObject } from '@nera-static/plugin-utils/values'
|
|
6
|
+
import { isRelative, listFiles } from './files.js'
|
|
7
|
+
import { makeSite } from './site.js'
|
|
8
|
+
|
|
9
|
+
// What a user's edited copy holds before a run: a publish that keeps it
|
|
10
|
+
// skipped the file, one that replaced it overwrote the edits.
|
|
11
|
+
const EDITED = '// edited by the site\n'
|
|
12
|
+
|
|
13
|
+
// The project shape plugin-utils' `validateNeraProject` accepts: makeSite's
|
|
14
|
+
// package.json (named `demo`, so neither the `dummy` test name nor a `nera…`
|
|
15
|
+
// name lets it through), its config/app.yaml and a pages/ folder.
|
|
16
|
+
const PROJECT_FILES = Object.freeze({ 'pages/index.md': '# Home\n' })
|
|
17
|
+
|
|
18
|
+
// Turns `project()` into a folder with a package.json and nothing else
|
|
19
|
+
// Nera needs.
|
|
20
|
+
const NOT_A_PROJECT = Object.freeze({ 'config/app.yaml': null, views: null, pages: null })
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Check the options once, so every case can trust them, and resolve the
|
|
24
|
+
* paths the cases need.
|
|
25
|
+
*
|
|
26
|
+
* @param {object} options see `publishTemplateSuite`
|
|
27
|
+
* @returns {{ root: string, pluginName: string, templates: string[], assets: { from: string, to: string }[], bin: string, binPath: string }}
|
|
28
|
+
*/
|
|
29
|
+
function normalize({ root, pluginName, templates, assets = [], bin = 'bin/publish-template.js' } = {}) {
|
|
30
|
+
if (typeof root !== 'string' || !path.isAbsolute(root) || !fs.existsSync(root)) {
|
|
31
|
+
throw new TypeError(
|
|
32
|
+
`publishTemplateSuite({ root }) expects the absolute path of the plugin repo, got ${JSON.stringify(root)}. Anchor it on the test file: path.resolve(import.meta.dirname, '..').`,
|
|
33
|
+
)
|
|
34
|
+
}
|
|
35
|
+
if (typeof pluginName !== 'string' || !/^[a-z0-9][a-z0-9-]*$/.test(pluginName)) {
|
|
36
|
+
throw new TypeError(
|
|
37
|
+
`publishTemplateSuite({ pluginName }) expects the vendor folder name, e.g. 'plugin-search' (templates land in views/vendor/<pluginName>/), got ${JSON.stringify(pluginName)}.`,
|
|
38
|
+
)
|
|
39
|
+
}
|
|
40
|
+
if (!Array.isArray(templates) || templates.length === 0 || !templates.every(isRelative)) {
|
|
41
|
+
throw new TypeError(
|
|
42
|
+
`publishTemplateSuite({ templates }) expects a non-empty array of paths relative to views/, e.g. ['search.pug', 'partials/tag-cloud.pug'], got ${JSON.stringify(templates)}.`,
|
|
43
|
+
)
|
|
44
|
+
}
|
|
45
|
+
if (!Array.isArray(assets) || !assets.every((asset) => isPlainObject(asset) && isRelative(asset.from) && isRelative(asset.to))) {
|
|
46
|
+
throw new TypeError(
|
|
47
|
+
`publishTemplateSuite({ assets }) expects an array of { from, to }: from relative to the repo root, to relative to the site's assets folder, e.g. [{ from: 'views/search.js', to: 'js/search.js' }], got ${JSON.stringify(assets)}.`,
|
|
48
|
+
)
|
|
49
|
+
}
|
|
50
|
+
if (!isRelative(bin)) {
|
|
51
|
+
throw new TypeError(`publishTemplateSuite({ bin }) expects a path relative to the repo root, e.g. 'bin/publish-template.js', got ${JSON.stringify(bin)}.`)
|
|
52
|
+
}
|
|
53
|
+
const binPath = path.join(root, bin)
|
|
54
|
+
if (!fs.existsSync(binPath)) {
|
|
55
|
+
throw new Error(`publishTemplateSuite: the bin ${binPath} does not exist. Pass the script \`npm run publish-template\` runs as { bin }, relative to ${root}.`)
|
|
56
|
+
}
|
|
57
|
+
return { root, pluginName, templates, assets, bin, binPath }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* A fresh Nera project, optionally made into something else by `files`.
|
|
62
|
+
*
|
|
63
|
+
* @param {Record<string, string | null>} [files] more files, or `null` to remove one
|
|
64
|
+
* @returns {string} the project root
|
|
65
|
+
*/
|
|
66
|
+
const project = (files = {}) => makeSite({ files: { ...PROJECT_FILES, ...files } })
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Run the plugin's bin in `cwd` the way `npm run publish-template` does.
|
|
70
|
+
*
|
|
71
|
+
* @param {{ bin: string, binPath: string }} options the normalized options
|
|
72
|
+
* @param {string} cwd the project to run in
|
|
73
|
+
* @param {string[]} [args] e.g. `['--force']`
|
|
74
|
+
* @returns {{ code: number | null, describe: string }} the exit code, and the command with its output for a problem
|
|
75
|
+
*/
|
|
76
|
+
function runBin({ bin, binPath }, cwd, args = []) {
|
|
77
|
+
const result = spawnSync(process.execPath, [binPath, ...args], {
|
|
78
|
+
cwd,
|
|
79
|
+
encoding: 'utf-8',
|
|
80
|
+
env: { ...process.env, NO_COLOR: '1', FORCE_COLOR: '0' },
|
|
81
|
+
})
|
|
82
|
+
const output = `--- stdout\n${result.stdout ?? ''}\n--- stderr\n${result.stderr ?? ''}${result.error ? `\n--- error\n${result.error.message}` : ''}`
|
|
83
|
+
return { code: result.status, describe: `node ${[bin, ...args].join(' ')} in ${cwd} exited ${result.status}.\n${output}` }
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Where each published file lands, relative to the project: the views and
|
|
87
|
+
// assets folders are the root ones, or `theme/…` on a themed site.
|
|
88
|
+
const templateTargets = ({ pluginName, templates }, prefix = '') =>
|
|
89
|
+
templates.map((template) => ({ source: `views/${template}`, target: `${prefix}views/vendor/${pluginName}/${template}` }))
|
|
90
|
+
const assetTargets = ({ assets }, prefix = '') =>
|
|
91
|
+
assets.map(({ from, to }) => ({ source: from, target: `${prefix}assets/${to}` }))
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Problems with the published copies: a target that is missing or that does
|
|
95
|
+
* not hold its source byte for byte.
|
|
96
|
+
*
|
|
97
|
+
* @returns {string[]}
|
|
98
|
+
*/
|
|
99
|
+
function copyProblems(options, dir, targets, why) {
|
|
100
|
+
const problems = []
|
|
101
|
+
for (const { source, target } of targets) {
|
|
102
|
+
const sourcePath = path.join(options.root, source)
|
|
103
|
+
const targetPath = path.join(dir, target)
|
|
104
|
+
if (!fs.existsSync(sourcePath)) {
|
|
105
|
+
problems.push(`${sourcePath} does not exist, yet the suite lists it. Ship the file in the package, or remove it from the suite's templates/assets.`)
|
|
106
|
+
} else if (!fs.existsSync(targetPath)) {
|
|
107
|
+
problems.push(`${target} was not published ${why}. ${options.bin} must copy ${source} there.`)
|
|
108
|
+
} else if (!fs.readFileSync(targetPath).equals(fs.readFileSync(sourcePath))) {
|
|
109
|
+
problems.push(`${target} does not hold ${source} ${why}. ${options.bin} must copy the file unchanged.`)
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return problems
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* A project whose targets already hold a site's edited copies.
|
|
117
|
+
*/
|
|
118
|
+
const editedProject = (targets) => project(Object.fromEntries(targets.map(({ target }) => [target, EDITED])))
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Problems with edited copies a run without `--force` must have kept.
|
|
122
|
+
*
|
|
123
|
+
* @param {string} dir the project
|
|
124
|
+
* @param {{ target: string }[]} targets the edited files
|
|
125
|
+
* @param {string} fix what the bin should do instead
|
|
126
|
+
* @returns {string[]}
|
|
127
|
+
*/
|
|
128
|
+
const lostEdits = (dir, targets, fix) =>
|
|
129
|
+
targets
|
|
130
|
+
.filter(({ target }) => !fs.existsSync(path.join(dir, target)) || fs.readFileSync(path.join(dir, target), 'utf-8') !== EDITED)
|
|
131
|
+
.map(({ target }) => `${target} was overwritten or removed without --force, so the site's edits are lost. ${fix}`)
|
|
132
|
+
|
|
133
|
+
const exitProblem = (run, expected) =>
|
|
134
|
+
run.code === 0 ? [] : [`${run.describe}\nExpected exit 0 ${expected}; fix what the output names.`]
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Case: in a Nera project the bin publishes every template into
|
|
138
|
+
* `views/vendor/<pluginName>/`, unchanged.
|
|
139
|
+
*/
|
|
140
|
+
function publishesEveryTemplate(options) {
|
|
141
|
+
const dir = project()
|
|
142
|
+
const run = runBin(options, dir)
|
|
143
|
+
return [...exitProblem(run, 'in a Nera project'), ...copyProblems(options, dir, templateTargets(options), 'in a Nera project')]
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Case: a vendor folder the site already has is left alone without `--force`.
|
|
148
|
+
*/
|
|
149
|
+
function skipsExistingTemplates(options) {
|
|
150
|
+
const targets = templateTargets(options)
|
|
151
|
+
const dir = editedProject(targets)
|
|
152
|
+
const run = runBin(options, dir)
|
|
153
|
+
return [
|
|
154
|
+
...exitProblem(run, 'when the templates already exist (a skip is no error)'),
|
|
155
|
+
...lostEdits(dir, targets, 'Publish over an existing copy only when --force is given (publishTemplates({ force: process.argv.includes(\'--force\') })).'),
|
|
156
|
+
]
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Case: `--force` replaces the site's copies with the shipped templates.
|
|
161
|
+
*/
|
|
162
|
+
function overwritesTemplatesWithForce(options) {
|
|
163
|
+
const targets = templateTargets(options)
|
|
164
|
+
const dir = editedProject(targets)
|
|
165
|
+
const run = runBin(options, dir, ['--force'])
|
|
166
|
+
return [...exitProblem(run, 'with --force'), ...copyProblems(options, dir, targets, 'with --force over an edited copy')]
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Case: outside a Nera project (a package.json, no config/app.yaml, no
|
|
171
|
+
* pages/) the bin exits non-zero and writes nothing.
|
|
172
|
+
*/
|
|
173
|
+
function refusesOutsideProject(options) {
|
|
174
|
+
const dir = project(NOT_A_PROJECT)
|
|
175
|
+
const before = listFiles(dir)
|
|
176
|
+
const run = runBin(options, dir, ['--force'])
|
|
177
|
+
const problems = []
|
|
178
|
+
if (run.code === 0) {
|
|
179
|
+
problems.push(`${run.describe}\nExpected a non-zero exit outside a Nera project (a package.json without config/app.yaml and pages/). Check the project first, as publishTemplates does with validateNeraProject().`)
|
|
180
|
+
}
|
|
181
|
+
const written = listFiles(dir).filter((file) => !before.includes(file))
|
|
182
|
+
if (written.length > 0) {
|
|
183
|
+
problems.push(`${options.bin} wrote ${written.join(', ')} outside a Nera project. Check the project before copying anything.`)
|
|
184
|
+
}
|
|
185
|
+
return problems
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Case: on a themed site (a local `theme/` folder) templates go to
|
|
190
|
+
* `theme/views/vendor/…` and assets to `theme/assets/…`, where the build
|
|
191
|
+
* looks, and nothing into the root `views/` or `assets/`.
|
|
192
|
+
*/
|
|
193
|
+
function publishesIntoTheme(options) {
|
|
194
|
+
const dir = project({ 'theme/views/layout.pug': 'main!= content\n' })
|
|
195
|
+
const before = listFiles(dir)
|
|
196
|
+
const run = runBin(options, dir)
|
|
197
|
+
const why = 'on a themed site (a theme/ folder)'
|
|
198
|
+
const problems = [
|
|
199
|
+
...exitProblem(run, why),
|
|
200
|
+
...copyProblems(options, dir, [...templateTargets(options, 'theme/'), ...assetTargets(options, 'theme/')], `${why}; resolve the folder with plugin-utils >= 1.5.0 (publishTemplates, publishAsset), as the build does`),
|
|
201
|
+
]
|
|
202
|
+
const stray = listFiles(dir).filter((file) => !before.includes(file) && /^(views|assets)\//.test(file))
|
|
203
|
+
if (stray.length > 0) {
|
|
204
|
+
problems.push(`${options.bin} wrote ${stray.join(', ')} into the root folders ${why}, where the build never looks. Publish through plugin-utils >= 1.5.0, which resolves theme/views and theme/assets.`)
|
|
205
|
+
}
|
|
206
|
+
return problems
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* The three cases of one `assets` entry: copied, an existing copy skipped,
|
|
211
|
+
* overwritten with `--force`.
|
|
212
|
+
*/
|
|
213
|
+
function assetCases(options, asset) {
|
|
214
|
+
const [target] = assetTargets({ assets: [asset] })
|
|
215
|
+
return [
|
|
216
|
+
{
|
|
217
|
+
name: `copies ${asset.from} to assets/${asset.to}`,
|
|
218
|
+
check: () => {
|
|
219
|
+
const dir = project()
|
|
220
|
+
const run = runBin(options, dir)
|
|
221
|
+
return [...exitProblem(run, 'in a Nera project'), ...copyProblems(options, dir, [target], 'in a Nera project')]
|
|
222
|
+
},
|
|
223
|
+
},
|
|
224
|
+
{
|
|
225
|
+
name: `skips an existing assets/${asset.to}`,
|
|
226
|
+
check: () => {
|
|
227
|
+
const dir = editedProject([target])
|
|
228
|
+
const run = runBin(options, dir)
|
|
229
|
+
return [
|
|
230
|
+
...exitProblem(run, `when assets/${asset.to} already exists (a skip is no error)`),
|
|
231
|
+
...lostEdits(dir, [target], 'Copy it with publishAsset({ force: process.argv.includes(\'--force\') }), which skips an existing file.'),
|
|
232
|
+
]
|
|
233
|
+
},
|
|
234
|
+
},
|
|
235
|
+
{
|
|
236
|
+
name: `overwrites assets/${asset.to} with --force`,
|
|
237
|
+
check: () => {
|
|
238
|
+
const dir = editedProject([target])
|
|
239
|
+
const run = runBin(options, dir, ['--force'])
|
|
240
|
+
return [...exitProblem(run, 'with --force'), ...copyProblems(options, dir, [target], 'with --force over an edited copy')]
|
|
241
|
+
},
|
|
242
|
+
},
|
|
243
|
+
]
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* The cases `publishTemplateSuite` registers, each a name and a `check()`
|
|
248
|
+
* that runs the plugin's real bin in a fresh temp project and returns the
|
|
249
|
+
* problems it found (empty when the case holds). Every problem names the
|
|
250
|
+
* file, what is wrong with it and what to change.
|
|
251
|
+
*
|
|
252
|
+
* @param {object} options see `publishTemplateSuite`
|
|
253
|
+
* @returns {{ name: string, check: () => string[] }[]}
|
|
254
|
+
*/
|
|
255
|
+
export function publishTemplateCases(options) {
|
|
256
|
+
const opts = normalize(options)
|
|
257
|
+
return [
|
|
258
|
+
{ name: `publishes every template to views/vendor/${opts.pluginName}`, check: () => publishesEveryTemplate(opts) },
|
|
259
|
+
{ name: 'skips existing templates without --force', check: () => skipsExistingTemplates(opts) },
|
|
260
|
+
{ name: 'overwrites existing templates with --force', check: () => overwritesTemplatesWithForce(opts) },
|
|
261
|
+
{ name: 'refuses to publish outside a Nera project', check: () => refusesOutsideProject(opts) },
|
|
262
|
+
{ name: 'publishes into theme/ on a themed site', check: () => publishesIntoTheme(opts) },
|
|
263
|
+
...opts.assets.flatMap((asset) => assetCases(opts, asset)),
|
|
264
|
+
]
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Register the publish-template test cases of a plugin: one `it` per case
|
|
269
|
+
* in a `describe('publish-template')`, each running the plugin's real bin
|
|
270
|
+
* (`node <bin>`) in a fresh temp Nera project.
|
|
271
|
+
*
|
|
272
|
+
* Cases: publishes every template; skips existing templates without
|
|
273
|
+
* `--force`; overwrites them with `--force`; refuses outside a Nera project
|
|
274
|
+
* (non-zero exit, nothing written); publishes into `theme/` on a themed
|
|
275
|
+
* site. For each `assets` entry three more: copies it, skips an existing
|
|
276
|
+
* copy, overwrites it with `--force`.
|
|
277
|
+
*
|
|
278
|
+
* @param {object} options
|
|
279
|
+
* @param {string} options.root absolute root of the plugin repo
|
|
280
|
+
* @param {string} options.pluginName the vendor folder, e.g. `'plugin-search'`
|
|
281
|
+
* @param {string[]} options.templates the published templates, relative to `<root>/views/`
|
|
282
|
+
* @param {{ from: string, to: string }[]} [options.assets] files the bin copies into the site's assets folder:
|
|
283
|
+
* `from` relative to `root`, `to` relative to the assets folder
|
|
284
|
+
* @param {string} [options.bin] the publish script relative to `root`, default `'bin/publish-template.js'`
|
|
285
|
+
*/
|
|
286
|
+
export function publishTemplateSuite(options) {
|
|
287
|
+
const cases = publishTemplateCases(options)
|
|
288
|
+
describe('publish-template', () => {
|
|
289
|
+
for (const { name, check } of cases) {
|
|
290
|
+
it(name, () => {
|
|
291
|
+
expect(check()).toEqual([])
|
|
292
|
+
})
|
|
293
|
+
}
|
|
294
|
+
})
|
|
295
|
+
}
|
package/src/site.js
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import { pathToFileURL } from 'node:url'
|
|
4
|
+
import { vi } from 'vitest'
|
|
5
|
+
import { isPlainObject } from '@nera-static/plugin-utils/values'
|
|
6
|
+
import { resolveCore } from './core.js'
|
|
7
|
+
import { listFiles, tempDir, writeFiles } from './files.js'
|
|
8
|
+
|
|
9
|
+
// The files every `makeSite` site starts with, as the plugins' integration
|
|
10
|
+
// tests wrote them: an ESM package, a site with an origin (sitemap, feed and
|
|
11
|
+
// structured-data need one) and a layout that renders the page body.
|
|
12
|
+
const DEFAULT_FILES = Object.freeze({
|
|
13
|
+
'package.json': JSON.stringify({ name: 'demo', private: true, type: 'module' }),
|
|
14
|
+
'config/app.yaml': 'name: Demo\nlang: en\norigin: https://example.com/\n',
|
|
15
|
+
'views/layout.pug': 'doctype html\nhtml\n body\n main!= content',
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The `folders` core's `run()` takes for the site at `root`, as `nera build`
|
|
20
|
+
* passes them: `config`, `pages`, `views`, `assets`, `plugins` and `dist`
|
|
21
|
+
* (`public/`).
|
|
22
|
+
*
|
|
23
|
+
* @param {string} root the site root
|
|
24
|
+
* @returns {{ config: string, pages: string, views: string, assets: string, dist: string, plugins: string }}
|
|
25
|
+
*/
|
|
26
|
+
export function folders(root) {
|
|
27
|
+
return {
|
|
28
|
+
config: path.join(root, 'config'),
|
|
29
|
+
pages: path.join(root, 'pages'),
|
|
30
|
+
views: path.join(root, 'views'),
|
|
31
|
+
assets: path.join(root, 'assets'),
|
|
32
|
+
dist: path.join(root, 'public'),
|
|
33
|
+
plugins: path.join(root, 'plugins'),
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* A throwaway Nera site under `os.tmpdir()`, removed after the test file.
|
|
39
|
+
*
|
|
40
|
+
* It starts with a `package.json`, a `config/app.yaml` (`name: Demo`,
|
|
41
|
+
* `lang: en`, `origin: https://example.com/`) and a `views/layout.pug` that
|
|
42
|
+
* renders `content` into `main`; `files` adds to them or overrides them, and
|
|
43
|
+
* a `null` value removes a default. Each entry of `plugins` becomes the local
|
|
44
|
+
* plugin `plugins/<name>/index.js`, which re-exports the given entry file, so
|
|
45
|
+
* core loads the plugin under test the way a site loads its own plugins.
|
|
46
|
+
*
|
|
47
|
+
* @param {{ files?: Record<string, string | Uint8Array | null>, plugins?: Record<string, string> }} [options]
|
|
48
|
+
* `files`: relative path -> content; `plugins`: plugin name -> absolute path of its entry file
|
|
49
|
+
* @returns {string} the site root
|
|
50
|
+
*/
|
|
51
|
+
export function makeSite({ files = {}, plugins = {} } = {}) {
|
|
52
|
+
if (!isPlainObject(files)) {
|
|
53
|
+
throw new TypeError(
|
|
54
|
+
'makeSite({ files }) expects files as an object of { \'relative/path\': content | null }, e.g. { \'pages/index.md\': \'---\\nlayout: layout.pug\\n---\\n\' }.',
|
|
55
|
+
)
|
|
56
|
+
}
|
|
57
|
+
if (!isPlainObject(plugins)) {
|
|
58
|
+
throw new TypeError(
|
|
59
|
+
'makeSite({ plugins }) expects an object of { name: entryFile }, e.g. { sitemap: path.resolve(import.meta.dirname, \'../index.js\') }.',
|
|
60
|
+
)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const reexports = {}
|
|
64
|
+
for (const [name, entry] of Object.entries(plugins)) {
|
|
65
|
+
if (name === '' || /[\\/]/.test(name)) {
|
|
66
|
+
throw new TypeError(
|
|
67
|
+
`makeSite: the plugin name ${JSON.stringify(name)} is not a folder name. Use a plain name such as 'sitemap'; it becomes plugins/<name>/index.js.`,
|
|
68
|
+
)
|
|
69
|
+
}
|
|
70
|
+
if (typeof entry !== 'string' || !path.isAbsolute(entry)) {
|
|
71
|
+
throw new TypeError(
|
|
72
|
+
`makeSite: the entry file of plugin "${name}" must be an absolute path, got ${JSON.stringify(entry)}. Anchor it on the test file: path.resolve(import.meta.dirname, '../index.js').`,
|
|
73
|
+
)
|
|
74
|
+
}
|
|
75
|
+
if (!fs.existsSync(entry)) {
|
|
76
|
+
throw new Error(`makeSite: the entry file of plugin "${name}" does not exist: ${entry}`)
|
|
77
|
+
}
|
|
78
|
+
reexports[`plugins/${name}/index.js`] = `export * from '${pathToFileURL(entry).href}'\n`
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
return writeFiles(tempDir('nera-site-'), { ...DEFAULT_FILES, ...reexports, ...files })
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Collect what `console[method]` writes during a build, each call's
|
|
85
|
+
// arguments joined with a space (as `captureConsole` and the copies do).
|
|
86
|
+
// A plain swap rather than `vi.spyOn`: a build usually runs in `beforeAll`,
|
|
87
|
+
// where the preset's `restoreMocks` does not reach, and a spy on a method the
|
|
88
|
+
// test already spies on would hand back that spy and restore it too early.
|
|
89
|
+
function collect(method) {
|
|
90
|
+
const original = console[method]
|
|
91
|
+
const lines = []
|
|
92
|
+
console[method] = (...args) => {
|
|
93
|
+
lines.push(args.join(' '))
|
|
94
|
+
}
|
|
95
|
+
return { lines, restore: () => (console[method] = original) }
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Build the site at `root` with core's real `run()`, from inside `root` the
|
|
100
|
+
* way `nera build` runs it: plugins read their config relative to
|
|
101
|
+
* `process.cwd()`. `console.log` and `console.warn` are silenced and
|
|
102
|
+
* collected, each call's arguments joined with a space; `console.error`
|
|
103
|
+
* passes through. The cwd and the console are restored even when the build
|
|
104
|
+
* throws.
|
|
105
|
+
*
|
|
106
|
+
* Needs vitest's default `forks` pool: a worker thread (`pool: 'threads'`)
|
|
107
|
+
* cannot change the cwd.
|
|
108
|
+
*
|
|
109
|
+
* @param {string} root the site root (from `makeSite`)
|
|
110
|
+
* @returns {Promise<{ warnings: string[], logs: string[] }>}
|
|
111
|
+
*/
|
|
112
|
+
export async function buildSite(root) {
|
|
113
|
+
if (typeof root !== 'string' || !path.isAbsolute(root) || !fs.existsSync(root)) {
|
|
114
|
+
throw new TypeError(`buildSite(root) expects the absolute path of an existing site, got ${JSON.stringify(root)}. Pass the dir makeSite() returned.`)
|
|
115
|
+
}
|
|
116
|
+
const { default: run } = await import(pathToFileURL(resolveCore('buildSite builds with')).href)
|
|
117
|
+
|
|
118
|
+
const prev = process.cwd()
|
|
119
|
+
try {
|
|
120
|
+
process.chdir(root)
|
|
121
|
+
} catch (err) {
|
|
122
|
+
if (err.code !== 'ERR_WORKER_UNSUPPORTED_OPERATION') throw err
|
|
123
|
+
throw new Error(
|
|
124
|
+
'buildSite needs to run the build from inside the site, and a worker thread cannot change the cwd. Use vitest\'s default pool: remove pool: \'threads\' from vitest.config.js.',
|
|
125
|
+
{ cause: err },
|
|
126
|
+
)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const log = collect('log')
|
|
130
|
+
const warn = collect('warn')
|
|
131
|
+
try {
|
|
132
|
+
await run({ folders: folders(root) })
|
|
133
|
+
return { warnings: warn.lines, logs: log.lines }
|
|
134
|
+
} finally {
|
|
135
|
+
warn.restore()
|
|
136
|
+
log.restore()
|
|
137
|
+
process.chdir(prev)
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Point `process.cwd()` at a fresh temp dir holding `files`, for unit tests
|
|
143
|
+
* of a hook that reads `config/<name>.yaml` relative to the cwd. Only
|
|
144
|
+
* `process.cwd()` changes (a `vi.spyOn`, put back by the preset's
|
|
145
|
+
* `restoreMocks` after the test), never the real cwd, so call it inside the
|
|
146
|
+
* test or a `beforeEach`; from a `beforeAll` it would hold for the first
|
|
147
|
+
* test only. Unlike `makeSite` there are no default files.
|
|
148
|
+
*
|
|
149
|
+
* @param {Record<string, string | Uint8Array | null>} [files] relative path -> content
|
|
150
|
+
* @returns {string} the dir `process.cwd()` now returns
|
|
151
|
+
*/
|
|
152
|
+
export function useSiteCwd(files = {}) {
|
|
153
|
+
const root = writeFiles(tempDir('nera-cwd-'), files)
|
|
154
|
+
vi.spyOn(process, 'cwd').mockReturnValue(root)
|
|
155
|
+
return root
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Read a built file from the site's `public/` dir.
|
|
160
|
+
*
|
|
161
|
+
* @param {string} root the site root
|
|
162
|
+
* @param {string} rel path below `public/`, e.g. `'de/index.html'`
|
|
163
|
+
* @returns {string} the file's text
|
|
164
|
+
*/
|
|
165
|
+
export function readPublic(root, rel) {
|
|
166
|
+
const dist = path.join(root, 'public')
|
|
167
|
+
try {
|
|
168
|
+
return fs.readFileSync(path.join(dist, rel), 'utf-8')
|
|
169
|
+
} catch (err) {
|
|
170
|
+
if (err.code !== 'ENOENT') throw err
|
|
171
|
+
const built = fs.existsSync(dist) ? listFiles(dist) : []
|
|
172
|
+
throw new Error(
|
|
173
|
+
built.length
|
|
174
|
+
? `readPublic: the build did not write public/${rel}. It wrote: ${built.join(', ')}.`
|
|
175
|
+
: `readPublic: ${dist} is empty or missing. Build the site first: await buildSite(root).`,
|
|
176
|
+
{ cause: err },
|
|
177
|
+
)
|
|
178
|
+
}
|
|
179
|
+
}
|