Files
ipal-kit/src/modules/content/blocksToMarkdown.ts
T
radoslaw.smolinski 09925e4cfd feat: v1.7.0 — AI-readability suite, form engine & boilerplate helpers
AI / GEO:
- feat(content): lexicalToMarkdown, blocksToMarkdown, createMarkdownRenderer
  (+markdownResponse) — per-page Markdown for AI agents
- feat(content): markdown content negotiation + discovery (prefersMarkdown, markdownHref)
- feat(seo): buildRobots aiBots policy (allow/block-training/disallow)
- feat(seo): llms-full.txt mode in buildLlmsTxt/createLlmsTxtRoute
- feat(mcp): createMcpRoute — read-only MCP server (search_content, get_page)
- feat(content): searchContent + createSearchRoute — shared JSON search
- feat(seo): buildSpeakableJsonLd + buildSummaryField (aiSummary, auto-fill)

Forms:
- feat(forms): useForm/useContactForm + validators (logic-only, no markup)
- feat(forms): honeypot anti-spam (honeypotInputProps, isHoneypotTripped)

Helpers / hardening:
- feat(i18n): resolveLocalized — replaces ad-hoc getSafeString
- feat(hooks): buildCrossLocaleFieldSync — locales from config, no hardcoded list
- feat(seo): buildNoindexField — checkbox → meta.noindex, no
- feat(content): resolveRedirect — 301/308 from slugHistory
- feat(env): assertEnv + ipalEnvRules — fail-fast env validation
- feat(consent): ConsentScript — load third-party only after consent
- feat(health): createHealthRoute — Coolify/Docker DB liveness

Fixes:
- fix(seo): wrap getCachedPayload in try/catch in createManifestHandler
  (Docker/CI build no longer crashes when DB unreachable)

docs: migration.md (20 sections), new env.md/mcp.md, updated agents.md,
AGENTS-TEMPLATE.md, forms/hooks/content/seo/consent/deployment/richtext
2026-10-10 16:52:16 +02:00

133 lines
4.2 KiB
TypeScript

// Import the leaf, not the richtext barrel — the barrel re-exports
// RenderRichText (a React component), which would pull React into this pure,
// server-usable module.
import { lexicalToMarkdown } from '../richtext/lexicalToMarkdown.js'
/**
* Converts a page's `blocks` layout to Markdown by CONVENTION — the same field
* names the project already standardises on (heading, subheading, body,
* content, image, items/faq/…; see the naming rules in agents.md). The plugin
* can't know each project's block shapes, but it CAN rely on those conventions,
* so most blocks convert with zero per-project wiring. Special blocks get an
* `overrides` entry keyed by blockType.
*
* Output is for AI/agent consumption (per-page Markdown, llms-full.txt), not
* on-page rendering — it extracts readable text, not pixel-perfect layout.
*
* blocksToMarkdown(page.layout)
* blocksToMarkdown(page.layout, {
* overrides: { gallery: (b) => `(${(b.images as unknown[])?.length ?? 0} photos)` },
* })
*/
type Block = Record<string, unknown> & { blockType?: string }
type BlockToMarkdown = (block: Block) => string
type BlocksToMarkdownArgs = {
/** Per-blockType custom renderers. Return '' to omit a block. */
overrides?: Record<string, BlockToMarkdown>
}
const HEADING_KEYS = new Set(['heading', 'title'])
const SUBHEADING_KEYS = new Set(['subheading', 'subtitle'])
const QUESTION_KEYS = new Set(['question'])
const TEXT_KEYS = new Set([
'body',
'text',
'description',
'excerpt',
'summary',
'answer',
'caption',
'label',
'content',
])
const ARRAY_KEYS = new Set([
'items',
'features',
'faq',
'faqs',
'cards',
'columns',
'rows',
'questions',
'services',
'steps',
'points',
'benefits',
'list',
])
/** A populated richText value is an object with a `root`. */
function isRichText(v: unknown): boolean {
return !!v && typeof v === 'object' && 'root' in (v as Record<string, unknown>)
}
/** A populated upload (image) is an object with a `url`. */
function imageMarkdown(v: unknown): string {
if (!v || typeof v !== 'object') return ''
const o = v as Record<string, unknown>
const url = typeof o.url === 'string' ? o.url : ''
const alt = typeof o.alt === 'string' ? o.alt : ''
return url ? `![${alt}](${url})` : ''
}
/** Extract readable Markdown from one block's known content fields. */
function extractBlock(block: Block, depth: number): string {
const lines: string[] = []
for (const [key, value] of Object.entries(block)) {
if (value == null) continue
if (HEADING_KEYS.has(key) && typeof value === 'string' && value.trim()) {
lines.push(`## ${value.trim()}`)
} else if (SUBHEADING_KEYS.has(key) && typeof value === 'string' && value.trim()) {
lines.push(`### ${value.trim()}`)
} else if (QUESTION_KEYS.has(key) && typeof value === 'string' && value.trim()) {
lines.push(`**${value.trim()}**`)
} else if (key === 'image') {
const img = imageMarkdown(value)
if (img) lines.push(img)
} else if (isRichText(value)) {
const md = lexicalToMarkdown(value as never)
if (md) lines.push(md)
} else if (TEXT_KEYS.has(key) && typeof value === 'string' && value.trim()) {
lines.push(value.trim())
} else if (ARRAY_KEYS.has(key) && Array.isArray(value) && depth < 4) {
for (const item of value) {
if (item && typeof item === 'object') {
const sub = extractBlock(item as Block, depth + 1)
if (sub.trim()) lines.push(sub)
} else if (typeof item === 'string' && item.trim()) {
lines.push(`- ${item.trim()}`)
}
}
}
}
return lines.join('\n\n')
}
export function blocksToMarkdown(layout: unknown, args: BlocksToMarkdownArgs = {}): string {
if (!Array.isArray(layout)) return ''
const { overrides = {} } = args
const out: string[] = []
for (const block of layout) {
if (!block || typeof block !== 'object') continue
const b = block as Block
const type = typeof b.blockType === 'string' ? b.blockType : ''
if (type && overrides[type]) {
const md = overrides[type](b)
if (md.trim()) out.push(md.trim())
continue
}
const md = extractBlock(b, 0)
if (md.trim()) out.push(md.trim())
}
return out.join('\n\n').trim()
}