diff --git a/worker/handler.js b/worker/handler.js index ea8fd60..23e4d9c 100644 --- a/worker/handler.js +++ b/worker/handler.js @@ -54,8 +54,16 @@ function matchesRoute(pathname, prefix) { * @returns {string} */ function cleanMarkdown(text) { - // Strip frontmatter + // Extract title from frontmatter, then strip it + const fmMatch = text.match(/^---\n([\s\S]*?)\n---/); + let title = ''; + if (fmMatch) { + const titleMatch = fmMatch[1].match(/^title:\s*(.+)$/m); + if (titleMatch) title = titleMatch[1].trim().replace(/^["']|["']$/g, ''); + } text = text.replace(/^---\n[\s\S]*?\n---\n*/, ''); + // Add title as H1 if present + if (title) text = `# ${title}\n\n${text}`; // Strip import statements text = text.replace(/^import\s+.*;\s*\n/gm, ''); // Convert to ### headings, strip wrappers diff --git a/worker/handler.test.js b/worker/handler.test.js index ec286fd..7a69bb3 100644 --- a/worker/handler.test.js +++ b/worker/handler.test.js @@ -41,8 +41,13 @@ describe('matchesRoute', () => { // --- cleanMarkdown --- describe('cleanMarkdown', () => { - it('strips frontmatter', () => { + it('extracts title from frontmatter as H1', () => { const input = '---\ntitle: Test\nsidebar_position: 1\n---\n\n# Hello\n'; + expect(cleanMarkdown(input)).toBe('# Test\n\n# Hello\n'); + }); + + it('strips frontmatter without title', () => { + const input = '---\nsidebar_position: 1\n---\n\n# Hello\n'; expect(cleanMarkdown(input)).toBe('# Hello\n'); }); @@ -144,9 +149,10 @@ describe('handleRequest', () => { const res = await handleRequest(req); expect(res.headers.get('content-type')).toBe('text/markdown; charset=utf-8'); const text = await res.text(); - expect(text).not.toContain('---'); + expect(text).not.toContain('sidebar_position'); expect(text).not.toContain('import '); expect(text).toContain('### JavaScript'); + expect(text).toContain('# Test'); expect(text).toContain('# Hello'); });