domma-cms 1.30.1 → 1.32.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.
- package/CHANGELOG.md +14 -0
- package/CLAUDE.md +36 -1
- package/admin/js/api.js +1 -1
- package/admin/js/lib/block-packs.js +26 -0
- package/admin/js/lib/block-tags.js +6 -1
- package/admin/js/lib/blocks-arrange.js +1 -1
- package/admin/js/lib/collection-editor-arrange.js +1 -1
- package/admin/js/lib/collection-entries-arrange.js +1 -1
- package/admin/js/lib/collections-arrange.js +1 -1
- package/admin/js/lib/list-tags-arrange.js +1 -1
- package/admin/js/lib/list-tags.js +9 -7
- package/admin/js/lib/pages-arrange.js +1 -1
- package/admin/js/lib/shortcode-context-menu.js +1 -1
- package/admin/js/lib/shortcode-form.js +7 -4
- package/admin/js/templates/blocks.html +5 -3
- package/admin/js/templates/collections.html +12 -2
- package/admin/js/templates/docs/usage-blocks.html +28 -1
- package/admin/js/templates/pages.html +5 -3
- package/admin/js/views/blocks.js +5 -4
- package/admin/js/views/collection-editor.js +10 -4
- package/admin/js/views/collection-entries.js +2 -2
- package/admin/js/views/collections.js +6 -5
- package/admin/js/views/page-editor.js +1 -1
- package/admin/js/views/pages.js +4 -4
- package/docs/DommaFeatures.md +156 -5
- package/docs/api-reference.md +8 -6
- package/docs/markdown-shortcodes.md +22 -1
- package/docs/starter-blocks.md +70 -1
- package/package.json +1 -1
- package/public/css/site.css +1 -1
- package/public/js/collection-browser.js +1 -1
- package/server/blocks/catalog.json +6 -0
- package/server/blocks/domma-block-cushion-card.css +30 -0
- package/server/blocks/domma-block-cushion-card.html +11 -0
- package/server/blocks/domma-block-cushion-card.meta.json +7 -0
- package/server/routes/api/block-packs.js +55 -0
- package/server/routes/api/blocks.js +16 -2
- package/server/routes/api/collections.js +9 -1
- package/server/routes/api/list-tags.js +35 -10
- package/server/routes/api/pages.js +16 -2
- package/server/services/block-pack-assets.js +6 -0
- package/server/services/block-packs.js +291 -0
- package/server/services/block-slots.js +43 -0
- package/server/services/block-write-lock.js +44 -0
- package/server/services/blocks.js +18 -3
- package/server/services/collections.js +6 -0
- package/server/services/listTags.js +243 -47
- package/server/services/markdown.js +105 -8
- package/server/services/starter-block-packs.js +22 -0
- package/server/templates/page.html +2 -2
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
/** Portable, immutable block packs with conflict-checked installs and rollback. */
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import {createHash, randomUUID} from 'node:crypto';
|
|
5
|
+
import {fileURLToPath} from 'node:url';
|
|
6
|
+
import {withBlockWriteLock} from './block-write-lock.js';
|
|
7
|
+
import {blockSlots} from './block-slots.js';
|
|
8
|
+
import {PACK_ASSET_NAME_RE as ASSET, PACK_MEDIA_RE, packAssetFilename} from './block-pack-assets.js';
|
|
9
|
+
|
|
10
|
+
const NAME = /^[a-z0-9][a-z0-9-]{0,79}$/;
|
|
11
|
+
const VERSION = /^\d+\.\d+\.\d+$/;
|
|
12
|
+
const fail = (message, statusCode = 400) => Object.assign(new Error(message), {statusCode});
|
|
13
|
+
const hash = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
|
14
|
+
const fingerprint = block => block ? hash([block.html, block.css]) : null;
|
|
15
|
+
const compare = (a, b) => {
|
|
16
|
+
const aa = a.split('.').map(Number), bb = b.split('.').map(Number);
|
|
17
|
+
for (let i = 0; i < 3; i++) if (aa[i] !== bb[i]) return aa[i] - bb[i];
|
|
18
|
+
return 0;
|
|
19
|
+
};
|
|
20
|
+
function identifier(value, pattern = NAME) {
|
|
21
|
+
if (typeof value !== 'string' || value.length > 80 || (pattern === VERSION && value.length > 32) || !pattern.test(value)) throw fail('Invalid pack, block name or version.');
|
|
22
|
+
return value;
|
|
23
|
+
}
|
|
24
|
+
async function readJson(file, fallback) {
|
|
25
|
+
try { return JSON.parse(await fs.readFile(file, 'utf8')); }
|
|
26
|
+
catch (error) { if (error.code === 'ENOENT' && fallback !== undefined) return fallback; throw error; }
|
|
27
|
+
}
|
|
28
|
+
async function atomic(file, value) {
|
|
29
|
+
await fs.mkdir(path.dirname(file), {recursive:true});
|
|
30
|
+
const staging = `${file}.${randomUUID()}.part`;
|
|
31
|
+
try { await fs.writeFile(staging, value); await fs.rename(staging, file); }
|
|
32
|
+
finally { await fs.rm(staging, {force:true}); }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function validatePack(raw) {
|
|
36
|
+
if (!raw || raw.format !== 'domma-block-pack' || ![1,2].includes(raw.schema)) throw fail('Unsupported block pack format.');
|
|
37
|
+
identifier(raw.id); identifier(raw.version, VERSION);
|
|
38
|
+
if (typeof raw.title !== 'string' || !raw.title.trim() || raw.title.length > 120) throw fail('Pack title is required (up to 120 characters).');
|
|
39
|
+
if (!Array.isArray(raw.blocks) || !raw.blocks.length || raw.blocks.length > 100) throw fail('A pack needs 1 to 100 blocks.');
|
|
40
|
+
if (Buffer.byteLength(JSON.stringify(raw)) > 2_000_000) throw fail('Block pack exceeds 2 MB.');
|
|
41
|
+
const names = new Set();
|
|
42
|
+
const blocks = raw.blocks.map(block => {
|
|
43
|
+
identifier(block?.name);
|
|
44
|
+
if (names.has(block.name)) throw fail(`Duplicate block: ${block.name}`);
|
|
45
|
+
names.add(block.name);
|
|
46
|
+
if (typeof block.html !== 'string' || block.html.length > 200_000 || typeof block.css !== 'string' || block.css.length > 50 * 1024) throw fail(`Invalid HTML or CSS for ${block.name}.`);
|
|
47
|
+
return {name:block.name, html:block.html, css:block.css};
|
|
48
|
+
});
|
|
49
|
+
if(raw.assets != null && (!Array.isArray(raw.assets) || raw.assets.length>30)) throw fail('A pack can carry up to 30 media assets.');
|
|
50
|
+
if(raw.assets?.length && raw.schema!==2) throw fail('Bundled media requires pack schema 2.');
|
|
51
|
+
const assetNames=new Set();
|
|
52
|
+
const assets=(raw.assets || []).map(asset=>{
|
|
53
|
+
if(!asset || !ASSET.test(asset.name) || assetNames.has(asset.name) || typeof asset.data!=='string' || asset.data.length>1_400_000) throw fail('Invalid or duplicate pack media asset.');
|
|
54
|
+
const bytes=Buffer.from(asset.data,'base64');
|
|
55
|
+
if(!bytes.length || bytes.length>1_000_000 || bytes.toString('base64')!==asset.data) throw fail('Pack assets need canonical base64 data.');
|
|
56
|
+
assetNames.add(asset.name);
|
|
57
|
+
return {name:asset.name,data:asset.data};
|
|
58
|
+
});
|
|
59
|
+
for(const block of blocks) for(const text of [block.html,block.css]) {
|
|
60
|
+
for(const m of text.matchAll(/pack-asset:([a-zA-Z0-9][a-zA-Z0-9._-]*)/g)) if(!assetNames.has(m[1])) throw fail(`Missing media asset: ${m[1]}`);
|
|
61
|
+
}
|
|
62
|
+
const requires = {...(raw.requires || {})};
|
|
63
|
+
if (raw.requires != null && (typeof raw.requires !== 'object' || Array.isArray(raw.requires))) throw fail('Invalid pack requirements.');
|
|
64
|
+
if (blocks.some(b => blockSlots(b.html).length)) requires.slots ??= 1;
|
|
65
|
+
if (requires.slots != null && requires.slots !== 1) throw fail('This pack requires an unsupported slots version.');
|
|
66
|
+
if (requires.cms != null) identifier(requires.cms, VERSION);
|
|
67
|
+
if (requires.plugins != null && (!Array.isArray(requires.plugins) || requires.plugins.length > 50)) throw fail('Invalid plugin requirements.');
|
|
68
|
+
for (const plugin of requires.plugins || []) identifier(plugin);
|
|
69
|
+
return {format:raw.format, schema:raw.schema, id:raw.id, version:raw.version, title:raw.title.trim(),
|
|
70
|
+
description:String(raw.description || '').slice(0, 1000), requires:{...(requires.cms ? {cms:requires.cms} : {}), ...(requires.slots ? {slots:requires.slots} : {}), ...(requires.plugins?.length ? {plugins:requires.plugins} : {})}, ...(assets.length ? {assets} : {}), blocks};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function createBlockPackStore(root = fileURLToPath(new URL('../../', import.meta.url))) {
|
|
74
|
+
root = path.resolve(root);
|
|
75
|
+
const directory = path.join(root, 'content/blocks');
|
|
76
|
+
const data = path.join(root, 'content/block-packs');
|
|
77
|
+
const serial = fn => withBlockWriteLock(root,fn);
|
|
78
|
+
const releasePath = (id, version) => path.join(data, 'catalogue', identifier(id), `${identifier(version, VERSION)}.json`);
|
|
79
|
+
const statePath = id => path.join(data, 'installed', `${identifier(id)}.json`);
|
|
80
|
+
const pendingPath = id => path.join(data, 'pending', `${identifier(id)}.json`);
|
|
81
|
+
async function block(name) {
|
|
82
|
+
identifier(name);
|
|
83
|
+
try {
|
|
84
|
+
const html = await fs.readFile(path.join(directory, `${name}.html`), 'utf8');
|
|
85
|
+
const css = await fs.readFile(path.join(directory, `${name}.css`), 'utf8').catch(e => { if(e.code === 'ENOENT') return ''; throw e; });
|
|
86
|
+
const meta = await readJson(path.join(directory, `${name}.meta.json`), null);
|
|
87
|
+
return {name, html, css, meta};
|
|
88
|
+
} catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
89
|
+
}
|
|
90
|
+
async function writeBlock(name, value) {
|
|
91
|
+
for (const [extension, content] of [['html',value?.html], ['css',value?.css || null], ['meta.json',value?.meta ? JSON.stringify(value.meta, null, 2)+'\n' : null]]) {
|
|
92
|
+
const file = path.join(directory, `${identifier(name)}.${extension}`);
|
|
93
|
+
if (content == null) await fs.rm(file, {force:true});
|
|
94
|
+
else await atomic(file, content);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
async function published(id, version) {
|
|
98
|
+
try { return validatePack(await readJson(releasePath(id,version))); }
|
|
99
|
+
catch(e) { if(e.code === 'ENOENT') throw fail('Pack version not found.',404); throw e; }
|
|
100
|
+
}
|
|
101
|
+
async function publish(raw) {
|
|
102
|
+
const pack = validatePack(raw);
|
|
103
|
+
return serial(async () => {
|
|
104
|
+
const file = releasePath(pack.id,pack.version);
|
|
105
|
+
const existing = await readJson(file, null);
|
|
106
|
+
if (existing && hash(existing) !== hash(pack)) throw fail('Published versions are immutable. Choose a new version.',409);
|
|
107
|
+
if (!existing) await atomic(file, JSON.stringify(pack, null, 2)+'\n');
|
|
108
|
+
return pack;
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
async function list() {
|
|
112
|
+
const ids = await fs.readdir(path.join(data,'catalogue')).catch(e => { if(e.code === 'ENOENT') return []; throw e; });
|
|
113
|
+
const packs = [];
|
|
114
|
+
for (const id of ids.filter(id => NAME.test(id))) {
|
|
115
|
+
const files = await fs.readdir(path.join(data,'catalogue',id));
|
|
116
|
+
const versions = files.filter(n => n.endsWith('.json') && VERSION.test(n.slice(0,-5))).map(n => n.slice(0,-5)).sort(compare).reverse();
|
|
117
|
+
if (!versions.length) continue;
|
|
118
|
+
const latest = await published(id, versions[0]);
|
|
119
|
+
const installed = await readJson(statePath(id), null);
|
|
120
|
+
packs.push({id,title:latest.title,description:latest.description,versions,latest:latest.version,installed:installed?.version || null,blocks:latest.blocks.map(b => b.name)});
|
|
121
|
+
}
|
|
122
|
+
return packs;
|
|
123
|
+
}
|
|
124
|
+
async function assemble({id,version,title,description='',names,requires={},media=[]}) {
|
|
125
|
+
if (!Array.isArray(names) || names.length > 100 || !names.length) throw fail('Choose blocks for this pack.');
|
|
126
|
+
const blocks = [];
|
|
127
|
+
for (const name of names) {
|
|
128
|
+
const current = await block(name);
|
|
129
|
+
if (!current) throw fail(`Block not found: ${name}`,404);
|
|
130
|
+
blocks.push({name:current.name, html:current.html, css:current.css});
|
|
131
|
+
}
|
|
132
|
+
if(!Array.isArray(media) || media.length>30 || new Set(media).size!==media.length) throw fail('Choose up to 30 distinct media files.');
|
|
133
|
+
const mediaConfig=await readJson(path.join(root,'config/content.json'),{});
|
|
134
|
+
const mediaRoot=path.resolve(root,mediaConfig.mediaDir || 'content/media');
|
|
135
|
+
const assets=[];
|
|
136
|
+
for(const file of media) {
|
|
137
|
+
if(typeof file!=='string' || file!==path.basename(file) || file.includes('\\') || file.includes('\0') || !PACK_MEDIA_RE.test(file)) throw fail('Only local raster images and webfonts can be bundled.');
|
|
138
|
+
const stat=await fs.lstat(path.join(mediaRoot,file));
|
|
139
|
+
if(!stat.isFile() || stat.size>1_000_000) throw fail('Media assets must be regular files up to 1 MB.');
|
|
140
|
+
const bytes=await fs.readFile(path.join(mediaRoot,file));
|
|
141
|
+
const name=`media-${assets.length+1}${path.extname(file).toLowerCase()}`;
|
|
142
|
+
assets.push({name,data:bytes.toString('base64')});
|
|
143
|
+
for(const b of blocks) for(const key of ['html','css']) {
|
|
144
|
+
for(const url of new Set([`/media/${file}`,`/media/${encodeURIComponent(file)}`])) b[key]=b[key].replaceAll(url,`pack-asset:${name}`);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return publish({format:'domma-block-pack',schema:assets.length ? 2 : 1,id,version,title,description,requires,assets,blocks});
|
|
148
|
+
}
|
|
149
|
+
async function compatibility(pack) {
|
|
150
|
+
const problems = [];
|
|
151
|
+
const pkg = await readJson(path.join(root,'package.json'),null);
|
|
152
|
+
if(!pkg?.version) return ['This site is missing its CMS installation.'];
|
|
153
|
+
if(pack.assets?.length && !await fs.access(path.join(root,'server/services/block-pack-assets.js')).then(()=>true,()=>false)) problems.push('This site needs a CMS update with bundled block pack media support.');
|
|
154
|
+
if (pack.requires.slots && !await fs.access(path.join(root,'server/services/block-slots.js')).then(()=>true,()=>false)) problems.push('This site needs a CMS update with Custom Block slots support.');
|
|
155
|
+
if (pack.requires.cms) {
|
|
156
|
+
const version = VERSION.test(pkg.dependencies?.['domma-cms'] || '') ? pkg.dependencies['domma-cms'] : pkg.version;
|
|
157
|
+
if (compare(version,pack.requires.cms) < 0) problems.push(`Requires CMS ${pack.requires.cms} or later.`);
|
|
158
|
+
}
|
|
159
|
+
for (const plugin of pack.requires.plugins || []) {
|
|
160
|
+
const states = await readJson(path.join(root,'config/plugins.json'),{});
|
|
161
|
+
if (!await readJson(path.join(root,'plugins',plugin,'plugin.json'),null) || states[plugin]?.enabled !== true) problems.push(`Requires plugin ${plugin}, switched on.`);
|
|
162
|
+
}
|
|
163
|
+
return problems;
|
|
164
|
+
}
|
|
165
|
+
async function plan(raw) {
|
|
166
|
+
const pack = validatePack(raw), current = await readJson(statePath(pack.id),null);
|
|
167
|
+
const owners = new Map();
|
|
168
|
+
const installs = await fs.readdir(path.join(data,'installed')).catch(e => { if(e.code === 'ENOENT') return []; throw e; });
|
|
169
|
+
for (const file of installs.filter(n => /^[a-z0-9][a-z0-9-]*\.json$/.test(n))) {
|
|
170
|
+
const state = await readJson(path.join(data,'installed',file));
|
|
171
|
+
if (state.id !== pack.id) for(const name of Object.keys(state.hashes)) owners.set(name,state.id);
|
|
172
|
+
}
|
|
173
|
+
const mediaConfig=await readJson(path.join(root,'config/content.json'),{});
|
|
174
|
+
const mediaRoot=path.resolve(root,mediaConfig.mediaDir || 'content/media');
|
|
175
|
+
const assetChanges=[];
|
|
176
|
+
for(const asset of pack.assets || []) {
|
|
177
|
+
const file=path.join(mediaRoot,packAssetFilename(pack,asset.name));
|
|
178
|
+
const before=await fs.readFile(file).catch(e=>{if(e.code==='ENOENT')return null;throw e;});
|
|
179
|
+
const bytes=Buffer.from(asset.data,'base64');
|
|
180
|
+
assetChanges.push({name:asset.name,file,bytes,before,action:before ? 'unchanged' : 'create',
|
|
181
|
+
conflict:before && !before.equals(bytes) ? `Pack media was locally edited: ${asset.name}` : !before && current?.version===pack.version ? `Pack media was locally deleted: ${asset.name}` : ''});
|
|
182
|
+
}
|
|
183
|
+
const resolve=text=>text.replace(/pack-asset:([a-zA-Z0-9][a-zA-Z0-9._-]*)/g,(_,name)=>{
|
|
184
|
+
if(!assetChanges.some(a=>a.name===name)) throw fail(`Missing media asset: ${name}`);
|
|
185
|
+
return `/media/${packAssetFilename(pack,name)}`;
|
|
186
|
+
});
|
|
187
|
+
const desired = new Map(pack.blocks.map(b => [b.name,{...b,html:resolve(b.html),css:resolve(b.css)}]));
|
|
188
|
+
const names = new Set([...desired.keys(), ...Object.keys(current?.hashes || {})]);
|
|
189
|
+
const changes = [];
|
|
190
|
+
for(const name of names) {
|
|
191
|
+
const before = await block(name), after = desired.get(name) || null;
|
|
192
|
+
const unchanged = fingerprint(before) === fingerprint(after);
|
|
193
|
+
const owned = current && Object.hasOwn(current.hashes,name);
|
|
194
|
+
// A block the site already had (identical, so the pack adopted it) is the site's: a version that
|
|
195
|
+
// leaves it out lets go of it rather than deleting it.
|
|
196
|
+
if (!after && owned && (current.adopted || []).includes(name)) {
|
|
197
|
+
changes.push({name,action:'release',conflict:fingerprint(before) === current.hashes[name] ? '' : 'Locally edited or deleted. Duplicate to customise before updating.',before,after:null,adopted:true});
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
let conflict = '';
|
|
201
|
+
if (owners.has(name)) conflict = `Owned by pack ${owners.get(name)}.`;
|
|
202
|
+
else if (before && !owned && !unchanged) conflict = 'An existing site block uses this name. Duplicate or rename it first.';
|
|
203
|
+
else if (owned && fingerprint(before) !== current.hashes[name]) conflict = 'Locally edited or deleted. Duplicate to customise before updating.';
|
|
204
|
+
changes.push({name,action:unchanged?'unchanged':after?(before?'update':'create'):'remove',conflict,before,after,
|
|
205
|
+
adopted:Boolean(after && ((before && !owned && unchanged) || (owned && (current.adopted || []).includes(name))))});
|
|
206
|
+
}
|
|
207
|
+
return {id:pack.id,version:pack.version,from:current?.version || null,problems:[...await compatibility(pack),...assetChanges.filter(a=>a.conflict).map(a=>a.conflict)],changes,current,pack,assetChanges};
|
|
208
|
+
}
|
|
209
|
+
const summary = p => ({id:p.id,version:p.version,from:p.from,problems:p.problems,assets:p.assetChanges.map(a=>({name:a.name,action:a.action})),changes:p.changes.map(({name,action,conflict}) => ({name,action,conflict})),
|
|
210
|
+
token:hash([p.pack,p.current,p.changes.map(c=>[c.name,c.before]),p.assetChanges.map(a=>[a.name,a.before?.toString('base64')])])});
|
|
211
|
+
async function preview(raw) {
|
|
212
|
+
// Under the write lock, so an interrupted install is undone first and never mistaken for local edits.
|
|
213
|
+
return serial(async () => { await recoverInterrupted(validatePack(raw).id); return summary(await plan(raw)); });
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* An install the process died in the middle of: the blocks it had written are put back from its snapshot (the
|
|
217
|
+
* state file was never moved on), so the site is as it was before and the install can simply be run again.
|
|
218
|
+
*/
|
|
219
|
+
async function recoverInterrupted(id) {
|
|
220
|
+
const pending = await readJson(pendingPath(id),null);
|
|
221
|
+
if (!pending) return false;
|
|
222
|
+
const state = await readJson(statePath(id),null);
|
|
223
|
+
if (!state?.history?.includes(pending.historyId)) {
|
|
224
|
+
const snapshot = await readJson(path.join(data,'history',`${pending.historyId}.json`),null);
|
|
225
|
+
for (const b of snapshot?.blocks || []) await writeBlock(b.name,b.value);
|
|
226
|
+
}
|
|
227
|
+
await fs.rm(pendingPath(id),{force:true});
|
|
228
|
+
return true;
|
|
229
|
+
}
|
|
230
|
+
async function install(raw, token) {
|
|
231
|
+
return serial(async () => {
|
|
232
|
+
await recoverInterrupted(validatePack(raw).id);
|
|
233
|
+
const p = await plan(raw), review = summary(p);
|
|
234
|
+
if (review.token !== token) throw fail('The installation changed. Preview it again before applying.',409);
|
|
235
|
+
if (p.problems.length || p.changes.some(c=>c.conflict)) throw fail('Pack has compatibility issues or local conflicts. Nothing was changed.',409);
|
|
236
|
+
const historyId = randomUUID();
|
|
237
|
+
const snapshot = {id:historyId,packId:p.id,at:new Date().toISOString(),before:p.current,blocks:p.changes.map(c=>({name:c.name,value:c.before})),after:null};
|
|
238
|
+
const next = {id:p.id,version:p.version,hashes:Object.fromEntries(p.changes.filter(c=>c.after).map(c=>[c.name,fingerprint(c.after)])),history:[...(p.current?.history || []),historyId],
|
|
239
|
+
adopted:p.changes.filter(c=>c.after && c.adopted).map(c=>c.name)};
|
|
240
|
+
snapshot.after = next;
|
|
241
|
+
await atomic(path.join(data,'history',`${historyId}.json`),JSON.stringify(snapshot));
|
|
242
|
+
const createdAssets=[];
|
|
243
|
+
try {
|
|
244
|
+
for(const asset of p.assetChanges) if(!asset.before) {await atomic(asset.file,asset.bytes);createdAssets.push(asset.file);}
|
|
245
|
+
await atomic(pendingPath(p.id),JSON.stringify({historyId}));
|
|
246
|
+
for (const c of p.changes) if(!['unchanged','release'].includes(c.action)) await writeBlock(c.name,c.after ? {...c.after,meta:c.before?.meta || null} : null);
|
|
247
|
+
await atomic(statePath(p.id),JSON.stringify(next));
|
|
248
|
+
await fs.rm(pendingPath(p.id),{force:true});
|
|
249
|
+
} catch (error) {
|
|
250
|
+
for(const c of p.changes) if(c.action !== 'release') await writeBlock(c.name,c.before);
|
|
251
|
+
await fs.rm(pendingPath(p.id),{force:true});
|
|
252
|
+
for(const file of createdAssets) await fs.rm(file,{force:true});
|
|
253
|
+
throw error;
|
|
254
|
+
}
|
|
255
|
+
return {...review,historyId};
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
async function history(id) {
|
|
259
|
+
const state = await readJson(statePath(id),null);
|
|
260
|
+
const rows = [];
|
|
261
|
+
for(const key of state?.history || []) {
|
|
262
|
+
const record = await readJson(path.join(data,'history',`${key}.json`));
|
|
263
|
+
rows.push({id:key,at:record.at,from:record.before?.version || null,to:record.after.version});
|
|
264
|
+
}
|
|
265
|
+
return rows;
|
|
266
|
+
}
|
|
267
|
+
async function rollback(id) {
|
|
268
|
+
return serial(async () => {
|
|
269
|
+
await recoverInterrupted(id);
|
|
270
|
+
const current = await readJson(statePath(id),null);
|
|
271
|
+
if (!current?.history?.length) throw fail('No pack installation to roll back.',404);
|
|
272
|
+
const snapshot = await readJson(path.join(data,'history',`${current.history.at(-1)}.json`));
|
|
273
|
+
for(const name of Object.keys(current.hashes)) if(fingerprint(await block(name)) !== current.hashes[name]) throw fail(`Locally edited block ${name}; rollback cancelled.`,409);
|
|
274
|
+
for(const old of snapshot.blocks) if(!Object.hasOwn(current.hashes,old.name) && await block(old.name)) throw fail(`Block ${old.name} was recreated; rollback cancelled.`,409);
|
|
275
|
+
const before = await Promise.all(snapshot.blocks.map(async b=>({name:b.name,value:await block(b.name)})));
|
|
276
|
+
try {
|
|
277
|
+
for(const b of snapshot.blocks) {
|
|
278
|
+
const now=before.find(row=>row.name===b.name).value;
|
|
279
|
+
await writeBlock(b.name,b.value ? {...b.value,meta:now ? now.meta : b.value.meta} : null);
|
|
280
|
+
}
|
|
281
|
+
if(snapshot.before) await atomic(statePath(id),JSON.stringify(snapshot.before));
|
|
282
|
+
else await fs.rm(statePath(id),{force:true});
|
|
283
|
+
} catch(error) {
|
|
284
|
+
for(const b of before) await writeBlock(b.name,b.value);
|
|
285
|
+
throw error;
|
|
286
|
+
}
|
|
287
|
+
return {id,version:snapshot.before?.version || null};
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
return {list,publish,published,assemble,preview,install,history,rollback};
|
|
291
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/** Balanced block/slot syntax. Templates declare <slot name="body">fallback</slot>. */
|
|
2
|
+
export const SLOT_PATTERN = /<slot(?:\s+name=["']([a-z][\w-]*)["'])?\s*>([\s\S]*?)<\/slot\s*>/gi;
|
|
3
|
+
export function blockSlots(html) {
|
|
4
|
+
return [...new Set([...String(html || '').replace(/<!--[\s\S]*?-->/g, '').matchAll(SLOT_PATTERN)].map(m => m[1] || 'default'))];
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Outermost balanced [name]...[/name] pairs. Quoted brackets are part of attributes; only the supplied container
|
|
9
|
+
* tags take part. A closing tag pairs with the nearest open tag of its name, and opens it skips over are left
|
|
10
|
+
* unpaired: a stray `[my-card]` in prose never stops a later, properly closed call from being found.
|
|
11
|
+
*/
|
|
12
|
+
export function pairedRanges(text, names) {
|
|
13
|
+
const stack = [], pairs = [];
|
|
14
|
+
const re = /\[(\/)?([a-z][\w-]*)(?=[\s/\]])((?:"[^"]*"|'[^']*'|[^\]"'])*?)\]/gi;
|
|
15
|
+
for (const m of text.matchAll(re)) {
|
|
16
|
+
const name = m[2];
|
|
17
|
+
if (!names.has(name) || /\/\s*$/.test(m[3])) continue;
|
|
18
|
+
if (!m[1]) { stack.push({name, start:m.index, bodyStart:m.index + m[0].length, attrs:m[3]}); continue; }
|
|
19
|
+
const at = stack.findLastIndex(open => open.name === name);
|
|
20
|
+
if (at < 0) continue;
|
|
21
|
+
const open = stack[at];
|
|
22
|
+
stack.length = at;
|
|
23
|
+
pairs.push({...open, bodyEnd:m.index, end:m.index + m[0].length});
|
|
24
|
+
}
|
|
25
|
+
return pairs.filter(p => !pairs.some(q => q !== p && q.start < p.start && q.end >= p.end)).sort((a, b) => a.start - b.start);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Extract only direct slots, leaving nested blocks' slots with their owners. */
|
|
29
|
+
export function slotBodies(body, names, attrs) {
|
|
30
|
+
const result = new Map(), plain = [];
|
|
31
|
+
let cursor = 0;
|
|
32
|
+
for (const range of pairedRanges(body, new Set([...names, 'slot']))) {
|
|
33
|
+
if (range.name !== 'slot') continue;
|
|
34
|
+
const name = attrs(range.attrs).name || 'default';
|
|
35
|
+
plain.push(body.slice(cursor, range.start));
|
|
36
|
+
result.set(name, (result.get(name) || '') + body.slice(range.bodyStart, range.bodyEnd));
|
|
37
|
+
cursor = range.end;
|
|
38
|
+
}
|
|
39
|
+
plain.push(body.slice(cursor));
|
|
40
|
+
const rest = plain.join('').trim();
|
|
41
|
+
if (rest) result.set('default', rest);
|
|
42
|
+
return result;
|
|
43
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/** Serialise block edits and pack transactions, including a manager writing to a child site. */
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import {setTimeout as delay} from 'node:timers/promises';
|
|
5
|
+
const queues=new Map();
|
|
6
|
+
|
|
7
|
+
export async function withBlockWriteLock(root, action) {
|
|
8
|
+
root=path.resolve(root);
|
|
9
|
+
const previous=queues.get(root) || Promise.resolve();
|
|
10
|
+
const run=previous.catch(()=>{}).then(async()=>{
|
|
11
|
+
const lock=path.join(root,'content','.block-write-lock');
|
|
12
|
+
await fs.mkdir(path.dirname(lock),{recursive:true});
|
|
13
|
+
const deadline=Date.now()+5000;
|
|
14
|
+
for(;;) {
|
|
15
|
+
try {await fs.mkdir(lock);break;}
|
|
16
|
+
catch(error) {
|
|
17
|
+
if(error.code!=='EEXIST')throw error;
|
|
18
|
+
// A crashed writer must not leave blocks permanently locked.
|
|
19
|
+
// Held longer than any block write takes: its owner died and its pid may since belong to
|
|
20
|
+
// another process, so the pid check alone would keep every save waiting forever.
|
|
21
|
+
const held=await fs.stat(lock).catch(()=>null);
|
|
22
|
+
if(held && Date.now()-held.mtimeMs>120_000) {await fs.rm(lock,{recursive:true,force:true});continue;}
|
|
23
|
+
try {
|
|
24
|
+
const owner=Number(await fs.readFile(path.join(lock,'owner'),'utf8'));
|
|
25
|
+
if(!Number.isSafeInteger(owner) || owner<=0) throw Object.assign(new Error('Missing lock owner'),{code:'ENOENT'});
|
|
26
|
+
try {process.kill(owner,0);}
|
|
27
|
+
catch(e) {if(e.code==='ESRCH') {await fs.rm(lock,{recursive:true,force:true});continue;}}
|
|
28
|
+
} catch(e) {
|
|
29
|
+
if(e.code==='ENOENT') {
|
|
30
|
+
const stat=await fs.stat(lock).catch(()=>null);
|
|
31
|
+
if(stat && Date.now()-stat.mtimeMs>60_000) {await fs.rm(lock,{recursive:true,force:true});continue;}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
if(Date.now()>=deadline)throw Object.assign(new Error('Blocks are being changed by another operation. Try again.'),{statusCode:409});
|
|
35
|
+
await delay(25);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
try {await fs.writeFile(path.join(lock,'owner'),String(process.pid));return await action();}
|
|
39
|
+
finally {await fs.rm(lock,{recursive:true,force:true});}
|
|
40
|
+
});
|
|
41
|
+
queues.set(root,run);
|
|
42
|
+
try {return await run;}
|
|
43
|
+
finally {if(queues.get(root)===run)queues.delete(root);}
|
|
44
|
+
}
|
|
@@ -4,10 +4,12 @@
|
|
|
4
4
|
* Never overwrites existing files during seeding - user customisations are preserved.
|
|
5
5
|
*/
|
|
6
6
|
import fs from 'fs/promises';
|
|
7
|
+
import {withBlockWriteLock} from './block-write-lock.js';
|
|
7
8
|
import path from 'path';
|
|
8
9
|
import {fileURLToPath} from 'url';
|
|
9
10
|
import * as cache from './cache/index.js';
|
|
10
11
|
import {seedStarterBlocks} from './starter-blocks.js';
|
|
12
|
+
import {seedStarterBlockPacks} from './starter-block-packs.js';
|
|
11
13
|
|
|
12
14
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
13
15
|
const BLOCKS_DIR = path.resolve(__dirname, '../../content/blocks');
|
|
@@ -326,7 +328,7 @@ export async function getBlock(name) {
|
|
|
326
328
|
* @returns {Promise<{success: boolean, name: string}>}
|
|
327
329
|
* @throws {Error} With code INVALID_NAME on bad name, or CSS_TOO_LARGE when CSS exceeds cap
|
|
328
330
|
*/
|
|
329
|
-
|
|
331
|
+
async function saveBlockUnlocked(name, content, {bundled, css, meta, createOnly = false} = {}) {
|
|
330
332
|
assertValidName(name);
|
|
331
333
|
if (typeof css === 'string' && css.length > MAX_CSS_SIZE) {
|
|
332
334
|
const err = new Error(`CSS exceeds ${MAX_CSS_SIZE} byte limit`);
|
|
@@ -379,7 +381,7 @@ export async function saveBlock(name, content, {bundled, css, meta, createOnly =
|
|
|
379
381
|
* @returns {Promise<object>} the sidecar as written
|
|
380
382
|
* @throws {Error} With code INVALID_NAME, or ENOENT when the block is not found
|
|
381
383
|
*/
|
|
382
|
-
|
|
384
|
+
async function setBlockMetaUnlocked(name, patch) {
|
|
383
385
|
assertValidName(name);
|
|
384
386
|
await fs.access(blockFilePath(name));
|
|
385
387
|
let meta = {};
|
|
@@ -401,7 +403,7 @@ export async function setBlockMeta(name, patch) {
|
|
|
401
403
|
* @returns {Promise<void>}
|
|
402
404
|
* @throws {Error} With code INVALID_NAME or ENOENT when the block is not found
|
|
403
405
|
*/
|
|
404
|
-
|
|
406
|
+
async function deleteBlockUnlocked(name) {
|
|
405
407
|
assertValidName(name);
|
|
406
408
|
try {
|
|
407
409
|
await fs.unlink(blockFilePath(name));
|
|
@@ -430,9 +432,22 @@ export async function deleteBlock(name) {
|
|
|
430
432
|
*/
|
|
431
433
|
export async function seedDefaultBlocks() {
|
|
432
434
|
await seedStarterBlocks(BLOCKS_DIR);
|
|
435
|
+
await seedStarterBlockPacks();
|
|
433
436
|
for (const [name, content] of Object.entries(BLOCKS)) {
|
|
434
437
|
await seedBlock(name, content);
|
|
435
438
|
}
|
|
436
439
|
const names = Object.keys(BLOCKS).join(', ');
|
|
437
440
|
console.log(`[blocks] Seeded default blocks: ${names}`);
|
|
438
441
|
}
|
|
442
|
+
|
|
443
|
+
export async function saveBlock(...args) {
|
|
444
|
+
return withBlockWriteLock(path.resolve(__dirname, '../..'), () => saveBlockUnlocked(...args));
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
export async function setBlockMeta(...args) {
|
|
448
|
+
return withBlockWriteLock(path.resolve(__dirname, '../..'), () => setBlockMetaUnlocked(...args));
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
export async function deleteBlock(...args) {
|
|
452
|
+
return withBlockWriteLock(path.resolve(__dirname, '../..'), () => deleteBlockUnlocked(...args));
|
|
453
|
+
}
|
|
@@ -247,6 +247,12 @@ export async function deleteCollection(slug) {
|
|
|
247
247
|
invalidate(slug);
|
|
248
248
|
await fs.rm(collectionDir(slug), { recursive: true, force: true });
|
|
249
249
|
await cache.invalidateTags([`collection:${slug}`]);
|
|
250
|
+
// Its admin list tags live in config/list-tags.json, not in the folder just
|
|
251
|
+
// removed. Imported here, not at the top: listTags imports this module.
|
|
252
|
+
try {
|
|
253
|
+
const {dropCollectionTags} = await import('./listTags.js');
|
|
254
|
+
await dropCollectionTags(slug);
|
|
255
|
+
} catch { /* a stale entry is ignored anyway */ }
|
|
250
256
|
}
|
|
251
257
|
|
|
252
258
|
// ---------------------------------------------------------------------------
|