domma-cms 1.31.0 → 1.33.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.
Files changed (49) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/CLAUDE.md +20 -2
  3. package/admin/js/lib/admin-brand.js +1 -1
  4. package/admin/js/lib/admin-theme.js +1 -1
  5. package/admin/js/lib/block-packs.js +26 -0
  6. package/admin/js/lib/block-tags.js +6 -1
  7. package/admin/js/lib/shortcode-context-menu.js +2 -2
  8. package/admin/js/lib/shortcode-form.js +7 -4
  9. package/admin/js/lib/shortcode-registry.js +1 -1
  10. package/admin/js/lib/sidebar-frequent.js +1 -1
  11. package/admin/js/lib/sidebar-renderer.js +4 -4
  12. package/admin/js/lib/site-settings-arrange.js +2 -2
  13. package/admin/js/lib/theme-aware-logo.js +1 -0
  14. package/admin/js/templates/docs/usage-blocks.html +28 -1
  15. package/admin/js/templates/settings.html +7 -1
  16. package/admin/js/views/blocks.js +4 -4
  17. package/admin/js/views/settings.js +2 -2
  18. package/docs/DommaFeatures.md +87 -8
  19. package/docs/markdown-shortcodes.md +35 -1
  20. package/docs/starter-blocks.md +106 -1
  21. package/package.json +1 -1
  22. package/server/blocks/catalog.json +30 -0
  23. package/server/blocks/domma-block-comparison-card.css +20 -0
  24. package/server/blocks/domma-block-comparison-card.html +18 -0
  25. package/server/blocks/domma-block-comparison-card.meta.json +7 -0
  26. package/server/blocks/domma-block-cta-card.css +20 -0
  27. package/server/blocks/domma-block-cta-card.html +15 -0
  28. package/server/blocks/domma-block-cta-card.meta.json +7 -0
  29. package/server/blocks/domma-block-cushion-card.css +30 -0
  30. package/server/blocks/domma-block-cushion-card.html +11 -0
  31. package/server/blocks/domma-block-cushion-card.meta.json +7 -0
  32. package/server/blocks/domma-block-feature-card.css +20 -0
  33. package/server/blocks/domma-block-feature-card.html +15 -0
  34. package/server/blocks/domma-block-feature-card.meta.json +7 -0
  35. package/server/blocks/domma-block-image-card.css +20 -0
  36. package/server/blocks/domma-block-image-card.html +17 -0
  37. package/server/blocks/domma-block-image-card.meta.json +7 -0
  38. package/server/routes/api/block-packs.js +55 -0
  39. package/server/routes/api/blocks.js +4 -1
  40. package/server/services/adminBrand.js +4 -1
  41. package/server/services/block-pack-assets.js +6 -0
  42. package/server/services/block-packs.js +291 -0
  43. package/server/services/block-slots.js +43 -0
  44. package/server/services/block-write-lock.js +44 -0
  45. package/server/services/blocks.js +18 -3
  46. package/server/services/embedCsp.js +1 -1
  47. package/server/services/markdown.js +166 -14
  48. package/server/services/sidebarFrequent.js +1 -1
  49. package/server/services/starter-block-packs.js +22 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "bundled": true,
