verso-cms 0.0.0-stage → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +168 -2
  3. package/bin/verso.js +16 -0
  4. package/editor/door.js +139 -0
  5. package/editor/editor.js +1880 -0
  6. package/editor/elevate.css +2158 -0
  7. package/editor/ext-attrs.js +87 -0
  8. package/editor/ext-blocks.js +422 -0
  9. package/editor/ext-builder.js +819 -0
  10. package/editor/ext-channels.js +574 -0
  11. package/editor/ext-components.js +160 -0
  12. package/editor/ext-history.js +242 -0
  13. package/editor/ext-palette.js +307 -0
  14. package/editor/ext-people.js +345 -0
  15. package/editor/ext-repeaters.js +143 -0
  16. package/editor/ext-screens.js +94 -0
  17. package/editor/ext-site-settings.js +318 -0
  18. package/editor/ext-site-view.js +632 -0
  19. package/editor/ext-tokens.js +1195 -0
  20. package/editor/new-page.js +252 -0
  21. package/editor/rich.js +23 -0
  22. package/package.json +69 -4
  23. package/src/blocks.js +269 -0
  24. package/src/box.js +339 -0
  25. package/src/build.js +210 -0
  26. package/src/cli.js +161 -0
  27. package/src/color.js +137 -0
  28. package/src/components.js +223 -0
  29. package/src/elevate.js +74 -0
  30. package/src/errors.js +46 -0
  31. package/src/extensions/README.md +70 -0
  32. package/src/extensions/blocks.js +294 -0
  33. package/src/extensions/builder.js +734 -0
  34. package/src/extensions/channels.js +341 -0
  35. package/src/extensions/components.js +141 -0
  36. package/src/extensions/history.js +169 -0
  37. package/src/extensions/palette.js +31 -0
  38. package/src/extensions/people.js +113 -0
  39. package/src/extensions/site-settings.js +251 -0
  40. package/src/extensions/site-view.js +381 -0
  41. package/src/extensions/tags.js +15 -0
  42. package/src/extensions/tokens.js +587 -0
  43. package/src/fonts.js +139 -0
  44. package/src/git.js +419 -0
  45. package/src/html-edit.js +942 -0
  46. package/src/images.js +116 -0
  47. package/src/people.js +286 -0
  48. package/src/rich.js +124 -0
  49. package/src/scaffold.js +185 -0
  50. package/src/screens.js +65 -0
  51. package/src/server.js +693 -0
  52. package/src/site.js +618 -0
  53. package/src/template.js +915 -0
  54. package/src/video.js +29 -0
  55. package/starter/Dockerfile +20 -0
  56. package/starter/README.md +49 -0
  57. package/starter/blocks/call-to-action.html +6 -0
  58. package/starter/blocks/features.html +15 -0
  59. package/starter/blocks/hero.html +8 -0
  60. package/starter/blocks/image-and-text.html +8 -0
  61. package/starter/blocks/latest-posts.html +20 -0
  62. package/starter/blocks/post-index.html +30 -0
  63. package/starter/blocks/quote.html +9 -0
  64. package/starter/blocks/site-footer.html +8 -0
  65. package/starter/blocks/site-nav.html +8 -0
  66. package/starter/blocks/tag-list.html +10 -0
  67. package/starter/blocks/tagged-posts.html +19 -0
  68. package/starter/blocks/team.html +15 -0
  69. package/starter/blocks/text.html +4 -0
  70. package/starter/content/404/page.json +21 -0
  71. package/starter/content/about/page.json +65 -0
  72. package/starter/content/journal/designing-for-the-morning-shift/body.html +22 -0
  73. package/starter/content/journal/designing-for-the-morning-shift/checklist.jpg +0 -0
  74. package/starter/content/journal/designing-for-the-morning-shift/cover.jpg +0 -0
  75. package/starter/content/journal/designing-for-the-morning-shift/page.json +17 -0
  76. package/starter/content/journal/page.json +19 -0
  77. package/starter/content/journal/the-first-week/body.html +17 -0
  78. package/starter/content/journal/the-first-week/cover.jpg +0 -0
  79. package/starter/content/journal/the-first-week/page.json +17 -0
  80. package/starter/content/journal/the-first-week/wall-of-cards.jpg +0 -0
  81. package/starter/content/page.json +94 -0
  82. package/starter/content/site.json +88 -0
  83. package/starter/content/studio-table.jpg +0 -0
  84. package/starter/content/topics/page.json +27 -0
  85. package/starter/dockerignore +5 -0
  86. package/starter/elevate/config/design.ts +30 -0
  87. package/starter/elevate/config/elevate.ts +16 -0
  88. package/starter/elevate/config/syntax.ts +6 -0
  89. package/starter/elevate/design/site.ts +9 -0
  90. package/starter/elevate/design/tokens.json +20 -0
  91. package/starter/elevate/extend/fonts.css +1 -0
  92. package/starter/gitignore +6 -0
  93. package/starter/netlify.toml +5 -0
  94. package/starter/parts/.gitkeep +0 -0
  95. package/starter/public/favicon.svg +1 -0
  96. package/starter/templates/page.html +20 -0
  97. package/starter/templates/page.layout.json +23 -0
  98. package/starter/templates/post.html +65 -0
  99. package/starter/verso.defaults.json +33 -0
  100. package/starter-blank/blocks/site-footer.html +3 -0
  101. package/starter-blank/blocks/site-nav.html +8 -0
  102. package/starter-blank/blocks/text.html +4 -0
  103. package/starter-blank/content/404/page.json +18 -0
  104. package/starter-blank/content/page.json +18 -0
  105. package/starter-blank/content/site.json +36 -0
  106. package/starter-blank/elevate/design/tokens.json +10 -0
  107. package/starter-blank/templates/page.html +17 -0
  108. package/starter-blank/verso.defaults.json +26 -0
