cook-ssg 2.9.0 → 2.10.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/README.md CHANGED
@@ -147,6 +147,7 @@ The build process performs the following steps, in this order:
147
147
  * Repeats elements for each item in collections (`[data-repeat]`, nesting supported)
148
148
  * Replaces custom elements and `[data-component]` elements with templates (nesting supported; flat or Declarative Shadow DOM)
149
149
  * Replaces ES6 template strings (`${}`) with front matter + global data
150
+ * Fills empty `<social-links>` elements with profile links from `config/social.json`
150
151
  * Rewrites `<img>` to responsive `<picture>` elements
151
152
  * Detects custom elements and manages component JS loading (`autoComponents` config)
152
153
  * Pre-renders Declarative Shadow DOM from a manifest (`dsd` config)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cook-ssg",
3
- "version": "2.9.0",
3
+ "version": "2.10.0",
4
4
  "description": "Cook your static pages into a beautifully performing site. Static site generation the web platform way.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -11,7 +11,8 @@
11
11
  ".": "./scripts/build.js",
12
12
  "./build": "./scripts/build.js",
13
13
  "./dev": "./scripts/dev.js",
14
- "./layouts": "./scripts/layouts.js"
14
+ "./layouts": "./scripts/layouts.js",
15
+ "./social": "./scripts/social/index.js"
15
16
  },
