Files
portfolio/scripts/content.mjs
T
2026-11-10 13:54:19 +01:00

94 lines
7.5 KiB
JavaScript

import { readdir, readFile, writeFile } from 'node:fs/promises';
import { pathToFileURL } from 'node:url';
const root = new URL('../', import.meta.url);
const readJSON = async path => JSON.parse(await readFile(new URL(path, root), 'utf8'));
const pairs = ['kind', 'title', 'name', 'intro', 'context', 'implementation', 'decisions'];
const require = (ok, message) => { if (!ok) throw new Error(message); };
const pair = value => Array.isArray(value) && value.length === 2 && value.every(v => typeof v === 'string' && v.trim());
const keys = (value, expected) => value !== null && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length === expected.length && expected.every(k => Object.hasOwn(value, k));
const safeHTTPS = value => {
if (typeof value !== 'string' || /[\s\\<>"']/.test(value)) return false;
try {
const url = new URL(value);
return value.startsWith('https://') && url.protocol === 'https:' && !!url.hostname && !url.username && !url.password;
} catch { return false; }
};
export function validateSettings(settings) {
require(keys(settings, ['profile', 'revision', 'processes']), 'settings: expected only profile, revision and processes');
const p = settings.profile;
require(keys(p, ['name', 'github', 'gitea', 'school', 'qualification', 'reviewed']), 'profile: invalid structure');
require(typeof p.name === 'string' && p.name.trim(), 'profile.name: required text');
require(typeof p.reviewed === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(p.reviewed) && Number.isFinite(Date.parse(p.reviewed)) && new Date(p.reviewed).toISOString().slice(0, 10) === p.reviewed, 'profile.reviewed: expected a valid ISO date');
for (const key of ['github', 'gitea', 'school', 'qualification']) require(safeHTTPS(p[key]), `profile.${key}: expected a safe HTTPS URL`);
require(/^https:\/\/github\.com\/[A-Za-z0-9_-]+$/.test(p.github), 'profile.github: expected a GitHub profile');
require(/^https:\/\/codealvin\.xyz\/[A-Za-z0-9_-]+$/.test(p.gitea), 'profile.gitea: expected a Gitea profile');
require(/^https:\/\/github\.com\/[A-Za-z0-9_-]+\/[A-Za-z0-9_.-]+$/.test(p.school) && !['.', '..'].includes(p.school.split('/').pop()), 'profile.school: expected a GitHub repository');
require(typeof settings.revision === 'string' && /^[a-f0-9]{40}$/.test(settings.revision), 'revision: expected a full lowercase commit SHA');
require(Array.isArray(settings.processes), 'processes: expected an array');
const codes = new Set();
for (const process of settings.processes) {
require(keys(process, ['code', 'title', 'description']), 'process: invalid structure');
require(typeof process.code === 'string' && /^B[1-9]\d*-K[1-9]\d*-W[1-9]\d*$/.test(process.code) && !codes.has(process.code), 'process.code: invalid or duplicate code');
codes.add(process.code);
require(pair(process.title) && pair(process.description), 'process: provide Dutch and English title and description');
}
}
export function validateProjects(projects, processes) {
const ids = new Set();
const codes = new Set(processes.map(p => p.code));
const require = (ok, message) => { if (!ok) throw new Error(message); };
const pair = value => Array.isArray(value) && value.length === 2 && value.every(v => typeof v === 'string' && v.trim());
const path = value => typeof value === 'string' && value.length > 0 && !value.startsWith('/') && !value.split('/').some(p => p === '..' || p === '.');
const mapping = value => Array.isArray(value) && value.every(c => codes.has(c));
for (const p of projects) {
require(/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(p.id) && !ids.has(p.id), `Invalid or duplicate project ID: ${p.id}`);
ids.add(p.id);
for (const key of pairs) require(pair(p[key]), `${p.id}.${key}: provide Dutch and English text`);
for (const key of ['number', 'challenge']) require(typeof p[key] === 'string' && p[key].trim(), `${p.id}.${key}: required text`);
for (const key of ['stack', 'nodes']) require(Array.isArray(p[key]) && p[key].length > 0 && p[key].every(v => typeof v === 'string' && v.trim()), `${p.id}.${key}: provide text entries`);
require(p.nodes.length === 3, `${p.id}.nodes: provide three diagram labels`);
if (p.repository !== undefined) {
const r = p.repository;
require(r && /^https:\/\/(github\.com|codealvin\.xyz)\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(r.url) && /^[a-f0-9]{40}$/.test(r.revision) && ['github', 'gitea'].includes(r.forge) && (r.forge === 'github') === r.url.startsWith('https://github.com/'), `${p.id}.repository: provide a supported repository and pinned commit`);
}
require(path(p.path) || (p.repository && p.path === ''), `${p.id}.path: provide a repository-relative path`);
require(p.setting === undefined || pair(p.setting), `${p.id}.setting: provide Dutch and English text`);
require(mapping(p.codes), `${p.id}.codes: unknown process code`);
require(Array.isArray(p.evidence), `${p.id}.evidence: expected an array`);
for (const e of p.evidence) {
require(pair(e.label) && path(e.path) && typeof e.type === 'string' && e.type.trim() && mapping(e.codes) && (e.directory === undefined || typeof e.directory === 'boolean'), `${p.id}: invalid evidence item`);
}
}
}
export async function compileContent() {
const settings = await readJSON('content/settings.json');
validateSettings(settings);
const files = (await readdir(new URL('content/projects/', root))).filter(f => f.endsWith('.json')).sort();
const projects = await Promise.all(files.map(f => readJSON(`content/projects/${f}`)));
projects.sort((a, b) => a.number.localeCompare(b.number, undefined, { numeric: true }));
validateProjects(projects, settings.processes);
return '// Generated from content/ by npm run content. Edit the JSON source files.\n' +
Object.entries({ profile: settings.profile, revision: settings.revision, processes: settings.processes, projects }).map(([key, value]) => `export const ${key} = ${JSON.stringify(value, null, 2)};`).join('\n') +
'\nexport const source = (path, directory = false, project = {}) => {\n' +
' const repo = project.repository || { url: profile.school, revision, forge: "github" };\n' +
' const view = repo.forge === "gitea" ? "src/commit" : (directory ? "tree" : "blob");\n' +
' return `${repo.url}/${view}/${repo.revision}${path ? "/" + path.split("/").map(encodeURIComponent).join("/") : ""}`;\n' +
'};\n';
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
const [command, id] = process.argv.slice(2);
if (command === 'add') {
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(id || '')) throw new Error('Usage: npm run project:add -- my-project');
const files = (await readdir(new URL('content/projects/', root))).filter(f => f.endsWith('.json'));
const existing = await Promise.all(files.map(f => readJSON(`content/projects/${f}`)));
const p = { id, number: String(Math.max(0, ...existing.map(p => Number(p.number) || 0)) + 1).padStart(2, '0'), challenge: '—' };
for (const key of pairs) p[key] = [key === 'name' ? id : 'Nog aanvullen', key === 'name' ? id : 'To be completed'];
Object.assign(p, { stack: ['To be completed'], codes: [], path: 'projects', nodes: ['Input', 'Application', 'Output'], evidence: [] });
await writeFile(new URL(`content/projects/${id}.json`, root), JSON.stringify(p, null, 2) + '\n', { flag: 'wx' });
console.log(`Created content/projects/${id}.json — replace the placeholder text before publishing.`);
}
await writeFile(new URL('content.js', root), await compileContent());
console.log('Validated and generated content.js');
}