package/src/site.js ADDED
@@ -0,0 +1,618 @@
1
+ // A Verso site is a folder:
2
+ //
3
+ // verso.json the site's name
4
+ // templates/*.html page templates
5
+ // content/…/page.json one folder per page; the folder path is the URL
6
+ // public/ files copied as they are (images, icons)
7
+ // elevate/ Elevate, which compiles the CSS
8
+ //
9
+ // This file reads all of that and checks it, so the editor and the build see
10
+ // the same site and report the same problems.
11
+
12
+ import fs from 'fs';
13
+ import path from 'path';
14
+ import { VersoError, VersoErrors, lineAt } from './errors.js';
15
+ import { parseTemplate, parseBlock, humanize, setSiteData, slugifyTag, uniqueTags } from './template.js';
16
+ import { checkBlocks, cloneWithNewIds } from './blocks.js';
17
+ import { listComponents } from './components.js';
18
+ import { checkRichClasses, richIsEmpty, IMAGE_FILE } from './rich.js';
19
+
20
+ export const PAGE_FILE = 'page.json';
21
+
22
+ export function findRoot(start = process.cwd()) {
23
+ let dir = path.resolve(start);
24
+ for (;;) {
25
+ if (fs.existsSync(path.join(dir, 'verso.json'))) return dir;
26
+ const up = path.dirname(dir);
27
+ if (up === dir) return null;
28
+ dir = up;
29
+ }
30
+ }
31
+
32
+ const rel = (root, p) => path.relative(root, p).split(path.sep).join('/');
33
+
34
+ function readJSON(root, file) {
35
+ const text = fs.readFileSync(file, 'utf8');
36
+ try {
37
+ return JSON.parse(text);
38
+ } catch (err) {
39
+ const at = /position (\d+)/.exec(err.message);
40
+ const line = at ? lineAt(text, Number(at[1])) : null;
41
+ throw new VersoError("This file isn't valid JSON, so Verso can't read it.", {
42
+ file: rel(root, file),
43
+ line,
44
+ hint: 'Look for a missing comma or quote near that line.',
45
+ });
46
+ }
47
+ }
48
+
49
+ export function readConfig(root) {
50
+ const config = readJSON(root, path.join(root, 'verso.json'));
51
+ const problems = checkRichClasses(config.rich).map((m) => new VersoError(m, { file: 'verso.json' }));
52
+ if (problems.length) throw problems[0];
53
+ return {
54
+ name: typeof config.name === 'string' ? config.name : 'My site',
55
+ locale: typeof config.locale === 'string' ? config.locale : 'en-US',
56
+ rich: config.rich && typeof config.rich === 'object' ? config.rich : {},
57
+ // The site's address, for sitemap.xml: "https://example.com".
58
+ url: typeof config.url === 'string' ? config.url.replace(/\/+$/, '') : '',
59
+ // Write dist/pages.json, a list of every page with its text, for search.
60
+ index: config.index === true,
61
+ // Where the site lives on its host, when it isn't the root: "/blog".
62
+ base: typeof config.base === 'string' && config.base.replace(/^\/+|\/+$/g, '') ? `/${config.base.replace(/^\/+|\/+$/g, '')}` : '',
63
+ // Folders of posts, for the Channels panel and RSS feeds.
64
+ channels: config.channels && typeof config.channels === 'object' && !Array.isArray(config.channels) ? config.channels : {},
65
+ };
66
+ }
67
+
68
+ // Today on this computer's calendar, not UTC's.
69
+ export const today = () => {
70
+ const d = new Date();
71
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
72
+ };
73
+
74
+ // "Spring menu, 2027!" → "spring-menu-2027"
75
+ export const slugify = (name) =>
76
+ String(name).normalize('NFKD').replace(/[\u0300-\u036f]/g, '').toLowerCase()
77
+ .replace(/&/g, ' and ').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 80);
78
+
79
+ // "/about/team/" ↔ content/about/team/page.json
80
+ export const urlForDir = (root, dir) => {
81
+ const parts = rel(path.join(root, 'content'), dir).split('/').filter(Boolean);
82
+ return parts.length ? `/${parts.join('/')}/` : '/';
83
+ };
84
+
85
+ export const dirForUrl = (root, url) => {
86
+ const clean = decodeURIComponent(url.split(/[?#]/)[0]).replace(/\/+$/, '');
87
+ const parts = clean.split('/').filter(Boolean);
88
+ if (parts.some((p) => p === '..' || p === '.' || p.startsWith('.'))) return null;
89
+ return path.join(root, 'content', ...parts);
90
+ };
91
+
92
+ export function listPageDirs(root) {
93
+ const base = path.join(root, 'content');
94
+ if (!fs.existsSync(base)) return [];
95
+ const found = [];
96
+ const walk = (dir) => {
97
+ if (fs.existsSync(path.join(dir, PAGE_FILE))) found.push(dir);
98
+ fs.readdirSync(dir, { withFileTypes: true })
99
+ .filter((e) => e.isDirectory() && !e.name.startsWith('.'))
100
+ .sort((a, b) => a.name.localeCompare(b.name))
101
+ .forEach((e) => walk(path.join(dir, e.name)));
102
+ };
103
+ walk(base);
104
+ return found;
105
+ }
106
+
107
+ // A page is its page.json plus one .html file per rich text field.
108
+ export function readPage(root, dir) {
109
+ const file = path.join(dir, PAGE_FILE);
110
+ const data = readJSON(root, file);
111
+ const url = urlForDir(root, dir);
112
+ const fields = data.fields && typeof data.fields === 'object' && !Array.isArray(data.fields) ? data.fields : {};
113
+ const rich = {};
114
+ fs.readdirSync(dir).filter((f) => f.endsWith('.html')).forEach((f) => {
115
+ rich[f.slice(0, -5)] = fs.readFileSync(path.join(dir, f), 'utf8').trim();
116
+ });
117
+ return {
118
+ url,
119
+ dir,
120
+ file: rel(root, file),
121
+ template: typeof data.template === 'string' ? data.template : '',
122
+ title: typeof data.title === 'string' ? data.title : '',
123
+ description: typeof data.description === 'string' ? data.description : '',
124
+ date: typeof data.date === 'string' ? data.date : '',
125
+ draft: data.draft === true,
126
+ order: Number.isFinite(data.order) ? data.order : null,
127
+ // Tags: words that group pages. "tags-of" makes this page the home of
128
+ // a folder's tags, with a page for each tag beneath it.
129
+ tags: Array.isArray(data.tags) ? uniqueTags(data.tags.filter((t) => typeof t === 'string')) : [],
130
+ tagsOf: typeof data['tags-of'] === 'string' ? data['tags-of'].replace(/^\/+|\/+$/g, '') : '',
131
+ blocks: data.blocks && typeof data.blocks === 'object' && !Array.isArray(data.blocks) ? data.blocks : {},
132
+ fields,
133
+ rich,
134
+ // What people call the page: its title without a " — Site name" tail,
135
+ // or its folder name when it has no title.
136
+ label: url === '/' ? 'Home' : (typeof data.title === 'string' && data.title.trim() ? data.title.split(/\s+[—–|]\s+/)[0].trim() : humanize(url.split('/').filter(Boolean).pop())),
137
+ };
138
+ }
139
+
140
+ // Files in a page's folder that rich text or image fields can use.
141
+ export const pageImages = (dir) => (fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => IMAGE_FILE.test(f)) : []);
142
+
143
+ // Writes the page in a fixed key order with a trailing newline, so git diffs
144
+ // stay small and readable. Written to a temporary file first, then renamed,
145
+ // so a crash can't leave half a file.
146
+ const writeAtomic = (file, text) => {
147
+ const tmp = `${file}.${process.pid}.tmp`;
148
+ fs.writeFileSync(tmp, text, 'utf8');
149
+ fs.renameSync(tmp, file);
150
+ };
151
+
152
+ export function writePage(root, page) {
153
+ const file = path.join(page.dir, PAGE_FILE);
154
+ const data = { template: page.template, title: page.title || '', description: page.description || '' };
155
+ if (page.date) data.date = page.date;
156
+ if (page.draft) data.draft = true;
157
+ if (Number.isFinite(page.order)) data.order = page.order;
158
+ if (page.tags && page.tags.length) data.tags = page.tags;
159
+ if (page.tagsOf) data['tags-of'] = page.tagsOf;
160
+ data.fields = page.fields || {};
161
+ if (page.blocks && Object.keys(page.blocks).length) data.blocks = page.blocks;
162
+ const text = JSON.stringify(data, null, 2) + '\n';
163
+ fs.mkdirSync(page.dir, { recursive: true });
164
+ writeAtomic(file, text);
165
+ const written = { [rel(root, file)]: text };
166
+ // Rich text: one file per field. A field emptied or removed loses its file.
167
+ const existing = fs.readdirSync(page.dir).filter((f) => f.endsWith('.html')).map((f) => f.slice(0, -5));
168
+ existing.forEach((name) => {
169
+ if (!(name in (page.rich || {}))) fs.rmSync(path.join(page.dir, `${name}.html`), { force: true });
170
+ });
171
+ Object.entries(page.rich || {}).forEach(([name, html]) => {
172
+ const target = path.join(page.dir, `${name}.html`);
173
+ const body = `${String(html).trim()}\n`;
174
+ if (!fs.existsSync(target) || fs.readFileSync(target, 'utf8') !== body) {
175
+ writeAtomic(target, body);
176
+ written[rel(root, target)] = body;
177
+ }
178
+ });
179
+ return written;
180
+ }
181
+
182
+ export function createPage(root, { parent = '/', name, template }) {
183
+ const slug = slugify(name);
184
+ if (!slug) throw new VersoError('Give the page a name with at least one letter or number.');
185
+ const parentDir = dirForUrl(root, parent);
186
+ if (!parentDir || !fs.existsSync(path.join(parentDir, PAGE_FILE))) throw new VersoError('The page you picked to put it in no longer exists.');
187
+ const dir = path.join(parentDir, slug);
188
+ if (fs.existsSync(dir)) throw new VersoError(`There's already a page at ${urlForDir(root, dir)}. Pick another name.`);
189
+ if (!listTemplates(root).includes(template)) throw new VersoError(`There's no template called "${template}".`);
190
+ const page = { dir, template, title: String(name).trim().slice(0, 300), description: '', date: today(), fields: {}, rich: {}, ...startingLayout(root, template) };
191
+ fillHeading(root, page);
192
+ writePage(root, page);
193
+ return readPage(root, dir);
194
+ }
195
+
196
+ // A new page's own heading starts as its name, so it isn't an empty field
197
+ // beside a title that's already filled in: the first empty text field
198
+ // called heading, title, headline or name.
199
+ export function fillHeading(root, page) {
200
+ let tpl = null;
201
+ try { tpl = loadTemplate(root, page.template); } catch { return page; }
202
+ if (!tpl) return page;
203
+ const name = ['heading', 'title', 'headline', 'name'].find((n) => tpl.fields.get(n)?.type === 'text');
204
+ if (name && !String(page.fields[name] ?? '').trim()) page.fields[name] = page.title;
205
+ return page;
206
+ }
207
+
208
+ // A page type's starting layout: templates/<name>.layout.json, { "blocks", "fields" },
209
+ // copied into every new page of that type, with fresh block ids. Images
210
+ // stay behind (they belong to the page they were added on) unless they
211
+ // start with "/", which means they're shared.
212
+ export function startingLayout(root, template) {
213
+ const file = path.join(root, 'templates', `${template}.layout.json`);
214
+ if (!fs.existsSync(file)) return {};
215
+ let data;
216
+ try { data = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return {}; }
217
+ const keepValue = (v) => !(v && typeof v === 'object' && typeof v.file === 'string' && !v.file.startsWith('/'));
218
+ const tidy = (fields) => Object.fromEntries(Object.entries(fields && typeof fields === 'object' ? fields : {}).filter(([, v]) => keepValue(v)));
219
+ const blocks = {};
220
+ Object.entries(data.blocks && typeof data.blocks === 'object' ? data.blocks : {}).forEach(([slot, list]) => {
221
+ if (!Array.isArray(list)) return;
222
+ blocks[slot] = list.map((inst) => {
223
+ const copy = cloneWithNewIds(inst);
224
+ const walk = (b) => { b.fields = tidy(b.fields); Object.values(b.blocks || {}).forEach((l) => l.forEach(walk)); };
225
+ walk(copy);
226
+ return copy;
227
+ });
228
+ });
229
+ return { fields: tidy(data.fields), blocks };
230
+ }
231
+
232
+ export function listTemplates(root) {
233
+ const dir = path.join(root, 'templates');
234
+ if (!fs.existsSync(dir)) return [];
235
+ return fs.readdirSync(dir).filter((f) => f.endsWith('.html')).map((f) => f.slice(0, -5)).sort();
236
+ }
237
+
238
+ export function listBlocks(root) {
239
+ const dir = path.join(root, 'blocks');
240
+ if (!fs.existsSync(dir)) return [];
241
+ return fs.readdirSync(dir).filter((f) => f.endsWith('.html')).map((f) => f.slice(0, -5)).sort();
242
+ }
243
+
244
+ export function loadBlock(root, name) {
245
+ const file = path.join(root, 'blocks', `${name}.html`);
246
+ if (!fs.existsSync(file)) return null;
247
+ return parseWithParts(root, file, parseBlock);
248
+ }
249
+
250
+ // A block's source with its parts filled in, for anything that reads the
251
+ // file itself (the builder) and then needs it whole.
252
+ export function withParts(root, source, file = 'block.html') {
253
+ PART.lastIndex = 0;
254
+ return PART.test(source) ? expandParts(root, source, file).source : source;
255
+ }
256
+
257
+ // Parts: {{ part:header }} in a template is replaced by parts/header.html
258
+ // before the template is read, so a header or footer lives in one file.
259
+ // Errors and field lines still point at the file and line they came from.
260
+ const PART = /\{\{\s*part:([^{}<>]*?)\s*\}\}/g;
261
+
262
+ export function listParts(root) {
263
+ const dir = path.join(root, 'parts');
264
+ if (!fs.existsSync(dir)) return [];
265
+ return fs.readdirSync(dir).filter((f) => f.endsWith('.html')).map((f) => f.slice(0, -5)).sort();
266
+ }
267
+
268
+ export function expandParts(root, source, file) {
269
+ const segments = []; // { start, end, file, firstLine } in the expanded text
270
+ let out = '';
271
+ let last = 0;
272
+ let line = 1; // line in the template file at `last`
273
+ const pushOwn = (text) => {
274
+ if (text) segments.push({ start: out.length, end: out.length + text.length, file, firstLine: line });
275
+ out += text;
276
+ line += text.split('\n').length - 1;
277
+ };
278
+ for (const m of source.matchAll(PART)) {
279
+ pushOwn(source.slice(last, m.index));
280
+ const call = m[1].trim();
281
+ const name = call.split(/\s+/)[0];
282
+ const where = { file, line, hint: `In {{ part:${call} }}` };
283
+ const args = readPartArgs(call.slice(name.length), where);
284
+ if (!/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name)) throw new VersoError(`"${name}" can't be a part name. Use the name of a file in parts/, without .html.`, where);
285
+ const partFile = path.join(root, 'parts', `${name}.html`);
286
+ if (!fs.existsSync(partFile)) {
287
+ const known = listParts(root);
288
+ throw new VersoError(`There's no part called "${name}" in parts/.`, { ...where, hint: known.length ? `The parts are: ${known.join(', ')}.` : 'Make parts/' + name + '.html with the shared HTML in it.' });
289
+ }
290
+ const raw = fs.readFileSync(partFile, 'utf8').replace(/\n$/, '');
291
+ const nested = /\{\{\s*part:/.exec(raw);
292
+ const partRel = rel(root, partFile);
293
+ if (nested) throw new VersoError("Parts can't include other parts.", { file: partRel, line: lineAt(raw, nested.index), hint: 'Put both parts in the template instead.' });
294
+ const text = fillPart(raw, args, { name, partRel, where });
295
+ segments.push({ start: out.length, end: out.length + text.length, file: partRel, firstLine: 1, part: name });
296
+ out += text;
297
+ line += m[0].split('\n').length - 1;
298
+ last = m.index + m[0].length;
299
+ }
300
+ pushOwn(source.slice(last));
301
+ // Where a position in the expanded text came from.
302
+ const locate = (index) => {
303
+ const seg = segments.find((sg) => index >= sg.start && index < sg.end) || segments[segments.length - 1];
304
+ if (!seg) return { file, line: 1 };
305
+ return { file: seg.file, line: seg.firstLine + lineAt(out.slice(seg.start, Math.max(seg.start, index)), index - seg.start) - 1 };
306
+ };
307
+ return { source: out, segments, locate, parts: segments.filter((sg) => sg.part).map((sg) => sg.part) };
308
+ }
309
+
310
+ // {{ part:card title=item.title label="Read more" }}: a reference (item.,
311
+ // page., parent., paging.) or "quoted text" for each value.
312
+ function readPartArgs(text, where) {
313
+ const args = {};
314
+ const re = /([a-zA-Z][a-zA-Z0-9_-]*)\s*=\s*("([^"]*)"|'([^']*)'|((?:item|page|parent|paging)\.[a-zA-Z][a-zA-Z0-9_-]*))|(\S+)/g;
315
+ for (const m of text.matchAll(re)) {
316
+ if (m[6]) throw new VersoError(`"${m[6]}" isn't a value a part can take.`, { ...where, hint: 'Write name=item.title, or name="Some text". ' + where.hint });
317
+ args[m[1]] = m[5] ? { ref: m[5] } : { text: m[3] ?? m[4] ?? '' };
318
+ }
319
+ return args;
320
+ }
321
+
322
+ const escapeText = (v) => String(v).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
323
+
324
+ // Puts a part's values in place: {{ part.title }} becomes {{ item.title }}
325
+ // or the quoted text, and part.title inside another tag, like
326
+ // {{ if:part.title }}, becomes the reference.
327
+ function fillPart(text, args, { name, partRel, where }) {
328
+ return text.replace(/\{\{([^{}<>]*)\}\}/g, (whole, inner, index) => {
329
+ if (!/\bpart\./.test(inner)) return whole;
330
+ const line = lineAt(text, index);
331
+ const plain = /^\s*part\.([a-zA-Z][a-zA-Z0-9_-]*)(?::([a-z0-9-]+))?\s*$/.exec(inner);
332
+ const missing = (key) => new VersoError(`The part "${name}" shows part.${key}, but this {{ part:${name} }} doesn't give it one.`, { ...where, hint: `Add ${key}=item.${key} or ${key}="…" to it. It's used in ${partRel}, line ${line}.` });
333
+ if (plain) {
334
+ const arg = args[plain[1]];
335
+ if (!arg) throw missing(plain[1]);
336
+ if (arg.ref) return `{{ ${arg.ref}${plain[2] ? `:${plain[2]}` : ''} }}`;
337
+ return escapeText(arg.text);
338
+ }
339
+ return whole.replace(/\bpart\.([a-zA-Z][a-zA-Z0-9_-]*)/g, (m, key) => {
340
+ const arg = args[key];
341
+ if (!arg) throw missing(key);
342
+ if (!arg.ref) throw new VersoError(`part.${key} is text in this {{ part:${name} }}, so ${whole.trim()} can't use it.`, { ...where, hint: `Give it a reference instead, like ${key}=item.${key}.` });
343
+ return arg.ref;
344
+ });
345
+ });
346
+ }
347
+
348
+ export function loadTemplate(root, name) {
349
+ const file = path.join(root, 'templates', `${name}.html`);
350
+ if (!fs.existsSync(file)) return null;
351
+ return parseWithParts(root, file, parseTemplate);
352
+ }
353
+
354
+ // Reads a template or a block, puts its parts in, and parses it. Errors and
355
+ // fields are traced back to the file and line they were written in.
356
+ function parseWithParts(root, file, parse) {
357
+ const original = fs.readFileSync(file, 'utf8');
358
+ const fileRel = rel(root, file);
359
+ PART.lastIndex = 0;
360
+ if (!PART.test(original)) return parse(original, fileRel);
361
+ PART.lastIndex = 0;
362
+ const expanded = expandParts(root, original, fileRel);
363
+ // Line n of the expanded text, back to its own file and line.
364
+ const lineStarts = [0];
365
+ for (let i = 0; i < expanded.source.length; i++) if (expanded.source[i] === '\n') lineStarts.push(i + 1);
366
+ const back = (line) => expanded.locate(lineStarts[Math.max(0, (line || 1) - 1)] ?? 0);
367
+ let template;
368
+ try {
369
+ template = parse(expanded.source, fileRel);
370
+ } catch (err) {
371
+ if (err instanceof VersoError && err.line) Object.assign(err, back(err.line));
372
+ throw err;
373
+ }
374
+ template.parts = expanded.parts;
375
+ template.fields.forEach((f) => { const at = back(f.line); f.line = at.line; f.file = at.file; });
376
+ return template;
377
+ }
378
+
379
+ // Checks one page against its template. Returns problems; never throws.
380
+ // strict: also report empty required fields and unused content, which the
381
+ // build refuses but the editor only marks.
382
+ const isBlank = (page, field, siteFields = null) => {
383
+ if (field.site) {
384
+ const key = field.name.slice(5);
385
+ const v = field.type === 'rich' ? siteFields?.rich?.[key] : siteFields?.fields?.[key];
386
+ return field.type === 'rich' ? richIsEmpty(v) : !String(v ?? '').trim();
387
+ }
388
+ if (field.type === 'rich') return richIsEmpty(page.rich?.[field.name]);
389
+ if (field.type === 'image') return !page.fields[field.name]?.file;
390
+ if (field.type === 'color') return !page.fields[field.name]?.color;
391
+ return !String(page.fields[field.name] ?? '').trim();
392
+ };
393
+
394
+ export function checkPage(root, page, template, { strict = true, blocks = null } = {}) {
395
+ const problems = [];
396
+ if (!page.template) {
397
+ problems.push(new VersoError('This page doesn\'t say which template it uses. Add "template": "page" (or another file in templates/).', { file: page.file }));
398
+ return problems;
399
+ }
400
+ if (!template) {
401
+ const names = listTemplates(root).join(', ') || 'none yet';
402
+ problems.push(new VersoError(`This page uses the template "${page.template}", but templates/${page.template}.html doesn't exist. Templates: ${names}.`, { file: page.file }));
403
+ return problems;
404
+ }
405
+ const stored = [...Object.keys(page.fields), ...Object.keys(page.rich || {})];
406
+ stored.forEach((name) => {
407
+ const field = template.fields.get(name);
408
+ if (!field) {
409
+ if (strict) {
410
+ problems.push(new VersoError(`${page.label} has content for "${name}", but ${template.file} no longer has that field, so it isn't shown.`, { file: page.file, hint: 'Remove it from the page in the editor, or put the field back in the template.', warning: true }));
411
+ }
412
+ return;
413
+ }
414
+ const isRich = name in (page.rich || {});
415
+ const value = page.fields[name];
416
+ if (field.type === 'rich' && !isRich) problems.push(new VersoError(`"${name}" is rich text, so it belongs in ${name}.html next to page.json.`, { file: page.file }));
417
+ if (field.type !== 'rich' && isRich) problems.push(new VersoError(`"${name}" is a ${field.type} field, so ${name}.html isn't used.`, { file: page.file.replace(PAGE_FILE, `${name}.html`), hint: 'Delete that file, or make the field rich text.' }));
418
+ if (field.type === 'text' && value != null && typeof value !== 'string') {
419
+ problems.push(new VersoError(`"${name}" should be text.`, { file: page.file }));
420
+ }
421
+ if (field.type === 'color' && value != null && (typeof value !== 'object' || typeof value.color !== 'string')) {
422
+ problems.push(new VersoError(`"${name}" should be one of the site's colours, like { "color": "blue" }.`, { file: page.file }));
423
+ }
424
+ if (field.type === 'image' && value != null) {
425
+ if (typeof value !== 'object' || typeof value.file !== 'string') problems.push(new VersoError(`"${name}" should be an image, like { "file": "photo.jpg", "alt": "…" }.`, { file: page.file }));
426
+ else if (value.file && !fs.existsSync(path.join(page.dir, value.file))) problems.push(new VersoError(`The image for "${field.label}" on ${page.label}, ${value.file}, is missing from the page's folder.`, { file: page.file, hint: 'Choose the image again in the editor.' }));
427
+ }
428
+ });
429
+ if (template && Object.keys(page.blocks || {}).length) problems.push(...checkBlocks(page, template, blocks || new Map(), { strict }));
430
+ if (page.date && !/^\d{4}-\d{2}-\d{2}$/.test(page.date)) problems.push(new VersoError(`The date "${page.date}" should look like 2026-11-16.`, { file: page.file }));
431
+ if (strict) {
432
+ template.fields.forEach((field) => {
433
+ if (field.required && isBlank(page, field, readSiteData(root))) {
434
+ problems.push(new VersoError(`"${field.label}" on ${page.label} is required, but it's empty.`, { file: page.file, hint: `Fill it in on the page, or remove :required from ${field.file || template.file}, line ${field.line}.` }));
435
+ }
436
+ });
437
+ }
438
+ return problems;
439
+ }
440
+
441
+ // Everything about the site, checked. Template problems are collected rather
442
+ // than thrown, so one broken template doesn't hide the rest of the site.
443
+ export function loadSite(root) {
444
+ const config = readConfig(root);
445
+ const templates = new Map();
446
+ const templateErrors = new Map();
447
+ listTemplates(root).forEach((name) => {
448
+ try {
449
+ templates.set(name, loadTemplate(root, name));
450
+ } catch (err) {
451
+ if (!(err instanceof VersoError)) throw err;
452
+ templateErrors.set(name, err);
453
+ }
454
+ });
455
+ // Blocks, and every slot's list of allowed blocks, checked against blocks/.
456
+ const blocks = new Map();
457
+ listBlocks(root).forEach((name) => {
458
+ try {
459
+ blocks.set(name, loadBlock(root, name));
460
+ } catch (err) {
461
+ if (!(err instanceof VersoError)) throw err;
462
+ templateErrors.set(`block:${name}`, err);
463
+ }
464
+ });
465
+ [...templates.values(), ...blocks.values()].forEach((tpl) => {
466
+ tpl.fields.forEach((f) => {
467
+ if (f.type !== 'blocks') return;
468
+ f.tools.forEach((name) => {
469
+ if (!blocks.has(name) && !templateErrors.has(`block:${name}`)) {
470
+ templateErrors.set(`slot:${tpl.file}:${f.name}:${name}`, new VersoError(`The block area "${f.name}" allows a block called "${name}", but blocks/${name}.html doesn't exist.`, { file: tpl.file, line: f.line }));
471
+ }
472
+ });
473
+ });
474
+ });
475
+ // Each {{ list:team }} item is a block of its own, named after its template
476
+ // and list ("about--team"), so the editor can add, move and remove items
477
+ // the way it does blocks.
478
+ const withLists = [...templates.entries(), ...[...blocks.entries()].filter(([, b]) => b && b.repeaters)];
479
+ withLists.forEach(([name, tpl]) => {
480
+ (tpl.repeaters || []).forEach((r) => {
481
+ const blockName = `${name}--${r.name}`;
482
+ r.item.repeaterOf = { template: name, list: r.name, label: humanize(r.name) };
483
+ blocks.set(blockName, r.item);
484
+ tpl.fields.get(r.name).tools = [blockName];
485
+ });
486
+ });
487
+ // Components ride along on the blocks map, so everything that renders or
488
+ // checks blocks (and is handed site.blocks) can expand them.
489
+ const comps = listComponents(root);
490
+ blocks.components = comps.components;
491
+ comps.errors.forEach((e, i) => templateErrors.set(`component:${i}`, e));
492
+ const pages = [];
493
+ const pageErrors = [];
494
+ listPageDirs(root).forEach((dir) => {
495
+ try {
496
+ pages.push(readPage(root, dir));
497
+ } catch (err) {
498
+ if (!(err instanceof VersoError)) throw err;
499
+ pageErrors.push(err);
500
+ }
501
+ });
502
+ const siteData = readSiteData(root);
503
+ setSiteData(siteData);
504
+ pages.filter((p) => p.tagsOf && !fs.existsSync(path.join(root, 'content', ...p.tagsOf.split('/')))).forEach((p) => {
505
+ pageErrors.push(new VersoError(`This page holds the tags of content/${p.tagsOf}/, but that folder doesn't exist.`, { file: p.file, hint: 'Fix "tags-of" in page.json, or remove it.' }));
506
+ });
507
+ return { root, config, templates, blocks, templateErrors, pages, pageErrors, siteData, tagPages: tagPages(pages) };
508
+ }
509
+
510
+ // Site fields: content/site.json holds { "fields": {…}, "rich": {…} }.
511
+ export const SITE_FILE = 'site.json';
512
+ export function readSiteData(root) {
513
+ const file = path.join(root, 'content', SITE_FILE);
514
+ if (!fs.existsSync(file)) return { fields: {}, rich: {}, blocks: {} };
515
+ const data = readJSON(root, file);
516
+ const obj = (v) => (v && typeof v === 'object' && !Array.isArray(v) ? v : {});
517
+ return { fields: obj(data.fields), rich: obj(data.rich), blocks: obj(data.blocks) };
518
+ }
519
+ export function writeSiteData(root, data) {
520
+ const file = path.join(root, 'content', SITE_FILE);
521
+ const out = { fields: data.fields || {}, rich: data.rich || {} };
522
+ if (data.blocks && Object.keys(data.blocks).length) out.blocks = data.blocks;
523
+ const text = JSON.stringify(out, null, 2) + '\n';
524
+ // Only when something changed, so a save elsewhere isn't a change here.
525
+ if (fs.existsSync(file)) {
526
+ const now = fs.readFileSync(file, 'utf8');
527
+ try { if (JSON.stringify(JSON.parse(now)) === JSON.stringify(out)) return {}; } catch { /* rewrite a broken file */ }
528
+ }
529
+ writeAtomic(file, text);
530
+ return { [rel(root, file)]: text };
531
+ }
532
+
533
+ // The pages a tag home makes: one for each tag used in its folder, at
534
+ // /<home>/<tag>/. They're rendered with the home's template, and
535
+ // {{ page.tag }} says which tag they're for.
536
+ export function tagPages(pages, { drafts = false } = {}) {
537
+ const out = [];
538
+ pages.filter((p) => p.tagsOf && (drafts || !p.draft)).forEach((home) => {
539
+ const prefix = `/${home.tagsOf}/`;
540
+ const depth = prefix.split('/').filter(Boolean).length + 1;
541
+ const seen = new Map();
542
+ pages.filter((p) => (drafts || !p.draft) && !p.tagsOf && p.url.startsWith(prefix) && p.url.split('/').filter(Boolean).length === depth)
543
+ .forEach((p) => (p.tags || []).forEach((t) => { if (!seen.has(slugifyTag(t))) seen.set(slugifyTag(t), t); }));
544
+ seen.forEach((tag, slug) => {
545
+ if (!slug) return;
546
+ out.push({ ...home, url: `${home.url}${slug}/`, tag, title: `${tag} — ${home.label}`, label: tag, virtual: true, tagHome: home.url, tagsOf: home.tagsOf, fields: home.fields, rich: home.rich });
547
+ });
548
+ });
549
+ return out;
550
+ }
551
+
552
+ // Every problem that should stop a build.
553
+ export function checkSite(site) {
554
+ const problems = [...site.templateErrors.values(), ...site.pageErrors];
555
+ if (!site.pages.length && !site.pageErrors.length) {
556
+ problems.push(new VersoError('There are no pages yet. A page is a folder in content/ with a page.json in it.', { file: 'content/' }));
557
+ }
558
+ site.pages.forEach((page) => {
559
+ if (site.templateErrors.has(page.template)) return; // already reported
560
+ problems.push(...checkPage(site.root, page, site.templates.get(page.template), { blocks: site.blocks }));
561
+ });
562
+ // A list of pages from a folder that has none is almost always a typo.
563
+ site.templates.forEach((template) => {
564
+ template.lists.forEach((section) => {
565
+ if (!fs.existsSync(path.join(site.root, 'content', ...section.split('/')))) {
566
+ problems.push(new VersoError(`This template lists the pages in content/${section}/, but that folder doesn't exist.`, { file: template.file }));
567
+ }
568
+ });
569
+ });
570
+ return problems;
571
+ }
572
+
573
+ // Throws the problems that stop a build; returns the warnings.
574
+ export function assertSite(site) {
575
+ const all = checkSite(site);
576
+ const problems = all.filter((p) => !p.warning);
577
+ if (problems.length) throw new VersoErrors(problems);
578
+ return all.filter((p) => p.warning);
579
+ }
580
+
581
+ // Site slots ({{ site.header:blocks }}) keep their blocks in site.json. While
582
+ // the editor changes a page, they ride along on page.blocks as "site.header",
583
+ // so moving, copying and editing blocks works the same in both; splitting
584
+ // them off again before writing sends each list to its own file.
585
+ export function withSiteBlocks(page, siteData, template) {
586
+ page.blocks = page.blocks || {};
587
+ (template ? [...template.fields.values()] : []).filter((f) => f.site && f.type === 'blocks').forEach((f) => {
588
+ const name = f.name.slice(5);
589
+ siteData.blocks = siteData.blocks || {};
590
+ siteData.blocks[name] = Array.isArray(siteData.blocks[name]) ? siteData.blocks[name] : [];
591
+ page.blocks[f.name] = siteData.blocks[name];
592
+ });
593
+ return page;
594
+ }
595
+ export function writePageAndSite(root, page) {
596
+ const siteBlocks = {};
597
+ const own = {};
598
+ Object.entries(page.blocks || {}).forEach(([k, v]) => { if (k.startsWith('site.')) siteBlocks[k.slice(5)] = v; else own[k] = v; });
599
+ const files = writePage(root, { ...page, blocks: own });
600
+ const hadSite = Object.keys(siteBlocks).length > 0;
601
+ if (!hadSite) return files;
602
+ const data = readSiteData(root);
603
+ // Shared images belong to the whole site: keep them in content/ with a "/".
604
+ const share = (list) => list.forEach((b) => {
605
+ Object.entries(b.fields || {}).forEach(([k, v]) => {
606
+ if (v && typeof v === 'object' && typeof v.file === 'string' && v.file && !v.file.startsWith('/')) {
607
+ const from = path.join(page.dir, v.file);
608
+ const to = path.join(root, 'content', v.file);
609
+ if (fs.existsSync(from) && !fs.existsSync(to)) fs.copyFileSync(from, to);
610
+ if (fs.existsSync(to)) b.fields[k] = { ...v, file: `/${v.file}` };
611
+ }
612
+ });
613
+ Object.values(b.blocks || {}).forEach(share);
614
+ });
615
+ Object.values(siteBlocks).forEach(share);
616
+ data.blocks = { ...data.blocks, ...siteBlocks };
617
+ return { ...files, ...writeSiteData(root, data) };
618
+ }