16
17
  "files": [
17
18
  "bin/",
package/scripts/build.js CHANGED
@@ -38,6 +38,7 @@ import processHtmlFrontmatter from './plugins/process-html-frontmatter.js';
38
38
  import replaceInclude from './plugins/replace-include.js';
39
39
  import replaceInline from './plugins/replace-inline.js';
40
40
  import replaceMissingExternalLinkProtocol from './plugins/replace-external-link-protocol.js';
41
+ import { socialData, fillSocialLinks } from './plugins/social-links.js';
41
42
  import replaceTemplateStrings from './plugins/replace-template-strings.js';
42
43
  import conditionalSections from './plugins/conditional-sections.js';
43
44
  import setActiveLinks from './plugins/set-active-links.js';
@@ -107,6 +108,9 @@ class Build {
107
108
  // PLUGIN: Programs: `programs` / `programAreas` data from config/programs.json
108
109
  await programsData({data});
109
110
 
111
+ // PLUGIN: Social: `social` data from config/social.json (or main.js `social`)
112
+ await socialData({data});
113
+
110
114
  // PLUGIN: Generate responsive image derivatives (AVIF/WebP at multiple widths)
111
115
  await optimizeImagesGenerate({store});
112
116
 
@@ -191,6 +195,9 @@ class Build {
191
195
  const templateData = file.frontMatter ? { ...data, ...file.frontMatter } : data;
192
196
  replaceTemplateStrings({file, data: templateData, allowType: ['.html', '.json', '.webmanifest']});
193
197
 
198
+ // PLUGIN: Fill empty <social-links> elements with the site's profile links
199
+ fillSocialLinks({file, data, allowType: ['.html']});
200
+
194
201
  // PLUGIN: Rewrite <img> to <picture> with responsive srcset
195
202
  await optimizeImagesRewrite({file, store, allowType: ['.html']});
196
203
 
package/scripts/dev.js CHANGED
@@ -173,3 +173,7 @@ browserSync.watch(themeJson).on('change', file => { rebuild(file); }).on('add',
173
173
  // config/programs.json (Vanilla Press) feeds the programs data: rebuild on change.
174
174
  const programsJson = `${process.cwd()}/config/programs.json`;
175
175
  browserSync.watch(programsJson).on('change', file => { rebuild(file); }).on('add', file => { rebuild(file); });
176
+
177
+ // config/social.json (Vanilla Press) feeds <social-links>: rebuild on change.
178
+ const socialJson = `${process.cwd()}/config/social.json`;
179
+ browserSync.watch(socialJson).on('change', file => { rebuild(file); }).on('add', file => { rebuild(file); });
@@ -0,0 +1,48 @@
1
+ /**
2
+ * @file social-links.js
3
+ * @description Social accounts: reads config/social.json (or main.js `social`),
4
+ * exposes `social.accounts` / `social.allAccounts` data, and fills each empty
5
+ * `<social-links>` element with a `<ul>` of profile links at build time.
6
+ */
7
+
8
+ import chalk from 'chalk';
9
+ import Util from '../utils/util/util.js';
10
+ import { getSocial } from '../utils/config/config.js';
11
+ import { normalizeAccounts, renderSocialLinks } from '../social/index.js';
12
+
13
+ const TAG = '[social] ';
14
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
15
+ const SKIP_INSIDE = 'pre, code, template, textarea';
16
+
17
+ let visibleAccounts = [];
18
+
19
+ /** Set `social` on the data store when a social config exists. */
20
+ export async function socialData({ data }) {
21
+ visibleAccounts = [];
22
+ const raw = getSocial();
23
+ if (raw === undefined) return;
24
+ const { all, visible, warnings } = normalizeAccounts(raw);
25
+ for (const w of warnings) console.log(chalk.yellow(`${TAG}${w}`));
26
+ visibleAccounts = visible;
27
+ data.social = { ...(isObj(raw) ? raw : {}), accounts: visible, allAccounts: all };
28
+ }
29
+
30
+ /**
31
+ * Fill each `<social-links>` that has no element child. Leaves the page's bytes
32
+ * alone when it has no live `<social-links>`.
33
+ */
34
+ export function fillSocialLinks({ file, allowType }) {
35
+ if (!Util.isAllowedType({ file, allowType })) return;
36
+ if (typeof file.src !== 'string' || !file.src.includes('<social-links')) return;
37
+ const dom = Util.fileDom(file);
38
+ const live = [...dom.window.document.querySelectorAll('social-links')]
39
+ .filter((el) => !el.closest(SKIP_INSIDE) && el.children.length === 0);
40
+ let changed = false;
41
+ for (const el of live) {
42
+ const html = renderSocialLinks(visibleAccounts, { services: el.getAttribute('services') ?? undefined });
43
+ if (!html) continue;
44
+ el.innerHTML = html;
45
+ changed = true;
46
+ }
47
+ Util.commitDom(file, dom, changed);
48
+ }
@@ -0,0 +1,160 @@
1
+ /**
2
+ * @file accounts.js
3
+ * @description Parse and validate social account handles, build profile URLs and
4
+ * normalize the `accounts` list from config/social.json. Pure: no fs, no config.
5
+ */
6
+
7
+ import { serviceById } from './catalog.js';
8
+
9
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
10
+
11
+ const DOMAIN = /^(?=.{3,253}$)(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
12
+ const GITHUB = /^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$/;
13
+ const MASTODON_USER = /^[A-Za-z0-9_](?:[A-Za-z0-9_.-]*[A-Za-z0-9_])?$/;
14
+ const LINKEDIN_SLUG = /^[A-Za-z0-9_%-]+$/;
15
+ const YOUTUBE = /^@[A-Za-z0-9._-]+$/;
16
+
17
+ /**
18
+ * If `s` is a pasted URL on `host` (optional `https?://` and `www.`, optional trailing
19
+ * slash), return the path after the host; otherwise null. Bare handles never match.
20
+ */
21
+ const urlPath = (s, host) => {
22
+ const m = s.match(new RegExp(`^(?:https?://)?(?:www\\.)?${host.replace(/\./g, '\\.')}/(.+?)/*$`, 'i'));
23
+ return m ? m[1] : null;
24
+ };
25
+
26
+ const fail = (error) => ({ error });
27
+
28
+ /** @param {string} v */
29
+ function isHttpsUrl(v) {
30
+ if (!/^https:\/\//i.test(v)) return false;
31
+ try {
32
+ return new URL(v).protocol === 'https:';
33
+ } catch {
34
+ return false;
35
+ }
36
+ }
37
+
38
+ /**
39
+ * Turn what a person typed (or pasted) into the stored handle.
40
+ * @param {string} service
41
+ * @param {string} input
42
+ * @returns {{ handle: string } | { error: string }}
43
+ */
44
+ export function parseHandle(service, input) {
45
+ if (typeof input !== 'string') return fail('Enter a handle');
46
+ const raw = input.trim();
47
+ if (!raw) return fail('Enter a handle');
48
+
49
+ switch (service) {
50
+ case 'bluesky': {
51
+ const m = (urlPath(raw, 'bsky.app') || '').match(/^profile\/([^/]+)$/i);
52
+ const handle = (m ? m[1] : raw).replace(/^@/, '').toLowerCase();
53
+ return DOMAIN.test(handle) ? { handle } : fail('Bluesky handles look like name.bsky.social');
54
+ }
55
+ case 'mastodon': {
56
+ const s = raw;
57
+ const m = s.match(/^(?:https?:\/\/)?([^/@\s]+)\/@([^/@]+)\/*$/i);
58
+ let user;
59
+ let instance;
60
+ if (m) {
61
+ [, instance, user] = m;
62
+ } else {
63
+ const parts = s.replace(/^@/, '').split('@');
64
+ if (parts.length !== 2) return fail('Mastodon handles look like @user@instance');
65
+ [user, instance] = parts;
66
+ }
67
+ instance = instance.toLowerCase();
68
+ if (!MASTODON_USER.test(user) || !DOMAIN.test(instance)) return fail('Mastodon handles look like @user@instance');
69
+ return { handle: `@${user}@${instance}` };
70
+ }
71
+ case 'github': {
72
+ const p = urlPath(raw, 'github.com');
73
+ const handle = (p && !p.includes('/') ? p : raw).replace(/^@/, '');
74
+ return GITHUB.test(handle) ? { handle } : fail('GitHub usernames are 1 to 39 letters, digits or single hyphens');
75
+ }
76
+ case 'linkedin': {
77
+ const m = (urlPath(raw, 'linkedin.com') || '').match(/^in\/([^/]+)$/i) || raw.match(/^in\/([^/]+?)\/*$/i);
78
+ const slug = m ? m[1] : raw;
79
+ return LINKEDIN_SLUG.test(slug) ? { handle: slug } : fail('Use the part after linkedin.com/in/');
80
+ }
81
+ case 'youtube': {
82
+ const p = urlPath(raw, 'youtube.com');
83
+ const handle = p && !p.includes('/') ? p : raw;
84
+ return YOUTUBE.test(handle) ? { handle } : fail('YouTube handles look like @name');
85
+ }
86
+ case 'link':
87
+ return isHttpsUrl(raw) ? { handle: raw } : fail('Links must start with https://');
88
+ default:
89
+ return fail(`Unknown service "${service}"`);
90
+ }
91
+ }
92
+
93
+ /**
94
+ * The public profile URL for an account, or null when it can't be built.
95
+ * @param {{ service?: string, handle?: string, url?: string } | null | undefined} account
96
+ * @returns {string | null}
97
+ */
98
+ export function profileUrl(account) {
99
+ if (!isObj(account)) return null;
100
+ const { service, handle, url } = account;
101
+ if (service === 'link') return typeof url === 'string' && isHttpsUrl(url) ? url : null;
102
+ if (typeof handle !== 'string' || !handle) return null;
103
+ switch (service) {
104
+ case 'bluesky': return `https://bsky.app/profile/${handle}`;
105
+ case 'mastodon': {
106
+ const m = handle.match(/^@([^@]+)@([^@]+)$/);
107
+ return m ? `https://${m[2]}/@${m[1]}` : null;
108
+ }
109
+ case 'github': return `https://github.com/${handle}`;
110
+ case 'linkedin': return `https://www.linkedin.com/in/${handle}`;
111
+ case 'youtube': return `https://www.youtube.com/${handle}`;
112
+ default: return null;
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Validate the raw contents of config/social.json. A bad entry is skipped with a
118
+ * warning; the rest still build.
119
+ * @param {unknown} raw
120
+ * @returns {{ all: object[], visible: object[], warnings: string[] }}
121
+ */
122
+ export function normalizeAccounts(raw) {
123
+ const warnings = [];
124
+ const all = [];
125
+ const list = isObj(raw) ? raw.accounts : undefined;
126
+ if (list !== undefined && !Array.isArray(list)) warnings.push('accounts must be an array; ignoring it');
127
+
128
+ (Array.isArray(list) ? list : []).forEach((entry, i) => {
129
+ const at = `accounts[${i}]`;
130
+ if (!isObj(entry)) return void warnings.push(`${at}: not an object; skipped`);
131
+ const svc = typeof entry.service === 'string' ? serviceById(entry.service) : undefined;
132
+ if (!svc) return void warnings.push(`${at}: unknown service ${JSON.stringify(entry.service)}; skipped`);
133
+
134
+ const hidden = entry.hidden === true;
135
+ if (svc.id === 'link') {
136
+ const label = typeof entry.label === 'string' ? entry.label.trim() : '';
137
+ const url = typeof entry.url === 'string' ? entry.url.trim() : '';
138
+ if (!label) return void warnings.push(`${at}: link needs a label; skipped`);
139
+ if (!isHttpsUrl(url)) return void warnings.push(`${at}: link url must be https:; skipped`);
140
+ all.push({ service: 'link', handle: '', url, name: label, icon: 'link', hidden });
141
+ return;
142
+ }
143
+
144
+ const parsed = parseHandle(svc.id, entry.handle);
145
+ if ('error' in parsed) return void warnings.push(`${at}: ${svc.id} handle ${JSON.stringify(entry.handle)}: ${parsed.error}; skipped`);
146
+ const account = {
147
+ service: svc.id,
148
+ handle: parsed.handle,
149
+ url: profileUrl({ service: svc.id, handle: parsed.handle }),
150
+ name: svc.name,
151
+ icon: svc.id,
152
+ hidden,
153
+ };
154
+ if (svc.id === 'bluesky' && typeof entry.did === 'string' && entry.did.startsWith('did:')) account.did = entry.did;
155
+ all.push(account);
156
+ });
157
+
158
+ return { all, visible: all.filter((a) => !a.hidden), warnings };
159
+ }
160
+
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @file catalog.js
3
+ * @description The services Cook knows how to link to: ids, display names and
4
+ * whether Vanilla Press can check a handle against the service. Pure data, no
5
+ * dependencies.
6
+ */
7
+
8
+ /** @type {Array<{ id: string, name: string, checkable: boolean }>} */
9
+ export const SERVICES = [
10
+ { id: 'bluesky', name: 'Bluesky', checkable: true },
11
+ { id: 'mastodon', name: 'Mastodon', checkable: true },
12
+ { id: 'github', name: 'GitHub', checkable: true },
13
+ { id: 'linkedin', name: 'LinkedIn', checkable: false },
14
+ { id: 'youtube', name: 'YouTube', checkable: false },
15
+ { id: 'link', name: 'Link', checkable: false },
16
+ ];
17
+
18
+ /** @param {string} id */
19
+ export const serviceById = (id) => SERVICES.find((s) => s.id === id);
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @file index.js
3
+ * @description Public entry for `cook-ssg/social`: the service catalog, account
4
+ * parsing and the profile-links renderer. Pure and dependency-free.
5
+ */
6
+
7
+ export { SERVICES } from './catalog.js';
8
+ export { parseHandle, profileUrl, normalizeAccounts } from './accounts.js';
9
+ export { renderSocialLinks } from './render.js';
@@ -0,0 +1,28 @@
1
+ /**
2
+ * @file render.js
3
+ * @description Render normalized accounts as the `<ul>` of profile links that
4
+ * goes inside `<social-links>`. Pure: no fs, no config.
5
+ */
6
+
7
+ const escapeHtml = (s) =>
8
+ String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
9
+
10
+ /**
11
+ * @param {Array<{ service: string, url: string, name: string, icon?: string }>} accounts
12
+ * @param {{ services?: string, variant?: string }} [options] `variant` is for CSS and
13
+ * is copied onto the element by the fill step; it does not change the list.
14
+ * @returns {string} the `<ul>…</ul>`, or '' when nothing matches
15
+ */
16
+ export function renderSocialLinks(accounts, { services } = {}) {
17
+ if (!Array.isArray(accounts)) return '';
18
+ const wanted = typeof services === 'string' && services.trim()
19
+ ? new Set(services.split(',').map((s) => s.trim()).filter(Boolean))
20
+ : null;
21
+ const items = accounts
22
+ .filter((a) => a && a.url && (!wanted || wanted.has(a.service)))
23
+ .map((a) => {
24
+ const rel = a.service === 'mastodon' ? ' rel="me"' : '';
25
+ return `<li><a href="${escapeHtml(a.url)}"${rel}><span class="social-icon" data-service="${escapeHtml(a.service)}" aria-hidden="true"></span><span>${escapeHtml(a.name)}</span></a></li>`;
26
+ });
27
+ return items.length ? `<ul>${items.join('')}</ul>` : '';
28
+ }
@@ -49,6 +49,21 @@ function getPrograms() {
49
49
  }
50
50
  }
51
51
 
52
+ // config/social.json (written by Vanilla Press): the site's social accounts; main.js `social` wins when defined
53
+ const socialJsonPath = `${cwd}/config/social.json`;
54
+
55
+ /** The social config. Re-read on every call, like getTheme. */
56
+ function getSocial() {
57
+ if (userConfig.social !== undefined) return userConfig.social;
58
+ if (!fs.existsSync(socialJsonPath)) return undefined;
59
+ try {
60
+ return JSON.parse(fs.readFileSync(socialJsonPath, 'utf8'));
61
+ } catch (err) {
62
+ console.log(chalk.yellow(`[social] config/social.json: ${err.message}`));
63
+ return undefined;
64
+ }
65
+ }
66
+
52
67
 
53
68
  // DEFINE DEFAULT CONFIG
54
69
  // -----------------------------
@@ -349,7 +364,7 @@ const config = mergeConfigs(defaultConfig, userConfig);
349
364
  export default config;
350
365
 
351
366
  // Named exports for destructuring imports
352
- export { getTheme, getPrograms };
367
+ export { getTheme, getPrograms, getSocial };
353
368
  export const {
354
369
  activeLink,
355
370
  autoComponents,
@@ -12,8 +12,11 @@
12
12
  const INDENT = ' ';
13
13
 
14
14
  const escapeAttr = (value) => String(value).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
15
+ // Invisible characters are written as references, so they show in the file
16
+ const INVISIBLE_REFS = { '\u00a0': '&nbsp;', '\u00ad': '&shy;', '\u200b': '&#8203;', '\u2060': '&#8288;' };
15
17
  const escapeMarkup = (text) => text
16
- .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\u00a0/g, '&nbsp;');
18
+ .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
19
+ .replace(/[\u00a0\u00ad\u200b\u2060]/g, (c) => INVISIBLE_REFS[c]);
17
20
  // A text run is literal: a `${` in it must not become a placeholder
18
21
  const escapeText = (text) => escapeMarkup(text).replace(/\$\{/g, '&#36;{');
19
22