Этап 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
+257 -2
View File
@@ -1,2 +1,257 @@
// Импорт стартового контента. Реализация появится на этапе 2.
console.log('seed: пока пусто');
// pnpm seed: импорт стартового контента из kb-seed/.
// Скрипт идемпотентный: повторный запуск обновляет записи, а не создаёт дубликаты.
//
// Что делает:
// 1. пространство «АСУПП» и разделы по папкам content/NN-slug
// 2. картинки kb-seed/assets → uploads/assets (WebP 1600 + превью 480, без EXIF)
// 3. исходники kb-seed/originals → uploads/originals
// 4. статьи из content/**/*.md (+ Attachment по полю source)
// 5. администратор из ADMIN_EMAIL / ADMIN_PASSWORD
// 6. отчёт: битые [[ссылки]], потерянные картинки и исходники
import fs from 'node:fs/promises';
import path from 'node:path';
import { assetKey, parseFrontMatter } from '@kb/md';
import type { PlaqueColor } from '@kb/shared';
import { prisma } from './db.js';
import { env } from './env.js';
import { rerenderAll } from './services/articles.js';
import { fileSize, storeImage, uploadPath } from './services/images.js';
import { hashPassword } from './services/password.js';
// Код и цвет плашки раздела: как в макете. Для новых папок код берётся из первых букв названия.
const SECTION_STYLE: Record<string, { code: string; color: PlaqueColor }> = {
shpargalka: { code: 'ШП', color: 'yellow' },
'stoyka-vezda': { code: 'ВВ', color: 'yellow' },
'stoyka-shlagbauma': { code: 'ШЛ', color: 'orange' },
'optika-vok': { code: 'ВОК', color: 'blue' },
ostrov: { code: 'ОБ', color: 'green' },
'naves-terminala': { code: 'НТ', color: 'ink' },
};
const IMAGE_EXT = /\.(jpe?g|png|webp|gif|tiff?)$/i;
async function walk(dir: string): Promise<string[]> {
const out: string[] = [];
let entries;
try {
entries = await fs.readdir(dir, { withFileTypes: true });
} catch {
return out;
}
for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
const p = path.join(dir, e.name);
if (e.isDirectory()) out.push(...(await walk(p)));
else out.push(p);
}
return out;
}
const toPosix = (p: string) => p.split(path.sep).join('/');
function fallbackCode(name: string): string {
return name
.split(/[\s/()-]+/)
.filter(Boolean)
.slice(0, 2)
.map((w) => w[0]!.toUpperCase())
.join('');
}
async function importImages(seedDir: string) {
const dir = path.join(seedDir, 'assets');
const files = (await walk(dir)).filter((f) => IMAGE_EXT.test(f));
let converted = 0;
for (const file of files) {
const key = assetKey(`assets/${toPosix(path.relative(dir, file))}`)!;
const rel = `${key}.webp`;
const srcStat = await fs.stat(file);
const existing = await prisma.asset.findUnique({ where: { path: rel } });
const outStat = await fs.stat(uploadPath(rel)).catch(() => null);
// Пропускаем, если уже сконвертировано и исходник с тех пор не менялся
if (existing && outStat && outStat.mtimeMs >= srcStat.mtimeMs) continue;
const img = await storeImage(await fs.readFile(file), key);
const data = { mime: 'image/webp', size: img.size, width: img.width, height: img.height };
await prisma.asset.upsert({ where: { path: rel }, create: { path: rel, ...data }, update: data });
converted++;
}
return { total: files.length, converted };
}
async function importOriginals(seedDir: string) {
const dir = path.join(seedDir, 'originals');
const files = await walk(dir);
for (const file of files) {
const dest = uploadPath(`originals/${toPosix(path.relative(dir, file))}`);
await fs.mkdir(path.dirname(dest), { recursive: true });
await fs.copyFile(file, dest);
}
return files.length;
}
async function main() {
const seedDir = path.resolve(env.SEED_DIR);
const contentDir = path.join(seedDir, 'content');
console.log(`Импорт из ${seedDir}`);
await fs.access(contentDir).catch(() => {
throw new Error(`Не найдена папка ${contentDir}. Проверьте SEED_DIR.`);
});
await fs.mkdir(env.UPLOADS_DIR, { recursive: true });
// 1. Пространство
const space = await prisma.space.upsert({
where: { slug: 'asupp' },
create: { slug: 'asupp', name: 'АСУПП', icon: 'А', order: 0 },
update: {},
});
// 2–3. Файлы
const images = await importImages(seedDir);
const originals = await importOriginals(seedDir);
// 4. Статьи
const admin = await ensureAdmin();
const problems: string[] = [];
const mdFiles = (await walk(contentDir)).filter((f) => f.endsWith('.md'));
let created = 0;
let updated = 0;
for (const file of mdFiles) {
const relFile = toPosix(path.relative(contentDir, file));
const { meta, body } = parseFrontMatter(await fs.readFile(file, 'utf8'));
if (!meta.slug || !meta.title) {
problems.push(`${relFile}: нет slug или title в шапке, статья пропущена`);
continue;
}
// Раздел по папке: «01-stoyka-vezda» → порядок 1, slug stoyka-vezda
const folder = relFile.split('/')[0] ?? '';
const fm = folder.match(/^(\d+)-(.+)$/);
const sectionSlug = fm?.[2] ?? folder;
const sectionName = meta.section ?? sectionSlug;
const style = SECTION_STYLE[sectionSlug] ?? { code: fallbackCode(sectionName), color: 'ink' as PlaqueColor };
const section = await prisma.section.upsert({
where: { slug: sectionSlug },
create: { slug: sectionSlug, spaceId: space.id, name: sectionName, order: Number(fm?.[1] ?? 0), ...style },
// При повторном запуске не затираем то, что админ поменял руками (название, порядок, цвет)
update: {},
});
const bodyMd = body.trim() + '\n';
const data = {
sectionId: section.id,
title: meta.title,
summary: meta.summary ?? '',
tags: meta.tags,
equipment: meta.equipment,
docCode: meta.doc_code ?? null,
pinned: meta.pinned,
order: meta.order ?? 0,
};
const existing = await prisma.article.findUnique({ where: { slug: meta.slug } });
let articleId: string;
if (!existing) {
const art = await prisma.article.create({
data: { ...data, slug: meta.slug, bodyMd, bodyHtml: '', status: 'PUBLISHED', authorId: admin?.id ?? null },
});
await prisma.articleRevision.create({
data: { articleId: art.id, version: 1, title: art.title, bodyMd, authorId: admin?.id ?? null, comment: 'Импорт из kb-seed' },
});
articleId = art.id;
created++;
} else {
const changed = existing.bodyMd !== bodyMd;
const version = changed ? existing.version + 1 : existing.version;
await prisma.article.update({
where: { id: existing.id },
data: { ...data, bodyMd, version, ...(changed ? { updatedAt: new Date() } : {}) },
});
if (changed) {
await prisma.articleRevision.create({
data: { articleId: existing.id, version, title: meta.title, bodyMd, authorId: admin?.id ?? null, comment: 'Обновление из kb-seed' },
});
updated++;
}
articleId = existing.id;
}
// Исходники по полю source
for (const src of meta.source) {
const rel = src.replace(/^\.?\/+/, '');
const size = await fileSize(uploadPath(rel));
if (size === null) {
problems.push(`${meta.slug}: исходник не найден: ${src}`);
continue;
}
const att = { filename: path.posix.basename(rel), size };
await prisma.attachment.upsert({
where: { articleId_path: { articleId, path: rel } },
create: { articleId, path: rel, ...att },
update: att,
});
}
}
// HTML рисуем вторым проходом: к этому моменту известны названия всех статей для [[ссылок]]
const report = await rerenderAll();
for (const r of report) {
for (const slug of r.brokenLinks) problems.push(`${r.slug}: битая ссылка [[${slug}]]`);
}
// Картинки, на которые ссылается текст, но файла нет
const assetPaths = new Set((await prisma.asset.findMany({ select: { path: true } })).map((a) => a.path));
const articles = await prisma.article.findMany({ select: { slug: true, bodyMd: true } });
let imageRefs = 0;
for (const art of articles) {
for (const m of art.bodyMd.matchAll(/!\[[^\]]*\]\(([^)\s]+)/g)) {
const key = assetKey(m[1] ?? '');
if (!key) continue;
imageRefs++;
if (!assetPaths.has(`${key}.webp`)) problems.push(`${art.slug}: картинка не найдена: ${m[1]}`);
}
}
const counts = {
spaces: await prisma.space.count(),
sections: await prisma.section.count(),
articles: await prisma.article.count(),
assets: await prisma.asset.count(),
attachments: await prisma.attachment.count(),
};
console.log('\n===== Отчёт импорта =====');
console.log(`Статей в БД: ${counts.articles} (новых ${created}, обновлено ${updated})`);
console.log(`Разделов: ${counts.sections}, пространств: ${counts.spaces}`);
console.log(`Картинок: ${counts.assets} (в kb-seed ${images.total}, сконвертировано сейчас ${images.converted})`);
console.log(`Ссылок на картинки: ${imageRefs}`);
console.log(`Исходников: ${counts.attachments} привязано к статьям (файлов ${originals})`);
console.log(`[[Ссылок]]: ${report.reduce((n, r) => n + r.brokenLinks.length, 0)} битых`);
console.log(admin ? `Администратор: ${admin.email}` : 'Администратор: не создан (задайте ADMIN_EMAIL и ADMIN_PASSWORD в .env)');
if (problems.length) {
console.log(`\nПроблемы (${problems.length}):`);
for (const p of problems) console.log(` - ${p}`);
process.exitCode = 1;
} else {
console.log('\nПроблем нет: все картинки, исходники и ссылки на месте.');
}
}
async function ensureAdmin() {
if (!env.ADMIN_EMAIL || !env.ADMIN_PASSWORD) return prisma.user.findFirst({ where: { role: 'ADMIN' } });
const email = env.ADMIN_EMAIL.toLowerCase();
const existing = await prisma.user.findUnique({ where: { email } });
// Существующему админу пароль не перезаписываем: он мог его уже сменить
if (existing) return existing;
return prisma.user.create({
data: { email, name: env.ADMIN_NAME, role: 'ADMIN', passwordHash: await hashPassword(env.ADMIN_PASSWORD) },
});
}
main()
.catch((err) => {
console.error(err);
process.exitCode = 1;
})
.finally(() => prisma.$disconnect());
+99
View File
@@ -0,0 +1,99 @@
import { Prisma } from '@prisma/client';
import { assetKey, renderMarkdown, type RenderResult } from '@kb/md';
import { compactSearch, normalizeSearch } from '@kb/shared';
import { prisma } from '../db.js';
type Db = Prisma.TransactionClient | typeof prisma;
/** slug → название для подстановки в [[ссылки]]. */
export async function loadTitleMap(db: Db = prisma): Promise<Map<string, string>> {
const rows = await db.article.findMany({ select: { slug: true, title: true } });
return new Map(rows.map((r) => [r.slug, r.title]));
}
/** Размеры картинок по ключу (assets/shkon/fig-1), чтобы в HTML сразу стояли width/height. */
export async function loadImageSizes(md: string, db: Db = prisma) {
const keys = [...md.matchAll(/!\[[^\]]*\]\(([^)\s]+)/g)]
.map((m) => assetKey(m[1] ?? ''))
.filter((k): k is string => !!k);
if (!keys.length) return new Map<string, { width: number; height: number }>();
const rows = await db.asset.findMany({
where: { path: { in: keys.map((k) => `${k}.webp`) } },
select: { path: true, width: true, height: true },
});
return new Map(rows.map((r) => [r.path.replace(/\.webp$/, ''), { width: r.width, height: r.height }]));
}
export async function renderArticle(md: string, db: Db = prisma): Promise<RenderResult> {
const [titles, sizes] = await Promise.all([loadTitleMap(db), loadImageSizes(md, db)]);
return renderMarkdown(md, {
resolveLink: (slug) => titles.get(slug),
imageSize: (key) => sizes.get(key),
});
}
export interface IndexSource {
title: string;
summary: string;
tags: string[];
equipment: string[];
docCode: string | null;
render: RenderResult;
}
/**
* Обновляет поисковые поля статьи.
* Веса: A заголовок, B «Главное» и краткое описание, C теги/оборудование/шифр, D остальной текст.
*/
export async function updateSearchIndex(articleId: string, src: IndexSource, db: Db = prisma) {
const a = normalizeSearch(src.title);
const b = normalizeSearch(`${src.render.text.keyfacts}\n${src.summary}`);
const c = normalizeSearch([...src.tags, ...src.equipment, src.docCode ?? ''].join('\n'));
const d = normalizeSearch(src.render.text.body);
const all = [a, b, c, d].join('\n');
await db.$executeRaw`
UPDATE "Article" SET
"searchVector" =
setweight(to_tsvector('russian', ${a}), 'A') ||
setweight(to_tsvector('russian', ${b}), 'B') ||
setweight(to_tsvector('russian', ${c}), 'C') ||
setweight(to_tsvector('russian', ${d}), 'D'),
"searchNorm" = ${all},
"searchCompact" = ${compactSearch(all)}
WHERE id = ${articleId}`;
}
/** Привязывает картинки из текста к статье (поле Asset.articleId). */
export async function linkAssets(articleId: string, render: RenderResult, db: Db = prisma) {
const paths = render.figures.map((f) => assetKey(f.src)).filter((k): k is string => !!k).map((k) => `${k}.webp`);
await db.asset.updateMany({ where: { articleId, path: { notIn: paths } }, data: { articleId: null } });
if (paths.length) {
await db.asset.updateMany({ where: { path: { in: paths }, articleId: null }, data: { articleId } });
}
}
/**
* Перерисовывает HTML всех статей. Нужно, когда поменялось название статьи
* или появилась новая: в чужих [[ссылках]] должно стоять актуальное название.
*/
export async function rerenderAll(db: Db = prisma): Promise<{ slug: string; brokenLinks: string[] }[]> {
const titles = await loadTitleMap(db);
const articles = await db.article.findMany();
const report: { slug: string; brokenLinks: string[] }[] = [];
for (const art of articles) {
const sizes = await loadImageSizes(art.bodyMd, db);
const render = renderMarkdown(art.bodyMd, {
resolveLink: (slug) => titles.get(slug),
imageSize: (key) => sizes.get(key),
});
await db.article.update({
where: { id: art.id },
data: { bodyHtml: render.html, facts: render.facts as unknown as Prisma.InputJsonValue },
});
await updateSearchIndex(art.id, { ...art, render }, db);
await linkAssets(art.id, render, db);
report.push({ slug: art.slug, brokenLinks: render.brokenLinks });
}
return report;
}
+59
View File
@@ -0,0 +1,59 @@
import fs from 'node:fs/promises';
import path from 'node:path';
import sharp from 'sharp';
import { env } from '../env.js';
export const FULL_WIDTH = 1600;
export const THUMB_WIDTH = 480;
export interface StoredImage {
/** Путь относительно uploads: assets/shkon/fig-1.webp */
path: string;
width: number;
height: number;
size: number;
}
/** Полный путь файла в папке uploads с защитой от выхода за её пределы («../»). */
export function uploadPath(rel: string): string {
const root = path.resolve(env.UPLOADS_DIR);
const full = path.resolve(root, rel);
if (full !== root && !full.startsWith(root + path.sep)) throw new Error(`Недопустимый путь: ${rel}`);
return full;
}
/**
* Сохраняет картинку в двух размерах:
* <key>.webp до 1600 px по ширине (просмотр, зум)
* <key>.480.webp превью 480 px
* EXIF (в том числе координаты съёмки) удаляется: sharp не переносит метаданные,
* а rotate() перед этим применяет поворот из EXIF, чтобы фото не легло набок.
*/
export async function storeImage(input: Buffer, key: string): Promise<StoredImage> {
const fullRel = `${key}.webp`;
const thumbRel = `${key}.${THUMB_WIDTH}.webp`;
const fullAbs = uploadPath(fullRel);
await fs.mkdir(path.dirname(fullAbs), { recursive: true });
const base = sharp(input, { failOn: 'error' }).rotate();
const full = await base
.clone()
.resize({ width: FULL_WIDTH, withoutEnlargement: true })
.webp({ quality: 80 })
.toFile(fullAbs);
await base
.clone()
.resize({ width: THUMB_WIDTH, withoutEnlargement: true })
.webp({ quality: 72 })
.toFile(uploadPath(thumbRel));
return { path: fullRel, width: full.width, height: full.height, size: full.size };
}
export async function fileSize(abs: string): Promise<number | null> {
try {
return (await fs.stat(abs)).size;
} catch {
return null;
}
}
+12
View File
@@ -0,0 +1,12 @@
import argon2 from 'argon2';
// argon2id: рекомендованный сейчас алгоритм хеширования паролей.
export const hashPassword = (password: string) => argon2.hash(password, { type: argon2.argon2id });
export async function verifyPassword(hash: string, password: string): Promise<boolean> {
try {
return await argon2.verify(hash, password);
} catch {
return false;
}
}