import type { BlogConfig } from '../../../../config/blog'
import { copyFileSync, existsSync, mkdirSync, readdirSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { path as p } from '@stacksjs/path'
export interface BuildBlogOptions {
config: BlogConfig
outDir: string
}
interface PostRow {
id: number
title: string
slug?: string | null
content: string
body?: string | null
excerpt?: string | null
poster?: string | null
status: string
published_at?: string | null
views?: number | null
is_featured?: boolean | number | null
author_id?: number | null
created_at?: string | null
updated_at?: string | null
}
interface AuthorRow {
id: number
name: string
email: string
bio?: string | null
avatar?: string | null
social_links?: string | null
}
function getSlug(post: PostRow): string {
if (post.slug && typeof post.slug === 'string' && post.slug !== 'null') {
return post.slug
}
return `post-${post.id}`
}
function escapeHtml(str: string): string {
return str
.replace(/&/g, '&')
.replace(//g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
}
function escapeXml(str: string): string {
return escapeHtml(str)
}
function formatDate(dateStr: string): string {
const date = new Date(dateStr)
return date.toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
})
}
function formatRssDate(dateStr: string): string {
return new Date(dateStr).toUTCString()
}
function estimateReadingTime(text: string): number {
const words = text.split(/\s+/).length
return Math.max(1, Math.ceil(words / 200))
}
function renderMarkdownish(text: string): string {
// Simple markdown-like rendering for paragraphs, headings, code blocks, bold, links
const lines = text.split('\n')
const result: string[] = []
let inCodeBlock = false
let codeBuffer: string[] = []
let paragraphBuffer: string[] = []
function flushParagraph() {
if (paragraphBuffer.length > 0) {
const text = paragraphBuffer.join(' ')
if (text.trim()) {
result.push(`
${inlineFormat(text.trim())}
`)
}
paragraphBuffer = []
}
}
function inlineFormat(str: string): string {
// Bold: **text**
str = str.replace(/\*\*(.+?)\*\*/g, '$1')
// Inline code: `text`
str = str.replace(/`([^`]+)`/g, '$1')
// Links: [text](url)
str = str.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '$1')
return str
}
for (const line of lines) {
if (line.startsWith('```')) {
if (inCodeBlock) {
result.push(`${escapeHtml(codeBuffer.join('\n'))}
`)
codeBuffer = []
inCodeBlock = false
} else {
flushParagraph()
inCodeBlock = true
}
continue
}
if (inCodeBlock) {
codeBuffer.push(line)
continue
}
if (line.trim() === '') {
flushParagraph()
continue
}
if (line.startsWith('## ')) {
flushParagraph()
result.push(`${inlineFormat(escapeHtml(line.slice(3)))}
`)
} else if (line.startsWith('### ')) {
flushParagraph()
result.push(`${inlineFormat(escapeHtml(line.slice(4)))}
`)
} else if (line.startsWith('- ') || line.startsWith('* ')) {
flushParagraph()
result.push(`- ${inlineFormat(escapeHtml(line.slice(2)))}
`)
} else {
paragraphBuffer.push(escapeHtml(line))
}
}
if (inCodeBlock && codeBuffer.length) {
result.push(`${escapeHtml(codeBuffer.join('\n'))}
`)
}
flushParagraph()
// Merge consecutive elements
return result.join('\n').replace(/<\/ul>\n/g, '\n')
}
function blogFontFaces(fontPath = '/assets/fonts/nps'): string {
return `@font-face {
font-family: 'Campmate Script';
src: url('${fontPath}/CampmateScript-Regular.woff2') format('woff2');
font-weight: 400;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: 'Sequoia Sans';
src: url('${fontPath}/SequoiaSans-Regular.woff2') format('woff2');
font-weight: 400;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: 'Switchback';
src: url('${fontPath}/Switchback-Regular.woff2') format('woff2');
font-weight: 400;
font-style: normal;
font-display: swap;
}`
}
function copyBlogFonts(outDir: string): void {
const sourceDir = p.frameworkPath('defaults/resources/assets/fonts/nps')
if (!existsSync(sourceDir))
return
const targetDir = join(outDir, 'assets', 'fonts', 'nps')
ensureDir(targetDir)
for (const file of readdirSync(sourceDir)) {
if (file.endsWith('.woff2'))
copyFileSync(join(sourceDir, file), join(targetDir, file))
}
}
function copyBlogImages(outDir: string): void {
const sourceDir = p.frameworkPath('defaults/resources/assets/images')
if (!existsSync(sourceDir))
return
const targetDir = join(outDir, 'assets', 'images')
ensureDir(targetDir)
for (const file of readdirSync(sourceDir)) {
if (file.endsWith('.svg'))
copyFileSync(join(sourceDir, file), join(targetDir, file))
}
}
function sqliteDatabasePath(): string {
const configuredPath = process.env.DB_DATABASE_PATH || 'database/stacks.sqlite'
return configuredPath.startsWith('/') ? configuredPath : p.projectPath(configuredPath)
}
function shouldUseLocalSqlite(): boolean {
return (process.env.DB_CONNECTION || 'sqlite') === 'sqlite' && existsSync(sqliteDatabasePath())
}
async function queryLocalSqlite(sql: string): Promise {
if (!shouldUseLocalSqlite())
return null
const { Database } = await import('bun:sqlite')
const sqlite = new Database(sqliteDatabasePath(), { readonly: true })
try {
return sqlite.query(sql).all() as T[]
} finally {
sqlite.close()
}
}
async function withTimeout(promise: Promise, ms: number): Promise {
let timeout: ReturnType | undefined
try {
return await Promise.race([
promise,
new Promise((_, reject) => {
timeout = setTimeout(() => reject(new Error(`CMS database query timed out after ${ms}ms`)), ms)
}),
])
} finally {
if (timeout)
clearTimeout(timeout)
}
}
async function fetchPublishedPosts(): Promise {
const sqlitePosts = await queryLocalSqlite(
'select * from posts where status = \'published\' order by published_at desc',
)
if (sqlitePosts)
return sqlitePosts
const { db } = await import('@stacksjs/database/runtime')
return await withTimeout(
db
.selectFrom('posts')
.where('status', '=', 'published')
.orderBy('published_at', 'desc')
.selectAll()
.execute() as unknown as Promise,
3000,
)
}
async function fetchAuthors(): Promise {
const sqliteAuthors = await queryLocalSqlite('select * from authors order by created_at desc')
if (sqliteAuthors)
return sqliteAuthors
const { db } = await import('@stacksjs/database/runtime')
return await withTimeout(
db
.selectFrom('authors')
.selectAll()
.execute() as unknown as Promise,
3000,
)
}
function generateLayout(config: BlogConfig, title: string, content: string, _options?: { isPost?: boolean }): string {
const pageTitle = title === config.title ? config.title : `${escapeHtml(title)} | ${escapeHtml(config.title)}`
return `
${pageTitle}
${content}
`
}
/**
* Posts to the app's own subscribe endpoint. It used to post to
* stacksjs.com's, so every app's blog signed its readers up to the framework's
* mailing list under copy that said so.
*/
function generateNewsletterCapture(config: BlogConfig, source = 'blog-static'): string {
return `
Newsletter
Get new posts by email
New posts from ${escapeHtml(config.title)}, sent when they are published.
`
}
function generatePostCard(post: PostRow, config: BlogConfig, author?: AuthorRow): string {
const slug = getSlug(post)
const date = post.published_at ? formatDate(post.published_at) : ''
const authorName = author?.name || config.author || ''
const rawExcerpt = post.excerpt || (post.body || post.content || '').slice(0, 220)
const excerpt = rawExcerpt.replace(/[#*`\[\]]/g, '').trim()
const featured = post.is_featured ? 'Featured' : ''
const readTime = estimateReadingTime(post.body || post.content || '')
return `-
${escapeHtml(authorName)}
·
${date}
·
${readTime} min read
${escapeHtml(excerpt)}${excerpt.length >= 200 ? '...' : ''}
Read more →
`
}
function generatePostPage(post: PostRow, config: BlogConfig, author?: AuthorRow): string {
const date = post.published_at ? formatDate(post.published_at) : ''
const bodyContent = post.body || post.content || ''
const authorName = author?.name || config.author || ''
const readTime = estimateReadingTime(bodyContent)
const authorHtml = author
? `
${author.avatar ? `
})
` : ''}
${escapeHtml(author.name)}
${author.bio ? `
${escapeHtml(author.bio.slice(0, 100))}
` : ''}
`
: `
${escapeHtml(authorName)}
`
const authorFooter = author
? ``
: ''
const content = `
← All posts
${renderMarkdownish(bodyContent)}
${authorFooter}
`
return generateLayout(config, post.title, content, { isPost: true })
}
function generateIndexPage(posts: PostRow[], config: BlogConfig, authors: Map, page: number, totalPages: number): string {
const postCards = posts.map(post => {
const author = post.author_id ? authors.get(post.author_id) : undefined
return generatePostCard(post, config, author)
}).join('\n')
let pagination = ''
if (totalPages > 1) {
const prev = page > 1 ? `← Newer` : ''
const next = page < totalPages ? `Older →` : ''
pagination = ``
}
const hero = page === 1 ? `
${escapeHtml(config.title)}
${escapeHtml(config.description)}
` : ''
const content = `
${hero}
${page === 1 ? generateNewsletterCapture(config) : ''}
${posts.length > 0
? ``
: 'No posts yet.
'}
${pagination}`
return generateLayout(config, config.title, content)
}
function generateRssFeed(posts: PostRow[], config: BlogConfig, origin: string): string {
const items = posts.map(post => {
const slug = getSlug(post)
const pubDate = post.published_at ? formatRssDate(post.published_at) : ''
const description = post.excerpt || (post.body || post.content || '').slice(0, 300)
return ` -
${escapeXml(post.title)}
${origin}/posts/${escapeXml(slug)}/
${origin}/posts/${escapeXml(slug)}/
${escapeXml(description)}
${pubDate ? `${pubDate}` : ''}
`
}).join('\n')
return `
${escapeXml(config.title)}
${origin}/
${escapeXml(config.description)}
en-us
${new Date().toUTCString()}
${items}
`
}
function generateSitemap(posts: PostRow[], _config: BlogConfig, origin: string): string {
const urls = posts.map((post) => {
const slug = getSlug(post)
const lastmod = post.updated_at || post.published_at || ''
return `
${origin}/posts/${escapeXml(slug)}/
${lastmod ? `${new Date(lastmod).toISOString().split('T')[0]}` : ''}
weekly
`
}).join('\n')
return `
${origin}/
daily
1.0
${urls}
`
}
function ensureDir(dir: string): void {
mkdirSync(dir, { recursive: true })
}
/**
* The site origin feeds and the sitemap link against: the blog's configured
* `url`, else APP_URL. It was `${subdomain}.stacksjs.com` for every app.
*/
function siteOrigin(config: BlogConfig): string {
const raw = String(config.url || process.env.APP_URL || '').trim().replace(/\/+$/, '')
if (!raw)
return ''
return /^https?:\/\//.test(raw) ? raw : `https://${raw}`
}
export async function buildBlogSite(options: BuildBlogOptions): Promise {
const { config, outDir } = options
const origin = siteOrigin(config)
// Ensure output directory
ensureDir(outDir)
ensureDir(join(outDir, 'posts'))
copyBlogFonts(outDir)
copyBlogImages(outDir)
// Fetch published posts from database. An empty or unreachable database
// builds an empty blog: this used to fall back to built-in posts announcing
// Stacks, and published them on whatever app deployed without posts yet.
let posts: PostRow[] = []
try {
const dbPosts = await fetchPublishedPosts()
// Seeded faker rows have no slug and a sentence for a title. A table
// holding nothing else is a fresh app's seed data, not a blog.
const hasRealContent = dbPosts.some(post => post.slug && post.slug !== 'null' && !post.title.endsWith('.'))
if (hasRealContent)
posts = dbPosts
} catch {
console.log(' Database not available, building an empty blog')
}
// Fetch authors
const authors = new Map()
try {
const authorRows = await fetchAuthors()
for (const author of authorRows) {
authors.set(author.id, author)
}
} catch {
// Authors table may not exist yet
}
// Generate paginated index pages
const postsPerPage = config.postsPerPage || 10
const totalPages = Math.max(1, Math.ceil(posts.length / postsPerPage))
for (let page = 1; page <= totalPages; page++) {
const start = (page - 1) * postsPerPage
const pagePosts = posts.slice(start, start + postsPerPage)
const html = generateIndexPage(pagePosts, config, authors, page, totalPages)
if (page === 1) {
writeFileSync(join(outDir, 'index.html'), html)
}
if (totalPages > 1) {
const pageDir = join(outDir, 'page', String(page))
ensureDir(pageDir)
writeFileSync(join(pageDir, 'index.html'), html)
}
}
// Generate individual post pages
const generatedSlugs = new Set()
for (const post of posts) {
const slug = getSlug(post)
// Skip duplicate slugs
if (generatedSlugs.has(slug)) continue
generatedSlugs.add(slug)
const postDir = join(outDir, 'posts', slug)
ensureDir(postDir)
const author = post.author_id ? authors.get(post.author_id) : undefined
const html = generatePostPage(post, config, author)
writeFileSync(join(postDir, 'index.html'), html)
}
// Generate RSS feed
if (config.enableRss) {
const rss = generateRssFeed(posts.slice(0, 20), config, origin)
writeFileSync(join(outDir, 'feed.xml'), rss)
}
// Generate sitemap
if (config.enableSitemap) {
const sitemap = generateSitemap(posts, config, origin)
writeFileSync(join(outDir, 'sitemap.xml'), sitemap)
}
// Generate 404 page
const notFoundContent = `
`
writeFileSync(join(outDir, '404.html'), generateLayout(config, '404 - Not Found', notFoundContent))
console.log(` Generated ${generatedSlugs.size} post pages, ${totalPages} index page(s)`)
if (config.enableRss) console.log(' Generated feed.xml')
if (config.enableSitemap) console.log(' Generated sitemap.xml')
}