@nera-static/test-utils 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,297 @@
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 { 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
+ const isRelative = (value) => typeof value === 'string' && value !== '' && !path.isAbsolute(value) && !value.split(/[\\/]/).includes('..')
23
+
24
+ /**
25
+ * Check the options once, so every case can trust them, and resolve the
26
+ * paths the cases need.
27
+ *
28
+ * @param {object} options see `publishTemplateSuite`
29
+ * @returns {{ root: string, pluginName: string, templates: string[], assets: { from: string, to: string }[], bin: string, binPath: string }}
30
+ */
31
+ function normalize({ root, pluginName, templates, assets = [], bin = 'bin/publish-template.js' } = {}) {
32
+ if (typeof root !== 'string' || !path.isAbsolute(root) || !fs.existsSync(root)) {
33
+ throw new TypeError(
34
+ `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, '..').`,
35
+ )
36
+ }
37
+ if (typeof pluginName !== 'string' || !/^[a-z0-9][a-z0-9-]*$/.test(pluginName)) {
38
+ throw new TypeError(
39
+ `publishTemplateSuite({ pluginName }) expects the vendor folder name, e.g. 'plugin-search' (templates land in views/vendor/<pluginName>/), got ${JSON.stringify(pluginName)}.`,
40
+ )
41
+ }
42
+ if (!Array.isArray(templates) || templates.length === 0 || !templates.every(isRelative)) {
43
+ throw new TypeError(
44
+ `publishTemplateSuite({ templates }) expects a non-empty array of paths relative to views/, e.g. ['search.pug', 'partials/tag-cloud.pug'], got ${JSON.stringify(templates)}.`,
45
+ )
46
+ }
47
+ if (!Array.isArray(assets) || !assets.every((asset) => isPlainObject(asset) && isRelative(asset.from) && isRelative(asset.to))) {
48
+ throw new TypeError(
49
+ `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)}.`,
50
+ )
51
+ }
52
+ if (!isRelative(bin)) {
53
+ throw new TypeError(`publishTemplateSuite({ bin }) expects a path relative to the repo root, e.g. 'bin/publish-template.js', got ${JSON.stringify(bin)}.`)
54
+ }
55
+ const binPath = path.join(root, bin)
56
+ if (!fs.existsSync(binPath)) {
57
+ throw new Error(`publishTemplateSuite: the bin ${binPath} does not exist. Pass the script \`npm run publish-template\` runs as { bin }, relative to ${root}.`)
58
+ }
59
+ return { root, pluginName, templates, assets, bin, binPath }
60
+ }
61
+
62
+ /**
63
+ * A fresh Nera project, optionally made into something else by `files`.
64
+ *
65
+ * @param {Record<string, string | null>} [files] more files, or `null` to remove one
66
+ * @returns {string} the project root
67
+ */
68
+ const project = (files = {}) => makeSite({ files: { ...PROJECT_FILES, ...files } })
69
+
70
+ /**
71
+ * Run the plugin's bin in `cwd` the way `npm run publish-template` does.
72
+ *
73
+ * @param {{ bin: string, binPath: string }} options the normalized options
74
+ * @param {string} cwd the project to run in
75
+ * @param {string[]} [args] e.g. `['--force']`
76
+ * @returns {{ code: number | null, describe: string }} the exit code, and the command with its output for a problem
77
+ */
78
+ function runBin({ bin, binPath }, cwd, args = []) {
79
+ const result = spawnSync(process.execPath, [binPath, ...args], {
80
+ cwd,
81
+ encoding: 'utf-8',
82
+ env: { ...process.env, NO_COLOR: '1', FORCE_COLOR: '0' },
83
+ })
84
+ const output = `--- stdout\n${result.stdout ?? ''}\n--- stderr\n${result.stderr ?? ''}${result.error ? `\n--- error\n${result.error.message}` : ''}`
85
+ return { code: result.status, describe: `node ${[bin, ...args].join(' ')} in ${cwd} exited ${result.status}.\n${output}` }
86
+ }
87
+
88
+ // Where each published file lands, relative to the project: the views and
89
+ // assets folders are the root ones, or `theme/…` on a themed site.
90
+ const templateTargets = ({ pluginName, templates }, prefix = '') =>
91
+ templates.map((template) => ({ source: `views/${template}`, target: `${prefix}views/vendor/${pluginName}/${template}` }))
92
+ const assetTargets = ({ assets }, prefix = '') =>
93
+ assets.map(({ from, to }) => ({ source: from, target: `${prefix}assets/${to}` }))
94
+
95
+ /**
96
+ * Problems with the published copies: a target that is missing or that does
97
+ * not hold its source byte for byte.
98
+ *
99
+ * @returns {string[]}
100
+ */
101
+ function copyProblems(options, dir, targets, why) {
102
+ const problems = []
103
+ for (const { source, target } of targets) {
104
+ const sourcePath = path.join(options.root, source)
105
+ const targetPath = path.join(dir, target)
106
+ if (!fs.existsSync(sourcePath)) {
107
+ 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.`)
108
+ } else if (!fs.existsSync(targetPath)) {
109
+ problems.push(`${target} was not published ${why}. ${options.bin} must copy ${source} there.`)
110
+ } else if (!fs.readFileSync(targetPath).equals(fs.readFileSync(sourcePath))) {
111
+ problems.push(`${target} does not hold ${source} ${why}. ${options.bin} must copy the file unchanged.`)
112
+ }
113
+ }
114
+ return problems
115
+ }
116
+
117
+ /**
118
+ * A project whose targets already hold a site's edited copies.
119
+ */
120
+ const editedProject = (targets) => project(Object.fromEntries(targets.map(({ target }) => [target, EDITED])))
121
+
122
+ /**
123
+ * Problems with edited copies a run without `--force` must have kept.
124
+ *
125
+ * @param {string} dir the project
126
+ * @param {{ target: string }[]} targets the edited files
127
+ * @param {string} fix what the bin should do instead
128
+ * @returns {string[]}
129
+ */
130
+ const lostEdits = (dir, targets, fix) =>
131
+ targets
132
+ .filter(({ target }) => !fs.existsSync(path.join(dir, target)) || fs.readFileSync(path.join(dir, target), 'utf-8') !== EDITED)
133
+ .map(({ target }) => `${target} was overwritten or removed without --force, so the site's edits are lost. ${fix}`)
134
+
135
+ const exitProblem = (run, expected) =>
136
+ run.code === 0 ? [] : [`${run.describe}\nExpected exit 0 ${expected}; fix what the output names.`]
137
+
138
+ /**
139
+ * Case: in a Nera project the bin publishes every template into
140
+ * `views/vendor/<pluginName>/`, unchanged.
141
+ */
142
+ function publishesEveryTemplate(options) {
143
+ const dir = project()
144
+ const run = runBin(options, dir)
145
+ return [...exitProblem(run, 'in a Nera project'), ...copyProblems(options, dir, templateTargets(options), 'in a Nera project')]
146
+ }
147
+
148
+ /**
149
+ * Case: a vendor folder the site already has is left alone without `--force`.
150
+ */
151
+ function skipsExistingTemplates(options) {
152
+ const targets = templateTargets(options)
153
+ const dir = editedProject(targets)
154
+ const run = runBin(options, dir)
155
+ return [
156
+ ...exitProblem(run, 'when the templates already exist (a skip is no error)'),
157
+ ...lostEdits(dir, targets, 'Publish over an existing copy only when --force is given (publishTemplates({ force: process.argv.includes(\'--force\') })).'),
158
+ ]
159
+ }
160
+
161
+ /**
162
+ * Case: `--force` replaces the site's copies with the shipped templates.
163
+ */
164
+ function overwritesTemplatesWithForce(options) {
165
+ const targets = templateTargets(options)
166
+ const dir = editedProject(targets)
167
+ const run = runBin(options, dir, ['--force'])
168
+ return [...exitProblem(run, 'with --force'), ...copyProblems(options, dir, targets, 'with --force over an edited copy')]
169
+ }
170
+
171
+ /**
172
+ * Case: outside a Nera project (a package.json, no config/app.yaml, no
173
+ * pages/) the bin exits non-zero and writes nothing.
174
+ */
175
+ function refusesOutsideProject(options) {
176
+ const dir = project(NOT_A_PROJECT)
177
+ const before = listFiles(dir)
178
+ const run = runBin(options, dir, ['--force'])
179
+ const problems = []
180
+ if (run.code === 0) {
181
+ 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().`)
182
+ }
183
+ const written = listFiles(dir).filter((file) => !before.includes(file))
184
+ if (written.length > 0) {
185
+ problems.push(`${options.bin} wrote ${written.join(', ')} outside a Nera project. Check the project before copying anything.`)
186
+ }
187
+ return problems
188
+ }
189
+
190
+ /**
191
+ * Case: on a themed site (a local `theme/` folder) templates go to
192
+ * `theme/views/vendor/…` and assets to `theme/assets/…`, where the build
193
+ * looks, and nothing into the root `views/` or `assets/`.
194
+ */
195
+ function publishesIntoTheme(options) {
196
+ const dir = project({ 'theme/views/layout.pug': 'main!= content\n' })
197
+ const before = listFiles(dir)
198
+ const run = runBin(options, dir)
199
+ const why = 'on a themed site (a theme/ folder)'
200
+ const problems = [
201
+ ...exitProblem(run, why),
202
+ ...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`),
203
+ ]
204
+ const stray = listFiles(dir).filter((file) => !before.includes(file) && /^(views|assets)\//.test(file))
205
+ if (stray.length > 0) {
206
+ 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.`)
207
+ }
208
+ return problems
209
+ }
210
+
211
+ /**
212
+ * The three cases of one `assets` entry: copied, an existing copy skipped,
213
+ * overwritten with `--force`.
214
+ */
215
+ function assetCases(options, asset) {
216
+ const [target] = assetTargets({ assets: [asset] })
217
+ return [
218
+ {
219
+ name: `copies ${asset.from} to assets/${asset.to}`,
220
+ check: () => {
221
+ const dir = project()
222
+ const run = runBin(options, dir)
223
+ return [...exitProblem(run, 'in a Nera project'), ...copyProblems(options, dir, [target], 'in a Nera project')]
224
+ },
225
+ },
226
+ {
227
+ name: `skips an existing assets/${asset.to}`,
228
+ check: () => {
229
+ const dir = editedProject([target])
230
+ const run = runBin(options, dir)
231
+ return [
232
+ ...exitProblem(run, `when assets/${asset.to} already exists (a skip is no error)`),
233
+ ...lostEdits(dir, [target], 'Copy it with publishAsset({ force: process.argv.includes(\'--force\') }), which skips an existing file.'),
234
+ ]
235
+ },
236
+ },
237
+ {
238
+ name: `overwrites assets/${asset.to} with --force`,
239
+ check: () => {
240
+ const dir = editedProject([target])
241
+ const run = runBin(options, dir, ['--force'])
242
+ return [...exitProblem(run, 'with --force'), ...copyProblems(options, dir, [target], 'with --force over an edited copy')]
243
+ },
244
+ },
245
+ ]
246
+ }
247
+
248
+ /**
249
+ * The cases `publishTemplateSuite` registers, each a name and a `check()`
250
+ * that runs the plugin's real bin in a fresh temp project and returns the
251
+ * problems it found (empty when the case holds). Every problem names the
252
+ * file, what is wrong with it and what to change.
253
+ *
254
+ * @param {object} options see `publishTemplateSuite`
255
+ * @returns {{ name: string, check: () => string[] }[]}
256
+ */
257
+ export function publishTemplateCases(options) {
258
+ const opts = normalize(options)
259
+ return [
260
+ { name: `publishes every template to views/vendor/${opts.pluginName}`, check: () => publishesEveryTemplate(opts) },
261
+ { name: 'skips existing templates without --force', check: () => skipsExistingTemplates(opts) },
262
+ { name: 'overwrites existing templates with --force', check: () => overwritesTemplatesWithForce(opts) },
263
+ { name: 'refuses to publish outside a Nera project', check: () => refusesOutsideProject(opts) },
264
+ { name: 'publishes into theme/ on a themed site', check: () => publishesIntoTheme(opts) },
265
+ ...opts.assets.flatMap((asset) => assetCases(opts, asset)),
266
+ ]
267
+ }
268
+
269
+ /**
270
+ * Register the publish-template test cases of a plugin: one `it` per case
271
+ * in a `describe('publish-template')`, each running the plugin's real bin
272
+ * (`node <bin>`) in a fresh temp Nera project.
273
+ *
274
+ * Cases: publishes every template; skips existing templates without
275
+ * `--force`; overwrites them with `--force`; refuses outside a Nera project
276
+ * (non-zero exit, nothing written); publishes into `theme/` on a themed
277
+ * site. For each `assets` entry three more: copies it, skips an existing
278
+ * copy, overwrites it with `--force`.
279
+ *
280
+ * @param {object} options
281
+ * @param {string} options.root absolute root of the plugin repo
282
+ * @param {string} options.pluginName the vendor folder, e.g. `'plugin-search'`
283
+ * @param {string[]} options.templates the published templates, relative to `<root>/views/`
284
+ * @param {{ from: string, to: string }[]} [options.assets] files the bin copies into the site's assets folder:
285
+ * `from` relative to `root`, `to` relative to the assets folder
286
+ * @param {string} [options.bin] the publish script relative to `root`, default `'bin/publish-template.js'`
287
+ */
288
+ export function publishTemplateSuite(options) {
289
+ const cases = publishTemplateCases(options)
290
+ describe('publish-template', () => {
291
+ for (const { name, check } of cases) {
292
+ it(name, () => {
293
+ expect(check()).toEqual([])
294
+ })
295
+ }
296
+ })
297
+ }
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
+ }