Этап 2: общий Markdown-рендер и импорт стартового контента

- packages/md: unified + remark-gfm + remark-directive, свой плагин [[slug]],
  блоки keyfacts/danger/warning/tip/info, чек-листы, шаги, таблицы, фото,
  rehype-sanitize, разбор шпаргалки, терпимый разбор front matter, тесты
- pnpm seed: пространство, разделы, 12 статей, 58 картинок (sharp → WebP
  1600 + 480, без EXIF), исходники как Attachment, администратор, отчёт
- поисковые поля статьи (tsvector с весами, нормализованный и сжатый текст)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
deonisii
2026-10-04 12:15:21 +03:00
co-authored by Claude Opus 5.5
parent aa04c1f5db
commit 768daf7c5f
14 changed files with 1530 additions and 30 deletions
+99
View File
@@ -0,0 +1,99 @@
// Разбор шапки статьи (front matter).
//
// Почему не библиотека YAML: в наших статьях встречаются строки вида
// summary: Карта стойки: верх — оптика и коммутатор
// equipment: [уголок 130х130х100х1,8, FTP Cat5e]
// Строгий YAML на первой падает (двоеточие в значении), а вторую режет по запятой
// внутри «1,8». Поэтому разбираем сами по простым правилам:
// - ключ отделяется ПЕРВЫМ двоеточием;
// - список [a, b] делится по «запятая + пробел», запятая без пробела остаётся в значении.
export interface FrontMatter {
title?: string;
slug?: string;
section?: string;
order?: number;
tags: string[];
equipment: string[];
/** Пути к исходникам: originals/file.pdf */
source: string[];
doc_code?: string;
summary?: string;
pinned: boolean;
/** Остальные ключи как есть. */
extra: Record<string, string>;
}
function unquote(s: string): string {
const t = s.trim();
if (t.length >= 2 && ((t.startsWith('"') && t.endsWith('"')) || (t.startsWith("'") && t.endsWith("'")))) {
return t.slice(1, -1);
}
return t;
}
function parseList(raw: string): string[] {
const t = raw.trim();
if (!t) return [];
if (t.startsWith('[') && t.endsWith(']')) {
return t
.slice(1, -1)
.split(/,\s+/)
.map(unquote)
.filter(Boolean);
}
return [unquote(t)];
}
export function parseFrontMatter(src: string): { meta: FrontMatter; body: string } {
const meta: FrontMatter = { tags: [], equipment: [], source: [], pinned: false, extra: {} };
// Убираем BOM и приводим переводы строк к \n
const text = src.replace(/^/, '').replace(/\r\n?/g, '\n');
const m = text.match(/^---\n([\s\S]*?)\n---\n?/);
if (!m) return { meta, body: text };
const lines = (m[1] ?? '').split('\n');
for (let i = 0; i < lines.length; i++) {
const line = lines[i] ?? '';
const c = line.indexOf(':');
if (c < 1 || /^\s/.test(line) || line.startsWith('#')) continue;
const key = line.slice(0, c).trim();
let value = line.slice(c + 1).trim();
// Многострочный список:
// tags:
// - один
// - два
if (!value) {
const items: string[] = [];
while (i + 1 < lines.length && /^\s*-\s+/.test(lines[i + 1] ?? '')) {
items.push(unquote((lines[++i] ?? '').replace(/^\s*-\s+/, '')));
}
if (items.length) value = `[${items.join(', ')}]`;
}
switch (key) {
case 'title':
case 'slug':
case 'section':
case 'summary':
case 'doc_code':
meta[key] = unquote(value);
break;
case 'order':
meta.order = Number.parseInt(value, 10) || 0;
break;
case 'pinned':
meta.pinned = /^(true|yes|да|1)$/i.test(value);
break;
case 'tags':
case 'equipment':
case 'source':
meta[key] = parseList(value);
break;
default:
meta.extra[key] = unquote(value);
}
}
return { meta, body: text.slice(m[0].length) };
}