diff --git a/apps/api/src/seed.ts b/apps/api/src/seed.ts index 4690aad..f59e5fe 100644 --- a/apps/api/src/seed.ts +++ b/apps/api/src/seed.ts @@ -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 = { + 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 { + 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()); diff --git a/apps/api/src/services/articles.ts b/apps/api/src/services/articles.ts new file mode 100644 index 0000000..689b875 --- /dev/null +++ b/apps/api/src/services/articles.ts @@ -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> { + 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(); + 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 { + 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; +} diff --git a/apps/api/src/services/images.ts b/apps/api/src/services/images.ts new file mode 100644 index 0000000..2c64235 --- /dev/null +++ b/apps/api/src/services/images.ts @@ -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; +} + +/** + * Сохраняет картинку в двух размерах: + * .webp до 1600 px по ширине (просмотр, зум) + * .480.webp превью 480 px + * EXIF (в том числе координаты съёмки) удаляется: sharp не переносит метаданные, + * а rotate() перед этим применяет поворот из EXIF, чтобы фото не легло набок. + */ +export async function storeImage(input: Buffer, key: string): Promise { + 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 { + try { + return (await fs.stat(abs)).size; + } catch { + return null; + } +} diff --git a/apps/api/src/services/password.ts b/apps/api/src/services/password.ts new file mode 100644 index 0000000..48a4be3 --- /dev/null +++ b/apps/api/src/services/password.ts @@ -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 { + try { + return await argon2.verify(hash, password); + } catch { + return false; + } +} diff --git a/packages/md/package.json b/packages/md/package.json index d9d98e1..53be14e 100644 --- a/packages/md/package.json +++ b/packages/md/package.json @@ -13,13 +13,12 @@ "test": "vitest run" }, "dependencies": { - "hast-util-to-string": "^3.0.1", + "@kb/shared": "workspace:^", "rehype-sanitize": "^6.0.0", "rehype-stringify": "^10.0.1", "remark-directive": "^4.0.0", "remark-gfm": "^4.0.1", "remark-parse": "^11.0.0", - "remark-rehype": "^11.1.2", "unified": "^11.0.5", "unist-util-visit": "^5.1.0" }, diff --git a/packages/md/src/assets.ts b/packages/md/src/assets.ts new file mode 100644 index 0000000..a405e05 --- /dev/null +++ b/packages/md/src/assets.ts @@ -0,0 +1,31 @@ +// Правило адресов картинок. Одно и то же на сервере и на клиенте. +// +// В Markdown автор пишет путь как есть: ![Рис. 1](assets/shkon/fig-1.jpg) +// При загрузке сервер делает из картинки два WebP-файла: +// /uploads/assets/shkon/fig-1.webp (до 1600 px, для просмотра и зума) +// /uploads/assets/shkon/fig-1.480.webp (превью 480 px, для сетки и списка) + +export interface AssetUrls { + full: string; + thumb: string; + /** Имя файла для подписи-заглушки, если картинка не загрузилась. */ + file: string; + /** Ключ картинки в папке uploads без расширения: assets/shkon/fig-1 */ + key: string | null; +} + +export function assetKey(src: string): string | null { + if (/^[a-z][a-z0-9+.-]*:/i.test(src) || src.startsWith('//')) return null; // внешний адрес + const clean = src + .split(/[?#]/)[0]! + .replace(/^\.?\/+/, '') + .replace(/^uploads\//, ''); + return clean.replace(/(\.480)?\.[a-z0-9]+$/i, ''); +} + +export function assetUrls(src: string): AssetUrls { + const file = src.split(/[?#]/)[0]!.split('/').pop() ?? src; + const key = assetKey(src); + if (key === null) return { full: src, thumb: src, file, key }; + return { full: `/uploads/${key}.webp`, thumb: `/uploads/${key}.480.webp`, file, key }; +} diff --git a/packages/md/src/cheatsheet.ts b/packages/md/src/cheatsheet.ts new file mode 100644 index 0000000..0f344b8 --- /dev/null +++ b/packages/md/src/cheatsheet.ts @@ -0,0 +1,123 @@ +// Разбор статьи-шпаргалки на структурные части для экрана «Шпаргалка»: +// запреты, цифры, цвета, «всегда». Разделы узнаём по словам в заголовках H2, +// эмодзи в заголовках не обязательны. +// +// Ничего не выдумываем: если раздела в статье нет, список будет пустым, +// а если структура совсем другая, экран покажет статью обычным рендером. + +import { type MdNode, parseMarkdown, plainText } from './parse.js'; + +export interface Seg { + t: string; + bold?: boolean; +} + +export interface CheatLine { + /** Текст с выделением жирного. */ + segs: Seg[]; + /** Значение (для «Цифр»): «20 см». */ + value?: string; + /** Статьи-источники: slug из [[...]]. */ + links: string[]; +} + +export interface CheatColor { + /** «RAL 5017» */ + code: string; + /** «Уголок фотоэлемента» */ + label: string; +} + +export interface CheatSheet { + bans: CheatLine[]; + facts: CheatLine[]; + colors: CheatColor[]; + always: CheatLine[]; + /** true, если нашёлся хотя бы один из разделов. */ + ok: boolean; +} + +function segsOf(nodes: MdNode[]): { segs: Seg[]; links: string[] } { + const segs: Seg[] = []; + const links: string[] = []; + for (const n of nodes) { + if (n.type === 'wikiLink') { + if (n.slug) links.push(n.slug); + } else if (n.type === 'strong') { + segs.push({ t: plainText(n), bold: true }); + } else { + segs.push({ t: plainText(n) }); + } + } + // Убираем хвост из стрелок и разделителей перед ссылками: «… шинки → » и « · » + for (let i = segs.length - 1; i >= 0; i--) { + const s = segs[i]!; + if (s.bold) break; + s.t = s.t.replace(/[\s→·]+$/u, ''); + if (s.t) break; + segs.pop(); + } + if (segs[0] && !segs[0].bold) segs[0].t = segs[0].t.replace(/^[\s·]+/u, ''); + return { segs: segs.filter((s) => s.t), links }; +} + +const itemNodes = (li: MdNode): MdNode[] => (li.children ?? []).flatMap((p) => p.children ?? []); + +export function parseCheatSheet(md: string): CheatSheet { + const tree = parseMarkdown(md); + const sheet: CheatSheet = { bans: [], facts: [], colors: [], always: [], ok: false }; + let part: 'bans' | 'facts' | 'colors' | 'always' | null = null; + + for (const node of tree.children ?? []) { + if (node.type === 'heading') { + const t = plainText(node).toLowerCase(); + part = /запрещ|запрет/.test(t) + ? 'bans' + : /цифр/.test(t) + ? 'facts' + : /цвет/.test(t) + ? 'colors' + : /всегда/.test(t) + ? 'always' + : null; + continue; + } + if (!part) continue; + + if (node.type === 'list') { + for (const li of node.children ?? []) { + const line = segsOf(itemNodes(li)); + if (part === 'colors') { + // «Уголок фотоэлемента: **RAL 5017**» + const code = line.segs.find((s) => s.bold)?.t ?? ''; + const label = line.segs + .filter((s) => !s.bold) + .map((s) => s.t) + .join(' ') + .replace(/[:\s]+$/u, '') + .trim(); + if (code) sheet.colors.push({ code, label }); + } else if (part === 'facts') { + sheet.facts.push(line); + } else { + sheet[part].push(line); + } + } + } else if (node.type === 'table' && part === 'facts') { + // Таблица «Что | Значение | Где» + for (const row of (node.children ?? []).slice(1)) { + const cells = row.children ?? []; + const what = segsOf(cells[0]?.children ?? []); + const where = segsOf(cells.slice(2).flatMap((c) => c.children ?? [])); + sheet.facts.push({ + segs: what.segs, + value: plainText(cells[1] ?? { type: 'text', value: '' }).trim(), + links: [...what.links, ...where.links], + }); + } + } + } + + sheet.ok = sheet.bans.length + sheet.facts.length + sheet.always.length > 0; + return sheet; +} diff --git a/packages/md/src/frontmatter.ts b/packages/md/src/frontmatter.ts new file mode 100644 index 0000000..839c6e3 --- /dev/null +++ b/packages/md/src/frontmatter.ts @@ -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; +} + +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) }; +} diff --git a/packages/md/src/hast.ts b/packages/md/src/hast.ts new file mode 100644 index 0000000..f296e5c --- /dev/null +++ b/packages/md/src/hast.ts @@ -0,0 +1,464 @@ +// Markdown-дерево (mdast) → HTML-дерево (hast) с нашими блоками. +// +// Разметка повторяет макет new_design/ArticleBodyXL.dc.html, только вместо инлайн-стилей +// стоят классы kb-*; сами стили лежат в apps/web/src/styles/article.css. +// Интерактив (галочки чек-листа, открытие фото) навешивает клиент по data-атрибутам, +// поэтому один и тот же HTML годится и для сервера, и для предпросмотра в редакторе. + +import { plural } from '@kb/shared'; +import { assetUrls } from './assets.js'; +import { type MdNode, plainText } from './parse.js'; + +export interface HNode { + type: 'element' | 'text' | 'root'; + tagName?: string; + properties?: Record; + children?: HNode[]; + value?: string; +} + +export interface TocItem { + id: string; + text: string; +} + +export interface FigureInfo { + src: string; + full: string; + thumb: string; + caption: string; + file: string; +} + +export interface RenderOptions { + /** Название статьи по slug. Вернёт undefined: ссылка битая. */ + resolveLink?: (slug: string) => string | undefined; + /** Размеры картинки по ключу (assets/shkon/fig-1): чтобы страница не прыгала при загрузке. */ + imageSize?: (key: string) => { width: number; height: number } | undefined; +} + +export interface RenderContext { + opts: RenderOptions; + toc: TocItem[]; + figures: FigureInfo[]; + links: string[]; + brokenLinks: string[]; + checkGroups: number; +} + +type Props = HNode['properties']; +const h = (tagName: string, properties: Props, ...children: (HNode | string | null | undefined)[]): HNode => ({ + type: 'element', + tagName, + properties: properties ?? {}, + children: children + .filter((c): c is HNode | string => c !== null && c !== undefined) + .map((c) => (typeof c === 'string' ? { type: 'text', value: c } : c)), +}); +const text = (value: string): HNode => ({ type: 'text', value }); + +// «flat»: внутри кнопок и плашек ссылка-чип не нужна (в кнопке не может быть ссылки), +// там она рисуется подчёркнутым текстом, как в макете. +type InlineMode = 'chip' | 'flat'; + +function inline(nodes: MdNode[] | undefined, ctx: RenderContext, mode: InlineMode): HNode[] { + const out: HNode[] = []; + for (const n of nodes ?? []) { + switch (n.type) { + case 'text': + out.push(text(n.value ?? '')); + break; + case 'strong': + out.push(h('strong', { className: ['kb-b'] }, ...inline(n.children, ctx, mode))); + break; + case 'emphasis': + out.push(h('em', {}, ...inline(n.children, ctx, mode))); + break; + case 'delete': + out.push(h('del', {}, ...inline(n.children, ctx, mode))); + break; + case 'inlineCode': + out.push(h('code', { className: ['kb-code'] }, n.value ?? '')); + break; + case 'break': + out.push(h('br', {})); + break; + case 'link': + out.push( + mode === 'flat' + ? h('span', { className: ['kb-ulink'] }, ...inline(n.children, ctx, mode)) + : h( + 'a', + { className: ['kb-a'], href: n.url ?? '', target: '_blank', rel: ['noopener', 'noreferrer'] }, + ...inline(n.children, ctx, mode), + ), + ); + break; + case 'wikiLink': { + const slug = n.slug ?? ''; + const title = ctx.opts.resolveLink?.(slug); + ctx.links.push(slug); + if (title === undefined && ctx.opts.resolveLink) ctx.brokenLinks.push(slug); + const broken = title === undefined && !!ctx.opts.resolveLink; + if (mode === 'flat') { + out.push( + h( + 'span', + { className: broken ? ['kb-ulink', 'kb-link--broken'] : ['kb-ulink'], dataSlug: slug }, + title ?? slug, + ), + ); + } else { + out.push( + h( + 'a', + { + className: broken ? ['kb-link', 'kb-link--broken'] : ['kb-link'], + href: `/a/${slug}`, + dataSlug: slug, + }, + h('span', { className: ['kb-link-arrow'], ariaHidden: 'true' }, '→'), + h('span', { className: ['kb-link-t'] }, title ?? slug), + ), + ); + } + break; + } + case 'image': + // Картинка посреди текста: показываем подпись, сам рисунок выносится в блок фото + out.push(text(n.alt ?? '')); + break; + case 'textDirective': + // remark-directive принимает «:слово» за директиву. Возвращаем текст как был. + out.push(text(`:${n.name ?? ''}`), ...inline(n.children, ctx, mode)); + break; + case 'html': + // Сырой HTML из Markdown не пропускаем вообще + break; + default: + if (n.children) out.push(...inline(n.children, ctx, mode)); + else if (n.value) out.push(text(n.value)); + } + } + return out; +} + +/** Абзац состоит только из картинок (и переводов строк между ними)? */ +function onlyImages(p: MdNode): MdNode[] | null { + const imgs: MdNode[] = []; + for (const c of p.children ?? []) { + if (c.type === 'image') imgs.push(c); + else if (c.type === 'break' || (c.type === 'text' && !(c.value ?? '').trim())) continue; + else return null; + } + return imgs.length ? imgs : null; +} + +function figure(img: MdNode, first: boolean, ctx: RenderContext): HNode { + const src = img.url ?? ''; + const urls = assetUrls(src); + const caption = img.alt ?? ''; + const idx = ctx.figures.length; + ctx.figures.push({ src, full: urls.full, thumb: urls.thumb, caption, file: urls.file }); + const size = urls.key ? ctx.opts.imageSize?.(urls.key) : undefined; + + const imgProps: Props = { + className: ['kb-fig-img'], + alt: caption, + loading: 'lazy', + decoding: 'async', + dataFile: urls.file, + }; + if (first) { + // Первое фото во всю ширину: телефон берёт превью 480, большой экран 1600 + imgProps.src = urls.full; + if (urls.key) { + imgProps.srcSet = `${urls.thumb} 480w, ${urls.full} 1600w`; + imgProps.sizes = '(max-width: 760px) 100vw, 720px'; + } + if (size) { + imgProps.width = size.width; + imgProps.height = size.height; + } + } else { + imgProps.src = urls.thumb; + imgProps.width = 480; + imgProps.height = 480; + } + + return h( + 'figure', + { className: first ? ['kb-fig', 'kb-fig--first'] : ['kb-fig'] }, + h( + 'button', + { type: 'button', className: ['kb-fig-btn'], dataFig: idx, ariaLabel: `Увеличить: ${caption}` }, + h('img', imgProps), + first ? h('span', { className: ['kb-fig-zoom'], ariaHidden: 'true' }, 'Увеличить') : null, + ), + h('figcaption', { className: ['kb-fig-cap'] }, caption), + ); +} + +function figures(imgs: MdNode[], ctx: RenderContext): HNode { + const [first, ...rest] = imgs; + return h( + 'div', + { className: ['kb-figs'] }, + first ? figure(first, true, ctx) : null, + rest.length ? h('div', { className: ['kb-figs-grid'] }, ...rest.map((i) => figure(i, false, ctx))) : null, + ); +} + +/** Содержимое пункта списка как инлайн (у пункта внутри лежит абзац). */ +function itemInline(item: MdNode): MdNode[] { + const out: MdNode[] = []; + for (const c of item.children ?? []) { + if (c.type === 'paragraph') { + if (out.length) out.push({ type: 'text', value: ' ' }); + out.push(...(c.children ?? [])); + } + } + return out; +} + +/** Строки внутри :::блока: каждый абзац и каждый пункт списка становится отдельной строкой. */ +function directiveLines(node: MdNode): MdNode[][] { + const lines: MdNode[][] = []; + for (const c of node.children ?? []) { + if (c.type === 'paragraph') lines.push(c.children ?? []); + else if (c.type === 'list') for (const li of c.children ?? []) lines.push(itemInline(li)); + else lines.push([{ type: 'text', value: plainText(c) }]); + } + return lines; +} + +/** «Подпись: значение» → подпись отдельно. Двоеточие ищем в начале строки (до 44 знаков). */ +export function splitLabel(nodes: MdNode[]): { label: string; rest: MdNode[] } { + const first = nodes[0]; + if (first?.type === 'text' && first.value) { + const c = first.value.indexOf(':'); + if (c > -1 && c < 44) { + const tail = first.value.slice(c + 1).replace(/^\s+/, ''); + const rest = tail ? [{ type: 'text', value: tail }, ...nodes.slice(1)] : nodes.slice(1); + return { label: first.value.slice(0, c).trim(), rest }; + } + } + return { label: '', rest: nodes }; +} + +function keyfacts(node: MdNode, ctx: RenderContext): HNode { + const items = directiveLines(node).map((line) => { + const { label, rest } = splitLabel(line); + const len = rest.map(plainText).join('').length; + // Длинное значение занимает всю ширину, короткое встаёт плиткой в две колонки + const wide = len > 24; + const segs = rest.map((n) => + n.type === 'strong' + ? h('span', { className: ['kb-key-v'] }, ...inline(n.children, ctx, 'flat')) + : h('span', { className: ['kb-key-t'] }, ...inline([n], ctx, 'flat')), + ); + return h( + 'div', + { className: wide ? ['kb-key-item', 'kb-key-item--wide'] : ['kb-key-item'] }, + label ? h('div', { className: ['kb-key-label'] }, label) : null, + h('div', { className: ['kb-key-val'] }, ...segs), + ); + }); + const n = items.length; + return h( + 'section', + { className: ['kb-key'] }, + h('div', { className: ['kb-hazard'], ariaHidden: 'true' }), + h( + 'div', + { className: ['kb-key-head'] }, + h('div', { className: ['kb-key-title'] }, 'Главное'), + h('div', { className: ['kb-key-count'] }, `${n} ${plural(n, ['пункт', 'пункта', 'пунктов'])}`), + ), + h('div', { className: ['kb-key-grid'] }, ...items), + ); +} + +const CALLOUTS: Record = { + danger: 'ЗАПРЕЩЕНО', + warning: 'ВНИМАНИЕ', + tip: 'СОВЕТ', + info: 'СПРАВКА', +}; + +function callout(kind: string, node: MdNode, ctx: RenderContext): HNode { + const paras = directiveLines(node).map((line) => h('p', {}, ...inline(line, ctx, 'flat'))); + const props: Props = { className: ['kb-callout', `kb-${kind}`] }; + if (kind === 'danger') props.role = 'alert'; + return h( + 'section', + props, + h( + 'div', + { className: ['kb-callout-head'] }, + h('span', { className: ['kb-callout-icon'], ariaHidden: 'true' }), + CALLOUTS[kind] ?? kind, + ), + h('div', { className: ['kb-callout-body'] }, ...paras), + ); +} + +function checklist(list: MdNode, ctx: RenderContext): HNode { + const gid = ctx.checkGroups++; + const items = list.children ?? []; + return h( + 'section', + { className: ['kb-check'], dataCheck: gid }, + h( + 'div', + { className: ['kb-check-head'] }, + h('div', { className: ['kb-check-title'] }, 'Чек-лист'), + h('div', { className: ['kb-check-count'] }, `0 из ${items.length}`), + h('button', { type: 'button', className: ['kb-check-reset'] }, 'Сбросить'), + ), + h('div', { className: ['kb-check-bar'] }, h('div', { className: ['kb-check-fill'] })), + ...items.map((it, i) => + h( + 'button', + { type: 'button', className: ['kb-check-row'], dataI: i, ariaPressed: 'false' }, + h('span', { className: ['kb-box'], ariaHidden: 'true' }), + h('span', { className: ['kb-check-text'] }, ...inline(itemInline(it), ctx, 'flat')), + ), + ), + ); +} + +function steps(list: MdNode, ctx: RenderContext): HNode { + const start = list.start ?? 1; + return h( + 'ol', + { className: ['kb-steps'] }, + ...(list.children ?? []).map((it, i) => { + let nodes = itemInline(it); + let title: HNode | null = null; + // «1. **Заголовок.** текст»: жирное начало становится заголовком шага + if (nodes[0]?.type === 'strong') { + title = h('div', { className: ['kb-step-title'] }, ...inline(nodes[0].children, ctx, 'flat')); + nodes = nodes.slice(1); + if (nodes[0]?.type === 'text') nodes[0] = { type: 'text', value: (nodes[0].value ?? '').replace(/^\s+/, '') }; + } + const body = inline(nodes, ctx, 'flat'); + return h( + 'li', + { className: ['kb-step'] }, + h('span', { className: ['kb-step-n'] }, String(start + i)), + h('div', { className: ['kb-step-main'] }, title, body.length ? h('div', {}, ...body) : null), + ); + }), + ); +} + +function table(node: MdNode, ctx: RenderContext): HNode { + const rows = (node.children ?? []).map((r) => r.children ?? []); + const head = rows[0] ?? []; + const body = rows.slice(1); + const cell = (c: MdNode | undefined, mode: InlineMode = 'chip') => inline(c?.children, ctx, mode); + + // Две колонки: «что → значение», значение крупно справа + if (head.length === 2) { + return h( + 'div', + { className: ['kb-kv'], role: 'table' }, + h( + 'div', + { className: ['kb-kv-head'], role: 'row' }, + h('span', { role: 'columnheader' }, ...cell(head[0], 'flat')), + h('span', { role: 'columnheader' }, ...cell(head[1], 'flat')), + ), + ...body.map((r) => + h( + 'div', + { className: ['kb-kv-row'], role: 'row' }, + h('span', { className: ['kb-kv-k'], role: 'cell' }, ...cell(r[0], 'flat')), + h('span', { className: ['kb-kv-v'], role: 'cell' }, ...cell(r[1], 'flat')), + ), + ), + ); + } + + // Три колонки и больше: каждая строка становится карточкой, первая ячейка: заголовок + return h( + 'div', + { className: ['kb-cards'] }, + ...body.map((r) => + h( + 'div', + { className: ['kb-card'] }, + h('div', { className: ['kb-card-title'] }, ...cell(r[0])), + ...r.slice(1).map((c, j) => + h( + 'div', + { className: ['kb-card-row'] }, + h('span', { className: ['kb-card-label'] }, plainText(head[j + 1] ?? { type: 'text', value: '' })), + h('span', { className: ['kb-card-val'] }, ...cell(c)), + ), + ), + ), + ), + ); +} + +function block(node: MdNode, ctx: RenderContext): HNode | null { + switch (node.type) { + case 'heading': { + const t = plainText(node).trim(); + if ((node.depth ?? 2) <= 2) { + const id = `h-${ctx.toc.length}`; + ctx.toc.push({ id, text: t }); + return h('h2', { className: ['kb-h2'], id }, ...inline(node.children, ctx, 'flat')); + } + return h('h3', { className: ['kb-h3'] }, ...inline(node.children, ctx, 'flat')); + } + case 'paragraph': { + const imgs = onlyImages(node); + if (imgs) return figures(imgs, ctx); + return h('p', { className: ['kb-p'] }, ...inline(node.children, ctx, 'chip')); + } + case 'containerDirective': { + const name = node.name ?? ''; + if (name === 'keyfacts') return keyfacts(node, ctx); + if (name in CALLOUTS) return callout(name, node, ctx); + // Неизвестный блок показываем как справку, чтобы текст не пропал + return callout('info', node, ctx); + } + case 'list': { + const items = node.children ?? []; + if (items.length && items.every((i) => typeof i.checked === 'boolean')) return checklist(node, ctx); + if (node.ordered) return steps(node, ctx); + return h( + 'ul', + { className: ['kb-ul'] }, + ...items.map((it) => h('li', {}, h('span', {}, ...inline(itemInline(it), ctx, 'chip')))), + ); + } + case 'table': + return table(node, ctx); + case 'blockquote': + return h('blockquote', { className: ['kb-quote'] }, ...blocks(node.children ?? [], ctx)); + case 'code': + return h('pre', { className: ['kb-pre'] }, h('code', {}, node.value ?? '')); + case 'thematicBreak': + return h('hr', { className: ['kb-hr'] }); + case 'leafDirective': + return h('p', { className: ['kb-p'] }, `::${node.name ?? ''}`, ...inline(node.children, ctx, 'chip')); + case 'html': + case 'definition': + case 'footnoteDefinition': + return null; + default: + return node.children ? h('div', {}, ...blocks(node.children, ctx)) : null; + } +} + +function blocks(nodes: MdNode[], ctx: RenderContext): HNode[] { + return nodes.map((n) => block(n, ctx)).filter((n): n is HNode => n !== null); +} + +export function toHast(tree: MdNode, ctx: RenderContext): HNode { + return { type: 'root', children: blocks(tree.children ?? [], ctx) }; +} diff --git a/packages/md/src/index.ts b/packages/md/src/index.ts index a8abf0d..033ccf2 100644 --- a/packages/md/src/index.ts +++ b/packages/md/src/index.ts @@ -1,2 +1,137 @@ -// Общий Markdown-рендер (сервер + клиент). Наполняется на этапе 2. -export const MD_PACKAGE = '@kb/md'; +// @kb/md: единственное место, где Markdown статьи превращается в HTML. +// Используется сервером (bodyHtml при сохранении, текст для поиска) и клиентом +// (живой предпросмотр в редакторе), поэтому результат всегда одинаковый. + +import { unified } from 'unified'; +import rehypeSanitize, { defaultSchema } from 'rehype-sanitize'; +import rehypeStringify from 'rehype-stringify'; +import { type FigureInfo, type HNode, type RenderContext, type RenderOptions, type TocItem, splitLabel, toHast } from './hast.js'; +import { type MdNode, parseMarkdown, plainText } from './parse.js'; + +export { parseFrontMatter, type FrontMatter } from './frontmatter.js'; +export { assetUrls, assetKey, type AssetUrls } from './assets.js'; +export { parseCheatSheet, type CheatSheet, type CheatLine } from './cheatsheet.js'; +export { parseMarkdown, plainText, type MdNode } from './parse.js'; +export type { RenderOptions, TocItem, FigureInfo } from './hast.js'; + +// Белый список тегов и атрибутов. HTML мы строим сами, но на всякий случай прогоняем +// через санитайзер: он же отсекает опасные адреса вроде javascript: в ссылках. +const schema: typeof defaultSchema = { + ...defaultSchema, + clobber: [], // не добавлять префикс к id заголовков (h-0, h-1): они наши, а не от автора + strip: ['script', 'style'], + tagNames: [ + 'h2', 'h3', 'p', 'strong', 'em', 'del', 'code', 'br', 'a', 'span', 'div', 'section', + 'figure', 'figcaption', 'button', 'img', 'ul', 'ol', 'li', 'blockquote', 'pre', 'hr', + ], + attributes: { + '*': ['className', 'id', 'role', 'ariaHidden', 'ariaLabel', 'ariaPressed', 'data*'], + a: ['href', 'target', 'rel'], + img: ['src', 'srcSet', 'sizes', 'alt', 'loading', 'decoding', 'width', 'height'], + button: ['type'], + }, + protocols: { + href: ['http', 'https', 'mailto', 'tel'], + src: ['http', 'https'], + }, +}; + +const htmlProcessor = unified().use(rehypeSanitize, schema).use(rehypeStringify); + +export interface FactItem { + label: string; + /** Значение в Markdown: «только **порты 1 и 2** коммутатора». */ + value: string; +} + +export interface RenderResult { + html: string; + /** Заголовки H2 для оглавления. */ + toc: TocItem[]; + /** Все рисунки статьи по порядку (для просмотрщика и офлайн-кеша). */ + figures: FigureInfo[]; + /** Все [[slug]] из текста. */ + links: string[]; + /** [[slug]], для которых статья не нашлась. */ + brokenLinks: string[]; + /** Пункты блоков «Главное». */ + facts: FactItem[]; + /** Текст без разметки по частям: для поиска. */ + text: { keyfacts: string; body: string }; +} + +/** Собрать Markdown обратно из инлайн-узлов (нужен только жирный). */ +function inlineMd(nodes: MdNode[]): string { + return nodes + .map((n) => (n.type === 'strong' ? `**${plainText(n)}**` : plainText(n))) + .join('') + .trim(); +} + +function collectFacts(tree: MdNode): FactItem[] { + const facts: FactItem[] = []; + for (const node of tree.children ?? []) { + if (node.type !== 'containerDirective' || node.name !== 'keyfacts') continue; + for (const c of node.children ?? []) { + const lines = + c.type === 'list' + ? (c.children ?? []).map((li) => (li.children ?? []).flatMap((p) => p.children ?? [])) + : [c.children ?? []]; + for (const line of lines) { + const { label, rest } = splitLabel(line); + const value = inlineMd(rest); + if (value) facts.push({ label, value }); + } + } + } + return facts; +} + +/** + * Главная функция пакета: Markdown (без front matter) → HTML и всё, что из него извлекается. + */ +export function renderMarkdown(md: string, opts: RenderOptions = {}): RenderResult { + const tree = parseMarkdown(md); + const ctx: RenderContext = { opts, toc: [], figures: [], links: [], brokenLinks: [], checkGroups: 0 }; + const hast = toHast(tree, ctx); + // HNode совместим с типом Root из hast, но описан проще: приводим тип для unified + const clean = htmlProcessor.runSync(hast as unknown as Parameters[0]); + const html = htmlProcessor.stringify(clean as Parameters[0]) as string; + + const keyfacts: string[] = []; + const body: string[] = []; + for (const node of tree.children ?? []) { + const t = plainText(node).replace(/\s+/g, ' ').trim(); + if (!t) continue; + if (node.type === 'containerDirective' && node.name === 'keyfacts') keyfacts.push(blockText(node)); + else body.push(node.children && node.type !== 'paragraph' && node.type !== 'heading' ? blockText(node) : t); + } + + return { + html, + toc: ctx.toc, + figures: ctx.figures, + links: [...new Set(ctx.links)], + brokenLinks: [...new Set(ctx.brokenLinks)], + facts: collectFacts(tree), + text: { keyfacts: keyfacts.join('\n'), body: body.join('\n') }, + }; +} + +/** Текст блока, где пункты списка и ячейки таблицы разделены переводом строки (а не слиты в одно слово). */ +function blockText(node: MdNode): string { + const parts: string[] = []; + const walk = (n: MdNode) => { + if (n.type === 'paragraph' || n.type === 'heading' || n.type === 'tableCell') { + const t = plainText(n).replace(/\s+/g, ' ').trim(); + if (t) parts.push(t); + return; + } + if (n.children) n.children.forEach(walk); + else if (n.value?.trim()) parts.push(n.value.trim()); + }; + walk(node); + return parts.join('\n'); +} + +export type { HNode }; diff --git a/packages/md/src/md.test.ts b/packages/md/src/md.test.ts new file mode 100644 index 0000000..d8cd3b5 --- /dev/null +++ b/packages/md/src/md.test.ts @@ -0,0 +1,136 @@ +import { describe, expect, it } from 'vitest'; +import { assetUrls, parseCheatSheet, parseFrontMatter, renderMarkdown } from './index.js'; + +describe('front matter', () => { + it('терпит двоеточие в значении и запятую без пробела в списке', () => { + const { meta, body } = parseFrontMatter( + [ + '---', + 'title: Заголовок', + 'summary: Карта стойки: верх — оптика', + 'equipment: [Fortisflex MG-12 80033, уголок 130х130х100х1,8, FTP Cat5e]', + 'source: [originals/a.pdf, originals/b.pdf]', + 'pinned: true', + 'order: 3', + '---', + '', + 'Текст', + ].join('\n'), + ); + expect(meta.summary).toBe('Карта стойки: верх — оптика'); + expect(meta.equipment).toEqual(['Fortisflex MG-12 80033', 'уголок 130х130х100х1,8', 'FTP Cat5e']); + expect(meta.source).toHaveLength(2); + expect(meta.pinned).toBe(true); + expect(meta.order).toBe(3); + expect(body.trim()).toBe('Текст'); + }); +}); + +describe('renderMarkdown', () => { + it('рисует блок «Главное» и собирает факты', () => { + const r = renderMarkdown(':::keyfacts\n- Запас: **20 см** (под светофор)\n- Сальник: **MG-12**\n:::'); + expect(r.html).toContain('kb-key'); + expect(r.html).toContain('2 пункта'); + expect(r.facts).toEqual([ + { label: 'Запас', value: '**20 см** (под светофор)' }, + { label: 'Сальник', value: '**MG-12**' }, + ]); + expect(r.text.keyfacts).toContain('20 см'); + }); + + it('рисует запрет, чек-лист, шаги и таблицы', () => { + const r = renderMarkdown( + [ + ':::danger', + 'Нельзя **так**.', + ':::', + '', + '- [ ] Раз', + '- [x] Два', + '', + '1. **Шаг.** Сделать', + '', + '| Куда | Длина |', + '|---|---|', + '| SIP | **2 м** |', + '', + '| A | B | C |', + '|---|---|---|', + '| 1 | 2 | 3 |', + ].join('\n'), + ); + expect(r.html).toContain('kb-danger'); + expect(r.html).toContain('ЗАПРЕЩЕНО'); + expect(r.html).toContain('data-check="0"'); + expect(r.html).toContain('0 из 2'); + expect(r.html).toContain('kb-step-title'); + expect(r.html).toContain('kb-kv'); + expect(r.html).toContain('kb-cards'); + }); + + it('подставляет названия в [[ссылки]] и отмечает битые', () => { + const r = renderMarkdown('См. [[shkon]] и [[net-takoy]]', { + resolveLink: (s) => (s === 'shkon' ? 'ШКОН' : undefined), + }); + expect(r.links).toEqual(['shkon', 'net-takoy']); + expect(r.brokenLinks).toEqual(['net-takoy']); + expect(r.html).toContain('href="/a/shkon"'); + expect(r.html).toContain('>ШКОН<'); + expect(r.html).toContain('kb-link--broken'); + }); + + it('собирает фото в группу и оглавление по H2', () => { + const r = renderMarkdown('## Фото\n\n![Рис. 1](assets/x/fig-1.jpg)\n![Рис. 2](assets/x/fig-2.jpg)'); + expect(r.toc).toEqual([{ id: 'h-0', text: 'Фото' }]); + expect(r.figures.map((f) => f.full)).toEqual(['/uploads/assets/x/fig-1.webp', '/uploads/assets/x/fig-2.webp']); + expect(r.html).toContain('/uploads/assets/x/fig-2.480.webp'); + expect(r.html).toContain('data-fig="1"'); + }); + + it('не пропускает HTML и опасные ссылки', () => { + const r = renderMarkdown('\n\n\n\n[жми](javascript:alert(1))'); + expect(r.html).not.toContain(' { + expect(renderMarkdown('Изолента ~15 см и ~30 см').html).not.toContain(' { + it('строит адреса WebP и превью', () => { + expect(assetUrls('assets/shkon/fig-1.jpg')).toMatchObject({ + full: '/uploads/assets/shkon/fig-1.webp', + thumb: '/uploads/assets/shkon/fig-1.480.webp', + file: 'fig-1.jpg', + }); + expect(assetUrls('/uploads/2026/10/abc.webp').thumb).toBe('/uploads/2026/10/abc.480.webp'); + }); +}); + +describe('parseCheatSheet', () => { + it('разбирает запреты, цифры, цвета и «всегда»', () => { + const s = parseCheatSheet( + [ + '## ⛔ Запрещено', + '- Подключать **УЗИП до автомата** → только шинки → [[silovoe]]', + '## 📏 Цифры', + '| Что | Значение | Где |', + '|---|---|---|', + '| Изолента: ШКОН / ШКОС | **15 см / 30 см** | [[shkon]] · [[shkos]] |', + '## 🎨 Цвета', + '- Уголок фотоэлемента: **RAL 5017**', + '## ✅ Всегда', + '- бирки на ВОК **до** сварки', + ].join('\n'), + ); + expect(s.ok).toBe(true); + expect(s.bans[0]?.links).toEqual(['silovoe']); + expect(s.bans[0]?.segs.at(-1)?.t).toBe(' → только шинки'); + expect(s.facts[0]).toMatchObject({ value: '15 см / 30 см', links: ['shkon', 'shkos'] }); + expect(s.colors).toEqual([{ code: 'RAL 5017', label: 'Уголок фотоэлемента' }]); + expect(s.always[0]?.segs).toHaveLength(3); + }); +}); diff --git a/packages/md/src/parse.ts b/packages/md/src/parse.ts new file mode 100644 index 0000000..4c78731 --- /dev/null +++ b/packages/md/src/parse.ts @@ -0,0 +1,78 @@ +import { unified } from 'unified'; +import remarkParse from 'remark-parse'; +import remarkGfm from 'remark-gfm'; +import remarkDirective from 'remark-directive'; + +// Упрощённый тип узла Markdown-дерева (mdast). Полные типы из @types/mdast здесь +// только мешают: у нас есть свои узлы (wikiLink, containerDirective). +export interface MdNode { + type: string; + value?: string; + children?: MdNode[]; + depth?: number; + ordered?: boolean; + start?: number | null; + checked?: boolean | null; + url?: string; + alt?: string | null; + title?: string | null; + name?: string; + slug?: string; + lang?: string | null; +} + +const WIKI_RE = /\[\[([a-z0-9][a-z0-9-]*)\]\]/g; + +/** + * Свой remark-плагин: превращает текст `[[slug]]` в узел { type: 'wikiLink', slug }. + * Дальше рендер делает из него ссылку-чип с названием статьи. + */ +function remarkWikiLinks() { + return (tree: MdNode) => { + const walk = (node: MdNode) => { + if (!node.children) return; + // Внутри кода ссылки не трогаем + if (node.type === 'code' || node.type === 'inlineCode') return; + const out: MdNode[] = []; + for (const child of node.children) { + if (child.type !== 'text' || !child.value || !child.value.includes('[[')) { + walk(child); + out.push(child); + continue; + } + const text = child.value; + let last = 0; + for (const m of text.matchAll(WIKI_RE)) { + const at = m.index ?? 0; + if (at > last) out.push({ type: 'text', value: text.slice(last, at) }); + out.push({ type: 'wikiLink', slug: m[1] }); + last = at + m[0].length; + } + if (last < text.length) out.push({ type: 'text', value: text.slice(last) }); + } + node.children = out; + }; + walk(tree); + }; +} + +const processor = unified().use(remarkParse) + // singleTilde: false, иначе «~15 см … ~30 см» в одном абзаце станет зачёркнутым текстом + .use(remarkGfm, { singleTilde: false }) + .use(remarkDirective) + .use(remarkWikiLinks); + +/** Markdown (без front matter) → дерево mdast. */ +export function parseMarkdown(md: string): MdNode { + const tree = processor.parse(md); + return processor.runSync(tree) as unknown as MdNode; +} + +/** Весь текст узла подряд, без разметки. */ +export function plainText(node: MdNode): string { + if (node.type === 'wikiLink') return ''; + if (node.type === 'image') return node.alt ?? ''; + if (node.type === 'break') return ' '; + if (typeof node.value === 'string') return node.value; + return (node.children ?? []).map(plainText).join(''); +} diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 45bf322..58e27eb 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -157,3 +157,34 @@ export function plural(n: number, forms: [string, string, string]): string { if (b === 1) return forms[0]; return forms[2]; } + +// ---------- Нормализация текста для поиска (одинаковая при индексации и при запросе) ---------- + +/** Нижний регистр, ё→е, все виды тире → дефис, лишние пробелы убраны. */ +export function normalizeSearch(s: string): string { + return s + .toLowerCase() + .replace(/ё/g, 'е') + .replace(/[‐-―−]/g, '-') + .replace(/[   ]/g, ' ') + .replace(/\s+/g, ' ') + .trim(); +} + +/** + * «Сжатый» вид: только буквы и цифры. Так «MG12» находит «MG-12», + * а «ral7024» находит «RAL 7024». + */ +export function compactSearch(s: string): string { + return normalizeSearch(s).replace(/[^\p{L}\p{N}]+/gu, ''); +} + +/** Короткое название статьи для меню: без «Название раздела — » в начале. */ +export function shortTitle(title: string, sectionName?: string): string { + let t = title; + if (sectionName && t.toLowerCase().startsWith(sectionName.toLowerCase())) { + const rest = t.slice(sectionName.length).replace(/^\s*[—–:-]\s*/, ''); + if (rest && rest !== t.slice(sectionName.length)) t = rest; + } + return t.charAt(0).toUpperCase() + t.slice(1); +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e1150c9..622550f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -151,9 +151,9 @@ importers: packages/md: dependencies: - hast-util-to-string: - specifier: ^3.0.1 - version: 3.0.1 + '@kb/shared': + specifier: workspace:^ + version: link:../shared rehype-sanitize: specifier: ^6.0.0 version: 6.0.0 @@ -169,9 +169,6 @@ importers: remark-parse: specifier: ^11.0.0 version: 11.0.0 - remark-rehype: - specifier: ^11.1.2 - version: 11.1.2 unified: specifier: ^11.0.5 version: 11.0.5 @@ -2440,9 +2437,6 @@ packages: hast-util-to-html@9.0.5: resolution: {integrity: sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==} - hast-util-to-string@3.0.1: - resolution: {integrity: sha512-XelQVTDWvqcl3axRfI0xSeoVKzyIFPwsAGSLIsKdJKQMXDYJS4WYrBNF/8J7RdhIcFI2BOHgAifggsvsxp/3+A==} - hast-util-whitespace@3.0.0: resolution: {integrity: sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==} @@ -3284,9 +3278,6 @@ packages: remark-parse@11.0.0: resolution: {integrity: sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==} - remark-rehype@11.1.2: - resolution: {integrity: sha512-Dh7l57ianaEoIpzbp0PC9UKAdCSVklD8E5Rpw7ETfbTl3FqcOOgq5q2LVDhgGCkaBv7p24JXikPdvhhmHvKMsw==} - remark-stringify@11.0.0: resolution: {integrity: sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw==} @@ -6206,10 +6197,6 @@ snapshots: stringify-entities: 4.0.4 zwitch: 2.0.4 - hast-util-to-string@3.0.1: - dependencies: - '@types/hast': 3.0.5 - hast-util-whitespace@3.0.0: dependencies: '@types/hast': 3.0.5 @@ -7205,14 +7192,6 @@ snapshots: transitivePeerDependencies: - supports-color - remark-rehype@11.1.2: - dependencies: - '@types/hast': 3.0.5 - '@types/mdast': 4.0.4 - mdast-util-to-hast: 13.2.1 - unified: 11.0.5 - vfile: 6.0.3 - remark-stringify@11.0.0: dependencies: '@types/mdast': 4.0.4