// generate-content.mjs — читает content/projects/*.md и content/team/*.md, // парсит frontmatter (без внешних зависимостей) и пишет src/data/{projects,team}.js // как window.HMT_* = [...] для статической страницы (vanilla, без сборки). // // Запуск: node scripts/generate-content.mjs // Пользователь заполняет .md в след. сессиях → повторный запуск подтянет правки. import { readFileSync, readdirSync, writeFileSync, existsSync, mkdirSync } from 'node:fs'; import { basename, join, dirname } from 'node:path'; import { fileURLToPath } from 'node:url'; const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..'); const PROJ_DIR = join(ROOT, 'content', 'projects'); const TEAM_DIR = join(ROOT, 'content', 'team'); const OUT = join(ROOT, 'src', 'data'); // ---- minimal frontmatter parser: `---\n key: value\n ---` ---- // Supports: scalar `key: value`, inline list `key: [a, b]`, // block list `key:` + indented `- a` lines, block map `key:` + indented ` sub: v`. function parseFrontmatter(path) { const raw = readFileSync(path, 'utf8').replace(/^\uFEFF/, ''); const m = raw.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/); const meta = {}; const body = m ? m[2] : raw; if (m) { const lines = m[1].split(/\r?\n/); let i = 0; while (i < lines.length) { const line = lines[i]; if (!line.trim() || line.trimStart().startsWith('#')) { i++; continue; } const idx = line.indexOf(':'); if (idx < 0) { i++; continue; } const key = line.slice(0, idx).trim(); const val = line.slice(idx + 1).trim(); if (val === '') { // block value: look ahead at indented lines const block = []; let j = i + 1; while (j < lines.length) { const nxt = lines[j]; const trimmed = nxt.trim(); const indent = nxt.match(/^\s*/)[0].length; if (!trimmed || indent === 0) break; block.push(trimmed); j++; } if (block.length) { i = j; if (block[0].startsWith('-')) { meta[key] = block.map((b) => b.slice(1).trim().replace(/^['"]|['"]$/g, '')); } else { const map = {}; for (const b of block) { const bi = b.indexOf(':'); if (bi > 0) map[b.slice(0, bi).trim()] = coerce(b.slice(bi + 1).trim()); } meta[key] = map; } continue; } } meta[key] = coerce(val); i++; } } return { meta, body: body.trim() }; } // coerce a value: keep one-line scalar; leave nested to JSON-in-frontmatter caller. function coerce(v) { if (v === undefined) return ''; if (typeof v !== 'string') return v; const t = v.trim(); if (t === '') return ''; if (/^(true|false)$/i.test(t)) return t.toLowerCase() === 'true'; if (/^-?\d+$/.test(t)) return Number(t); if (/^-?\d+(\.\d+)?$/.test(t)) return Number(t); // array-ish literal: ["a", "b"] or [a, b] if (t.startsWith('[') && t.endsWith(']')) { const inner = t.slice(1, -1).trim(); if (!inner) return []; return inner.split(',').map((s) => s.trim().replace(/^['"]|['"]$/g, '')); } // ponytail: scalars are NOT comma-split — prose contains commas // («Проект студии — описание, платформы и метрики…» became an array that way). return t; } // toList: only the fields that ARE lists accept `a, b` scalar form. function toList(v) { if (Array.isArray(v)) return v; const t = coerce(v); if (Array.isArray(t)) return t; if (typeof t !== 'string' || t === '') return []; return t.includes(',') ? t.split(',').map((s) => s.trim()).filter(Boolean) : [t]; } // .md хранит путь от корня сайта (/Work_files/...), страница живёт в src/ → добавляем ../ function sitePath(p) { const s = String(p == null ? '' : p).trim(); return s.replace(/^\/(?=Work_files)/, '../'); } function slugToName(slug) { return slug .split(/[-_]/) .map((w) => (w ? w.charAt(0).toUpperCase() + w.slice(1) : w)) .join(' '); } function loadProjects() { if (!existsSync(PROJ_DIR)) return []; // Порядок показа = порядок объектов на арте планеты (§10.11 / D18): грузовик World Wide // Wheels → жёлтый герой Moba → зелёная фишка BattleCaps → корабль TITANS (aquatherium). // Выпущенные игры (bukvika, associations) — явным хвостом после арт-четвёрки. Не алфавит // readdirSync: карточки в #work и плашка на планете должны идти в одном порядке. const ART_ORDER = ['ww-wheels', 'moba', 'battlecaps', 'aquatherium', 'bukvika', 'associations']; const out = []; for (const f of readdirSync(PROJ_DIR).filter((x) => x.endsWith('.md') && !x.startsWith('_'))) { const { meta, body } = parseFrontmatter(join(PROJ_DIR, f)); const slug = meta.slug || basename(f, '.md'); const p = { slug, title: meta.title || slugToName(slug), status: meta.status || '', badge: meta.badge || '', platforms: toList(meta.platforms), stack: toList(meta.stack), link: meta.link || '', play: meta.play || '', video: meta.video || '', images: toList(meta.images).map(sitePath), metrics: (meta.metrics && typeof meta.metrics === 'object') ? meta.metrics : '', summary: coerce(meta.summary), detail: body, }; out.push(p); } const rank = new Map(ART_ORDER.map((s, i) => [s, i])); return out.sort((a, b) => (rank.get(a.slug) ?? ART_ORDER.length) - (rank.get(b.slug) ?? ART_ORDER.length)); } function loadTeam() { if (!existsSync(TEAM_DIR)) return []; const roster = [ { slug: 'timur', name: 'Тимур', role: 'Frontend · стратегия разработки' }, { slug: 'maria', name: 'Мария', role: 'Product Manager' }, { slug: 'den', name: 'Ден', role: '3D · Animation · Visualization' }, { slug: 'kolya', name: 'Коля', role: 'Backend · network setup' }, { slug: 'sergey', name: 'Сергей', role: 'Strategy · analytics · planning' }, ]; const out = []; for (const f of readdirSync(TEAM_DIR).filter((x) => x.endsWith('.md') && !x.startsWith('_'))) { const { meta, body } = parseFrontmatter(join(TEAM_DIR, f)); const slug = meta.slug || basename(f, '.md'); // merge with fallback roster so names/roles survive a placeholder .md const fallback = roster.find((r) => r.slug === slug) || { slug, name: slugToName(slug), role: '' }; out.push({ slug, name: meta.name || fallback.name, role: meta.role || fallback.role, photo: sitePath(meta.photo), bio: meta.bio || body, initials: (meta.name || fallback.name).split(/\s+/).map((w) => w[0]).join('').slice(0, 2).toUpperCase(), }); } // client-approved order: roster index, not readdirSync alphabet const rank = new Map(roster.map((r, i) => [r.slug, i])); return out.sort((a, b) => (rank.get(a.slug) ?? roster.length) - (rank.get(b.slug) ?? roster.length)); } function writeJs(path, varname, data) { mkdirSync(dirname(path), { recursive: true }); const json = JSON.stringify(data, null, 2); writeFileSync(path, `// AUTO-GENERATED from content/ — do not edit. Run: node scripts/generate-content.mjs\nwindow.${varname} = ${json};\n`); console.log(`wrote ${path} (${data.length} item(s))`); } writeJs(join(OUT, 'projects.js'), 'HMT_PROJECTS', loadProjects()); writeJs(join(OUT, 'team.js'), 'HMT_TEAM', loadTeam()); console.log('done.');