3
+ "adminTags": [
4
+ "domma-blocks",
5
+ "cards"
6
+ ]
7
+ }
@@ -0,0 +1,20 @@
1
+ /* Shared default card proportions; colour is opt-in and intentionally light. */
2
+ .db-card { --db-accent: var(--dm-primary, #486b82); box-sizing: border-box; height: 100%; display: flex; flex-direction: column; gap: .9rem; padding: 1.5rem; border: 1px solid var(--dm-border, #d5e0e5); border-radius: var(--dm-radius-lg, .75rem); background: var(--dm-card-bg, #fff); color: var(--dm-text, #152832); overflow-wrap: anywhere; }
3
+ .db-card[data-tone="blue"] { --db-accent: #547d99; }
4
+ .db-card[data-tone="teal"] { --db-accent: #50857b; }
5
+ .db-card[data-tone="violet"] { --db-accent: #837298; }
6
+ .db-card[data-tone="warm"] { --db-accent: #a37b59; }
7
+ .db-card:is([data-tone="blue"], [data-tone="teal"], [data-tone="violet"], [data-tone="warm"]) { background: color-mix(in srgb, var(--db-accent) 4%, var(--dm-card-bg, #fff)); border-color: color-mix(in srgb, var(--db-accent) 22%, var(--dm-border, #d5e0e5)); }
8
+ .db-card .db-card-icon { box-sizing: border-box; width: 2.5rem; height: 2.5rem; padding: .55rem; border-radius: .6rem; background: color-mix(in srgb, var(--db-accent) 10%, var(--dm-card-bg, #fff)); color: var(--db-accent); }
9
+ .db-card-icon[data-icon=""] { display: none; }
10
+ .db-card h3 { margin: 0; font-size: 1.2rem; font-weight: 650; line-height: 1.35; color: inherit; }
11
+ .db-card p { margin: 0; color: var(--dm-text-secondary, #465865); font-size: 1rem; line-height: 1.65; white-space: pre-line; }
12
+ .db-card p:empty { display: none; }
13
+ .db-card-choice { display: grid; gap: .35rem; }
14
+ .db-card-choice strong { font-size: .9rem; font-weight: 600; }
15
+ .db-card-choice + .db-card-choice { padding-top: .9rem; border-top: 1px solid var(--dm-border, #d5e0e5); }
16
+ .db-card .db-card-link { margin-top: auto; padding-top: .25rem; color: var(--dm-primary, #486b82); font-weight: 600; text-underline-offset: .2em; }
17
+ .db-card-link[href=""], .db-card-link:empty { display: none; }
18
+ .db-card-link:focus-visible { outline: 2px solid currentColor; outline-offset: 4px; }
19
+ .db-card-image { width: 100%; aspect-ratio: 16 / 10; object-fit: cover; border-radius: var(--dm-radius-md, .5rem); }
20
+ .db-card-image[src=""] { display: none; }
@@ -0,0 +1,17 @@
1
+ <!--
2
+ domma-block-image-card - Image card with a heading, description and optional link.
3
+
4
+ Parameters:
5
+ header - Card heading
6
+ icon - Optional Domma icon name
7
+ tone - Optional subtle accent: blue, teal, violet or warm; omitted is neutral
8
+ link - Optional link destination
9
+ label - Optional link text
10
+ blurb - Description as plain text
11
+ image - Image address from your Media library
12
+ alt - Image description
13
+
14
+ Example:
15
+ [domma-block-image-card header="Our work" blurb="Take a closer look at a recent project." image="/media/project.jpg" alt="A recent project" link="/showcase" label="View the project" /]
16
+ -->
17
+ <article class="db-card" data-tone="{{tone}}"><img class="db-card-image" src="{{image}}" alt="{{alt}}" loading="lazy" decoding="async"><span class="db-card-icon" data-icon="{{icon}}"></span><h3>{{header}}</h3><p>{{blurb}}</p><a class="db-card-link" href="{{link}}">{{label}}</a></article>
@@ -0,0 +1,7 @@
1
+ {
2
+ "bundled": true,
3
+ "adminTags": [
4
+ "domma-blocks",
5
+ "cards"
6
+ ]
7
+ }
@@ -0,0 +1,55 @@
1
+ import {authenticate, requirePermission} from '../../middleware/auth.js';
2
+ import {createBlockPackStore} from '../../services/block-packs.js';
3
+ import {invalidateTags} from '../../services/cache/index.js';
4
+
5
+ /** Catalogue administration requires site settings access, not just page editing. */
6
+ export function blockPackRoutes(fastify) {
7
+ const store = createBlockPackStore();
8
+ const read = {preHandler:[authenticate,requirePermission('settings','read')]};
9
+ const write = {preHandler:[authenticate,requirePermission('settings','update')]};
10
+ const upload = {...write,bodyLimit:2_100_000};
11
+ fastify.get('/block-packs',read,()=>store.list());
12
+ fastify.post('/block-packs',upload,request=>store.publish(request.body));
13
+ fastify.post('/block-packs/assemble',write,async (request,reply)=>{
14
+ if(request.body?.media?.length) {
15
+ await requirePermission('media','read')(request,reply);
16
+ if(reply.sent)return reply;
17
+ }
18
+ const {getBlock} = await import('../../services/blocks.js');
19
+ const {canSeeArtefact} = await import('../../services/projects.js');
20
+ if(Array.isArray(request.body?.names)) for(const name of request.body.names) {
21
+ let found;
22
+ try { found = await getBlock(name); }
23
+ catch { throw Object.assign(new Error(`Block not found: ${String(name).slice(0, 80)}`),{statusCode:404}); }
24
+ if(!canSeeArtefact(request.user,found)) throw Object.assign(new Error('Access denied for this project.'),{statusCode:403});
25
+ }
26
+ return store.assemble(request.body);
27
+ });
28
+ fastify.get('/block-packs/:id/:version/export',read,async(request,reply)=>{
29
+ const pack = await store.published(request.params.id,request.params.version);
30
+ reply.header('Content-Disposition',`attachment; filename="${pack.id}-${pack.version}.dmblockpack.json"`);
31
+ return pack;
32
+ });
33
+ fastify.post('/block-packs/:id/:version/preview',write,async request=>store.preview(await store.published(request.params.id,request.params.version)));
34
+ fastify.post('/block-packs/:id/:version/install',write,async (request,reply)=>{
35
+ const pack = await store.published(request.params.id,request.params.version);
36
+ // A pack with pictures adds them to Media, so it needs what an upload needs.
37
+ if(pack.assets?.length) {
38
+ await requirePermission('media','create')(request,reply);
39
+ if(reply.sent)return reply;
40
+ }
41
+ const result = await store.install(pack,request.body?.token);
42
+ await invalidateTags(result.changes.map(c=>`block:${c.name}`));
43
+ return result;
44
+ });
45
+ fastify.get('/block-packs/:id/history',read,request=>store.history(request.params.id));
46
+ fastify.post('/block-packs/:id/rollback',write,async request=>{
47
+ const catalogue = await store.list();
48
+ const result = await store.rollback(request.params.id);
49
+ // Blocks removed by a previous version can reappear during rollback.
50
+ const names = catalogue.find(p=>p.id===request.params.id)?.blocks || [];
51
+ const {listBlocks} = await import('../../services/blocks.js');
52
+ await invalidateTags([...new Set([...names,...(await listBlocks()).map(b=>b.name)])].map(n=>`block:${n}`));
53
+ return result;
54
+ });
55
+ }
@@ -12,6 +12,8 @@
12
12
  * DELETE /api/blocks/:name - delete block
13
13
  */
14
14
  import fs from 'fs/promises';
15
+ import {blockPackRoutes} from './block-packs.js';
16
+ import {blockSlots} from '../../services/block-slots.js';
15
17
  import path from 'path';
16
18
  import {authenticate, requirePermission} from '../../middleware/auth.js';
17
19
  import {deleteBlock, getBlock, listBlocks, saveBlock} from '../../services/blocks.js';
@@ -211,6 +213,7 @@ export function blocksBadge(blocks = []) {
211
213
  const BUNDLE_FORMAT = 1;
212
214
 
213
215
  export async function blocksRoutes(fastify) {
216
+ blockPackRoutes(fastify);
214
217
  const canRead = {preHandler: [authenticate, requirePermission('pages', 'read')]};
215
218
  const canUpdate = {preHandler: [authenticate, requirePermission('pages', 'update')]};
216
219
  const canDelete = {preHandler: [authenticate, requirePermission('pages', 'delete')]};
@@ -229,7 +232,7 @@ export async function blocksRoutes(fastify) {
229
232
  try { full = await getBlock(b.name); } catch { /* skip */ }
230
233
  if (!canSeeArtefact(user, full)) continue;
231
234
  out.push({...b, hasCss: Boolean(full?.css), cssSize: full?.css?.length || 0, ...blockDoc(full?.content, b.name),
232
- fields: blockFields(full?.content), shortTag: isShortTag(b.name)});
235
+ slots: blockSlots(full?.content), fields: blockFields(full?.content), shortTag: isShortTag(b.name)});
233
236
  }
234
237
  return out;
235
238
  }
@@ -16,18 +16,21 @@ export const DEFAULT_ADMIN_TITLE = 'Domma CMS';
16
16
 
17
17
  /**
18
18
  * @param {object} [site] - config/site.json
19
- * @returns {{title: string, logo: string, icon: string}}
19
+ * @returns {{title: string, logo: string, logoDark: string, icon: string}}
20
20
  */
21
21
  export function adminBrandFor(site = {}) {
22
22
  const own = site?.adminBrand && typeof site.adminBrand === 'object' ? site.adminBrand : {};
23
23
  // Whitespace collapsed: a title reads back that way from the browser tab.
24
24
  const str = (v) => (typeof v === 'string' ? v.replace(/[ \t\n\f\r]+/g, ' ').trim() : '');
25
25
  const logo = str(own.logo);
26
+ const logoDark = str(own.logoDark);
26
27
  return {
27
28
  enabled: own.enabled !== false,
28
29
  title: (str(own.title) || str(site?.title) || DEFAULT_ADMIN_TITLE).slice(0, 120),
29
30
  // Same rule as the sidebar header: a site path or an http(s) address, nothing else.
30
31
  logo: /^(?:\/(?!\/)|https?:\/\/)/i.test(logo) ? logo : '',
32
+ // Optional: the logo for a dark admin theme (lib/theme-aware-logo.js picks one by the theme's background).
33
+ logoDark: /^(?:\/(?!\/)|https?:\/\/)/i.test(logoDark) ? logoDark : '',
31
34
  icon: /^[a-z0-9-]{1,40}$/.test(str(own.icon)) ? str(own.icon) : ''
32
35
  };
33
36
  }
@@ -0,0 +1,6 @@
1
+ /** Schema 2 adds portable, versioned raster images and webfonts to block packs. */
2
+ export const PACK_ASSET_NAME_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,99}\.(?:png|jpe?g|gif|webp|avif|ico|bmp|tiff?|woff2?)$/i;
3
+ export const PACK_MEDIA_RE = /\.(?:png|jpe?g|gif|webp|avif|ico|bmp|tiff?|woff2?)$/i;
4
+ export function packAssetFilename(pack, name) {
5
+ return `pack-${pack.id}-${pack.version}-${name}`;
6
+ }
@@ -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
- export async function saveBlock(name, content, {bundled, css, meta, createOnly = false} = {}) {
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
- export async function setBlockMeta(name, patch) {
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
- export async function deleteBlock(name) {
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
+ }
@@ -15,7 +15,7 @@
15
15
  */
16
16
  /** The players [embed] always uses. */
17
17
  // youtube.com too: the HTML sanitiser lets its iframes through, so the policy must agree.
18
- export const ALWAYS_FRAMED = ['https://www.youtube-nocookie.com', 'https://www.youtube.com', 'https://youtube.com', 'https://player.vimeo.com'];
18
+ export const ALWAYS_FRAMED = ['https://www.youtube-nocookie.com', 'https://www.youtube.com', 'https://youtube.com', 'https://player.vimeo.com', 'https://www.google.com'];
19
19
 
20
20
  /** A bare hostname, or nothing: a host in embeds.json must never smuggle in a scheme, path or wildcard. */
21
21
  const HOST_RE = /^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/;