An open source design system that's fully customizable and agent ready
TypeScript
feat(docsite): add human-authored blog scaffold (#2909)
Cindy Zhang189f6157d65d
diff --git a/apps/docsite/README.md b/apps/docsite/README.mdindex 00419649e1..e6533beac8 100644--- a/apps/docsite/README.md+++ b/apps/docsite/README.md@@ -31,6 +31,7 @@ from the monorepo and writes typed TypeScript registries to `src/generated/`.| `blockRegistry.ts` | CLI `templates/blocks/` | Showcase and example blocks with metadata || `templateRegistry.ts` | CLI `templates/pages/` | Page-level templates (e.g. dashboard, settings) || `docsRegistry.ts` | CLI `docs/` | Long-form guide and foundation topics |+| `blogRegistry.ts` | `src/content/blog/posts/` | Human-authored blog posts (frontmatter validated) || `themeRegistry.ts` | Installed `@xds/theme-*` packages | Built theme objects, keyed by package name || `showcaseRegistry.ts` | Blocks with `isShowcase` | Copied showcase source files || `exampleRegistry.ts` | Blocks with `exampleFor` | Copied example blocks per component |@@ -82,6 +83,24 @@ The package appears in the sidebar, the libraries section, and gets its own`/docs/<name>` detail page. If the package contains `.doc.mjs` files,its components are extracted into `componentRegistry.ts` as well.+## Adding a Blog Post++The blog lives at `/blog` and `/blog/<slug>`. Posts are human-authored Markdown+files with YAML frontmatter under `src/content/blog/posts/`. Adding a post is+close to dropping in one file — discovery, validation, and sorting are automatic.++See **[`src/content/blog/README.md`](src/content/blog/README.md)** for the full+guide: frontmatter reference, post types, the author registry, cover images, and+local preview. In short:++1. Create `src/content/blog/posts/<slug>.md` with required frontmatter+ (`title`, `description`, `date`, `type`, `authors`, `tags`).+2. If you are a new author, add yourself to `src/content/blog/authors.ts`.+3. Run `pnpm generate && pnpm test && pnpm typecheck`, then `pnpm dev` to preview.++Required frontmatter is validated at build time; drafts (`draft: true`) are+excluded from production output.+## Project Structure```@@ -95,8 +114,11 @@ apps/docsite/│ │ ├── layout.tsx # Root layout│ │ ├── providers.tsx # XDSTheme + client providers│ │ ├── (docs)/ # Main docs routes (components, packages, docs)+│ │ ├── blog/ # Blog index + post detail (no sidebar)│ │ └── craft/ # Craft landing (templates, themes, showcases)-│ └── components/ # Shared UI components+│ ├── components/ # Shared UI components+│ ├── content/blog/ # Blog posts (MD + frontmatter) + authors.ts+│ └── lib/blog/ # Blog discovery, validation, and types├── package.json└── .gitignore # Excludes src/generated/```diff --git a/apps/docsite/scripts/generate-data.mjs b/apps/docsite/scripts/generate-data.mjsindex f1079f45ed..e73e706e9f 100644--- a/apps/docsite/scripts/generate-data.mjs+++ b/apps/docsite/scripts/generate-data.mjs@@ -1469,6 +1469,47 @@ ${componentLines}return entries.length;}+// ── 6. Blog Registry ───────────────────────────────────────────────────++async function generateBlogRegistry() {+ console.log('Generating blog registry...');++ const POSTS_DIR = path.join(+ DOCSITE_ROOT,+ 'src',+ 'content',+ 'blog',+ 'posts',+ );++ // Single source of truth for discovery + validation (shared with tests).+ const {discoverPosts, collectTypes, collectTags} = await import(+ pathToFileURL(+ path.join(DOCSITE_ROOT, 'src', 'lib', 'blog', 'posts.mjs'),+ ).href+ );++ // Exclude drafts from production output; include them only in dev.+ const includeDrafts = process.env.NODE_ENV !== 'production';+ const posts = discoverPosts(POSTS_DIR, {includeDrafts});+ const types = collectTypes(posts);+ const tags = collectTags(posts);++ const content = `// Auto-generated by scripts/generate-data.mjs — do not edit+import type {BlogPost, BlogPostType} from '../lib/blog/schema';++export const blogPosts: BlogPost[] = ${JSON.stringify(posts, null, 2)};++export const blogTypes: BlogPostType[] = ${JSON.stringify(types)};++export const blogTags: string[] = ${JSON.stringify(tags)};++export const blogPostCount = ${posts.length};+`;+ writeRegistry('blogRegistry.ts', content);+ return {blogPostCount: posts.length, blogTypeCount: types.length};+}+async function main() {console.log('Generating docsite data...\n');@@ -1479,6 +1520,7 @@ async function main() {const {blockCount, showcaseCount} = await generateBlockRegistry();const {templateCount} = await generateTemplateRegistry();const {docsCount} = await generateDocsRegistry();+ const {blogPostCount} = await generateBlogRegistry();const showcaseCopied = generateShowcaseRegistry();const examplesCopied = generateExampleRegistry();@@ -1488,6 +1530,7 @@ async function main() {console.log(` ${blockCount} blocks (${showcaseCopied} showcases, ${examplesCopied} examples)`);console.log(` ${templateCount} templates`);console.log(` ${docsCount} doc topics`);+ console.log(` ${blogPostCount} blog posts`);console.log(` ${themeCount} themes`);console.log('Done.');}diff --git a/apps/docsite/src/__tests__/blog.test.ts b/apps/docsite/src/__tests__/blog.test.tsnew file mode 100644index 0000000000..71640ebe9f--- /dev/null+++ b/apps/docsite/src/__tests__/blog.test.ts@@ -0,0 +1,294 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Blog tests for the docsite.+ *+ * Covers blog post discovery, frontmatter parsing, and validation — the+ * contract agents and authors rely on. The discovery/validation logic lives in+ * src/lib/blog/posts.mjs (shared with the build-time generator), so these tests+ * exercise the same code path that CI and `yarn generate` use.+ *+ * Run: yarn workspace @xds/docsite test+ */++import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {describe, it, expect, beforeEach, afterEach} from 'vitest';+import {+ parseFrontmatter,+ parseYamlFrontmatter,+ validatePostFrontmatter,+ estimateReadingTime,+ discoverPosts,+ collectTypes,+ collectTags,+ POST_TYPES,+ MAX_TAGS,+} from '../lib/blog/posts.mjs';++const POSTS_DIR = path.resolve(__dirname, '../content/blog/posts');++const VALID_FM: Record<string, unknown> = {+ title: 'A title',+ description: 'A description',+ date: '2026-06-17',+ type: 'guide',+ authors: ['team'],+ tags: ['AI', 'Docs'],+};++// ── Frontmatter parsing ────────────────────────────────────────────────++describe('parseFrontmatter', () => {+ it('splits frontmatter from body', () => {+ const {data, body} = parseFrontmatter(+ '---\ntitle: "Hi"\n---\n\nHello world.',+ );+ expect(data.title).toBe('Hi');+ expect(body).toBe('Hello world.');+ });++ it('returns empty data when no frontmatter is present', () => {+ const {data, body} = parseFrontmatter('Just a body.');+ expect(data).toEqual({});+ expect(body).toBe('Just a body.');+ });++ it('parses inline string sequences', () => {+ const data = parseYamlFrontmatter('tags: ["AI", "Docs", "Theming"]');+ expect(data.tags).toEqual(['AI', 'Docs', 'Theming']);+ });++ it('parses block string sequences', () => {+ const data = parseYamlFrontmatter('authors:\n - "team"\n - "octocat"');+ expect(data.authors).toEqual(['team', 'octocat']);+ });++ it('parses block sequences of maps (relatedDocs)', () => {+ const data = parseYamlFrontmatter(+ 'relatedDocs:\n - title: "Button"\n href: "/components/button"\n - title: "Docs"\n href: "/docs"',+ );+ expect(data.relatedDocs).toEqual([+ {title: 'Button', href: '/components/button'},+ {title: 'Docs', href: '/docs'},+ ]);+ });++ it('coerces booleans and ignores comments', () => {+ const data = parseYamlFrontmatter('draft: true\n# a comment\nx: false');+ expect(data.draft).toBe(true);+ expect(data.x).toBe(false);+ });+});++// ── Validation ─────────────────────────────────────────────────────────++describe('validatePostFrontmatter', () => {+ it('accepts a valid post and applies defaults', () => {+ const meta = validatePostFrontmatter('slug', {...VALID_FM});+ expect(meta.draft).toBe(false);+ expect(meta.coverImage).toBeNull();+ expect(meta.relatedDocs).toBeNull();+ expect(meta.updatedAt).toBeNull();+ });++ it.each(['title', 'description', 'date', 'type'])('requires "%s"', field => {+ const fm = {...VALID_FM};+ delete fm[field];+ expect(() => validatePostFrontmatter('slug', fm)).toThrow();+ });++ it('rejects unknown post types', () => {+ expect(() =>+ validatePostFrontmatter('slug', {...VALID_FM, type: 'news'}),+ ).toThrow(/type/);+ });++ it('accepts every declared post type', () => {+ for (const type of POST_TYPES) {+ expect(() =>+ validatePostFrontmatter('slug', {...VALID_FM, type}),+ ).not.toThrow();+ }+ });++ it('rejects malformed dates', () => {+ expect(() =>+ validatePostFrontmatter('slug', {...VALID_FM, date: 'June 17 2026'}),+ ).toThrow(/date/);+ });++ it('rejects an empty authors list', () => {+ expect(() =>+ validatePostFrontmatter('slug', {...VALID_FM, authors: []}),+ ).toThrow(/authors/);+ });++ it('rejects an empty tags list', () => {+ expect(() =>+ validatePostFrontmatter('slug', {...VALID_FM, tags: []}),+ ).toThrow(/tags/);+ });++ it(`rejects more than ${MAX_TAGS} tags`, () => {+ expect(() =>+ validatePostFrontmatter('slug', {+ ...VALID_FM,+ tags: ['a', 'b', 'c', 'd', 'e'],+ }),+ ).toThrow(/tags/);+ });++ it('requires coverAlt when coverImage is set', () => {+ expect(() =>+ validatePostFrontmatter('slug', {+ ...VALID_FM,+ coverImage: '/blog/x/cover.png',+ }),+ ).toThrow(/coverAlt/);+ });++ it('accepts coverImage when coverAlt is provided', () => {+ const meta = validatePostFrontmatter('slug', {+ ...VALID_FM,+ coverImage: '/blog/x/cover.png',+ coverAlt: 'A cover',+ });+ expect(meta.coverImage).toBe('/blog/x/cover.png');+ expect(meta.coverAlt).toBe('A cover');+ });++ it('rejects relatedDocs entries missing title or href', () => {+ expect(() =>+ validatePostFrontmatter('slug', {+ ...VALID_FM,+ relatedDocs: [{title: 'No href'}],+ }),+ ).toThrow(/relatedDocs/);+ });+});++// ── Reading time ───────────────────────────────────────────────────────++describe('estimateReadingTime', () => {+ it('returns at least 1 minute', () => {+ expect(estimateReadingTime('a few words')).toBe(1);+ });++ it('scales with word count and ignores code fences', () => {+ const prose = Array(400).fill('word').join(' ');+ expect(estimateReadingTime(prose)).toBe(2);+ const withCode =+ prose + '\n```\n' + Array(1000).fill('x').join(' ') + '\n```';+ // Code is excluded, so the estimate stays ~2 minutes.+ expect(estimateReadingTime(withCode)).toBe(2);+ });+});++// ── Discovery against a temp directory ─────────────────────────────────++describe('discoverPosts (temp fixtures)', () => {+ let dir: string;++ beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'xds-blog-'));+ });++ afterEach(() => {+ fs.rmSync(dir, {recursive: true, force: true});+ });++ const write = (name: string, content: string) =>+ fs.writeFileSync(path.join(dir, name), content);++ const fm = (over: Record<string, string> = {}) => {+ const f = {+ title: 'T',+ description: 'D',+ date: '2026-01-01',+ type: 'guide',+ ...over,+ };+ return [+ '---',+ `title: "${f.title}"`,+ `description: "${f.description}"`,+ `date: "${f.date}"`,+ `type: "${f.type}"`,+ 'authors:',+ ' - "team"',+ 'tags: ["AI"]',+ '---',+ '',+ 'Body content here.',+ ].join('\n');+ };++ it('returns an empty array for a missing directory', () => {+ expect(discoverPosts(path.join(dir, 'nope'))).toEqual([]);+ });++ it('discovers posts and sorts latest-first', () => {+ write('older.md', fm({date: '2026-01-01', title: 'Older'}));+ write('newer.md', fm({date: '2026-06-01', title: 'Newer'}));+ const posts = discoverPosts(dir);+ expect(posts.map(p => p.slug)).toEqual(['newer', 'older']);+ });++ it('excludes drafts by default and includes them on request', () => {+ write('live.md', fm({title: 'Live'}));+ write(+ 'wip.md',+ fm({title: 'WIP'}).replace('tags: ["AI"]', 'tags: ["AI"]\ndraft: true'),+ );+ expect(discoverPosts(dir).map(p => p.slug)).toEqual(['live']);+ expect(+ discoverPosts(dir, {includeDrafts: true})+ .map(p => p.slug)+ .sort(),+ ).toEqual(['live', 'wip']);+ });++ it('throws a clear error for an invalid post', () => {+ write('bad.md', fm({type: 'news'}));+ expect(() => discoverPosts(dir)).toThrow(/bad[\s\S]*type/);+ });++ it('throws when a post body is empty', () => {+ write('empty.md', fm().replace('Body content here.', ''));+ expect(() => discoverPosts(dir)).toThrow(/empty/);+ });++ it('collects present types and tags', () => {+ write('a.md', fm({type: 'guide'}));+ write(+ 'b.md',+ fm({type: 'update'}).replace('tags: ["AI"]', 'tags: ["Release", "AI"]'),+ );+ const posts = discoverPosts(dir);+ expect(collectTypes(posts)).toEqual(['update', 'guide']); // canonical order+ expect(collectTags(posts)).toEqual(['AI', 'Release']); // alphabetical+ });+});++// ── The real content directory ─────────────────────────────────────────++describe('blog content', () => {+ it('discovers and validates all committed posts without throwing', () => {+ expect(() => discoverPosts(POSTS_DIR, {includeDrafts: true})).not.toThrow();+ });++ it('has at least one published example post', () => {+ const posts = discoverPosts(POSTS_DIR);+ expect(posts.length).toBeGreaterThanOrEqual(1);+ });++ it('ships the Astryx launch announcement', () => {+ const posts = discoverPosts(POSTS_DIR);+ const post = posts.find(p => p.slug === 'introducing-astryx');+ expect(post).toBeDefined();+ expect(post?.type).toBe('update');+ expect(post?.authors).toContain('cvkxx');+ });+});diff --git a/apps/docsite/src/app/blog/[slug]/page.tsx b/apps/docsite/src/app/blog/[slug]/page.tsxnew file mode 100644index 0000000000..0d7300c566--- /dev/null+++ b/apps/docsite/src/app/blog/[slug]/page.tsx@@ -0,0 +1,55 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Page type: blog post detail+ * Renders an individual post with article typography. Static params and per-post+ * metadata are derived from the generated blog registry.+ */++import type {Metadata} from 'next';+import {notFound} from 'next/navigation';+import {blogPosts} from '../../../generated/blogRegistry';+import {BlogArticle} from '../../../components/blog/BlogArticle';++export function generateStaticParams() {+ return blogPosts.map(p => ({slug: p.slug}));+}++export async function generateMetadata({+ params,+}: {+ params: Promise<{slug: string}>;+}): Promise<Metadata> {+ const {slug} = await params;+ const post = blogPosts.find(p => p.slug === slug);+ if (!post) {+ return {title: 'Blog — Astryx'};+ }++ const images = post.coverImage ? [{url: post.coverImage}] : undefined;+ return {+ title: `${post.title} — Astryx Blog`,+ description: post.description,+ openGraph: {+ title: post.title,+ description: post.description,+ type: 'article',+ publishedTime: post.date,+ ...(images ? {images} : {}),+ },+ };+}++export default async function BlogPostPage({+ params,+}: {+ params: Promise<{slug: string}>;+}) {+ const {slug} = await params;+ const post = blogPosts.find(p => p.slug === slug);+ if (!post) {+ notFound();+ }++ return <BlogArticle post={post} />;+}diff --git a/apps/docsite/src/app/blog/layout.tsx b/apps/docsite/src/app/blog/layout.tsxnew file mode 100644index 0000000000..5eeed61154--- /dev/null+++ b/apps/docsite/src/app/blog/layout.tsx@@ -0,0 +1,33 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Page type: blog layout+ * Standalone shell with the shared top nav and NO sidebar (issue #2896:+ * "Avoid traditional blog sidebars"). Mirrors the craft/playground layout.+ */++import {headers} from 'next/headers';+import {XDSAppShell} from '@xds/core/AppShell';+import {SharedTopNav} from '../../components/SharedTopNav';+import {SiteFooter} from '../../components/SiteFooter';++export default async function BlogLayout({+ children,+}: {+ children: React.ReactNode;+}) {+ const headersList = await headers();+ const ua = headersList.get('user-agent') ?? '';+ const defaultIsMobile = /mobile|android|iphone|ipad/i.test(ua);++ return (+ <XDSAppShell+ variant="surface"+ height="auto"+ mobileNav={{defaultIsMobile}}+ topNav={<SharedTopNav />}>+ {children}+ <SiteFooter />+ </XDSAppShell>+ );+}diff --git a/apps/docsite/src/app/blog/page.tsx b/apps/docsite/src/app/blog/page.tsxnew file mode 100644index 0000000000..39839747fd--- /dev/null+++ b/apps/docsite/src/app/blog/page.tsx@@ -0,0 +1,21 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Page type: blog index+ * Grid of posts with horizontal type filters and no sidebar.+ * Data comes from the build-time generated blog registry.+ */++import type {Metadata} from 'next';+import {blogPosts, blogTypes} from '../../generated/blogRegistry';+import {BlogIndex} from '../../components/blog/BlogIndex';++export const metadata: Metadata = {+ title: 'Blog — Astryx',+ description:+ 'Notes on building Astryx — releases, guides, stories, and perspectives on designing a system for humans and agents.',+};++export default function BlogPage() {+ return <BlogIndex posts={blogPosts} availableTypes={blogTypes} />;+}diff --git a/apps/docsite/src/components/SiteFooter.tsx b/apps/docsite/src/components/SiteFooter.tsxindex 4f823a97ba..1ea8cad040 100644--- a/apps/docsite/src/components/SiteFooter.tsx+++ b/apps/docsite/src/components/SiteFooter.tsx@@ -16,6 +16,10 @@ const styles = stylex.create({});const links = [+ {+ label: 'Blog',+ href: '/blog',+ },{label: 'Terms of use',href: 'https://opensource.fb.com/legal/terms',diff --git a/apps/docsite/src/components/blog/AuthorByline.tsx b/apps/docsite/src/components/blog/AuthorByline.tsxnew file mode 100644index 0000000000..717add75b7--- /dev/null+++ b/apps/docsite/src/components/blog/AuthorByline.tsx@@ -0,0 +1,109 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file AuthorByline.tsx+ *+ * Renders one or more resolved authors with avatars, plus optional publish/+ * updated dates and reading time. Used on blog cards (compact) and at the top of+ * article pages (full).+ *+ * @input author keys, date, optional updatedAt, optional readingTimeMinutes+ * @output A horizontal byline row+ * @position Used by BlogCard and the article header+ */++import * as stylex from '@stylexjs/stylex';+import {XDSAvatar} from '@xds/core/Avatar';+import {XDSText} from '@xds/core/Text';+import {XDSHStack} from '@xds/core/Layout';+import {resolveAuthor} from '../../content/blog/authors';++export function formatDate(iso: string): string {+ // Parse as UTC to avoid off-by-one from local timezones.+ const d = new Date(iso + 'T00:00:00Z');+ if (Number.isNaN(d.getTime())) {+ return iso;+ }+ return d.toLocaleDateString('en-US', {+ year: 'numeric',+ month: 'long',+ day: 'numeric',+ timeZone: 'UTC',+ });+}++const styles = stylex.create({+ names: {+ display: 'inline',+ },+ dot: {+ opacity: 0.5,+ },+});++export interface AuthorBylineProps {+ authors: string[];+ date: string;+ updatedAt?: string | null;+ readingTimeMinutes?: number;+ /** 'compact' for cards, 'full' for article headers. */+ variant?: 'compact' | 'full';+}++export function AuthorByline({+ authors,+ date,+ updatedAt,+ readingTimeMinutes,+ variant = 'compact',+}: AuthorBylineProps) {+ const resolved = authors.map(resolveAuthor);+ const avatarSize = variant === 'full' ? 'small' : 'tiny';+ const names = resolved.map(a => a.name).join(', ');++ return (+ <XDSHStack gap={2} align="center">+ <XDSHStack gap={0} align="center">+ {resolved.map(author => (+ <XDSAvatar+ key={author.key}+ src={author.avatar}+ name={author.name}+ size={avatarSize}+ />+ ))}+ </XDSHStack>+ <XDSHStack gap={1} align="center">+ <XDSText type="supporting" color="secondary">+ {names}+ </XDSText>+ <XDSText type="supporting" color="secondary" xstyle={styles.dot}>+ ·+ </XDSText>+ <XDSText type="supporting" color="secondary">+ {formatDate(date)}+ </XDSText>+ {variant === 'full' && updatedAt ? (+ <>+ <XDSText type="supporting" color="secondary" xstyle={styles.dot}>+ ·+ </XDSText>+ <XDSText type="supporting" color="secondary">+ Updated {formatDate(updatedAt)}+ </XDSText>+ </>+ ) : null}+ {readingTimeMinutes ? (+ <>+ <XDSText type="supporting" color="secondary" xstyle={styles.dot}>+ ·+ </XDSText>+ <XDSText type="supporting" color="secondary">+ {readingTimeMinutes} min read+ </XDSText>+ </>+ ) : null}+ </XDSHStack>+ </XDSHStack>+ );+}diff --git a/apps/docsite/src/components/blog/BlogArticle.tsx b/apps/docsite/src/components/blog/BlogArticle.tsxnew file mode 100644index 0000000000..08202a8667--- /dev/null+++ b/apps/docsite/src/components/blog/BlogArticle.tsx@@ -0,0 +1,139 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file BlogArticle.tsx+ *+ * Article layout matching the docs page typography: a centered, readable column+ * (maxWidth 800) with a display-1 title, large regular-weight dek, byline, a+ * neutral cover placeholder, the prose body (rendered via XDSMarkdown), optional+ * curated related-doc links, and a link back to the blog index. No sidebar.+ *+ * @input post (BlogPost)+ * @output The full article view+ * @position Rendered by app/blog/[slug]/page.tsx+ */++import * as stylex from '@stylexjs/stylex';+import {XDSMarkdown} from '@xds/core/Markdown';+import {XDSText, XDSHeading} from '@xds/core/Text';+import {XDSVStack, XDSHStack} from '@xds/core/Layout';+import {XDSSection} from '@xds/core/Section';+import {XDSBadge} from '@xds/core/Badge';+import {XDSDivider} from '@xds/core/Divider';+import {XDSLink} from '@xds/core/Link';+import {XDSClickableCard} from '@xds/core/ClickableCard';+import {spacingVars} from '@xds/core/theme/tokens.stylex';+import type {BlogPost} from '../../lib/blog/schema';+import {POST_TYPE_LABELS} from '../../lib/blog/schema';+import {AuthorByline} from './AuthorByline';++const styles = stylex.create({+ section: {+ marginInline: 'auto',+ paddingBottom: `calc(${spacingVars['--spacing-12']} * 2)`,+ },+ // Neutral cover placeholder (cover generator deferred). Calm, theme-driven.+ cover: {+ width: '100%',+ aspectRatio: '16 / 7',+ borderRadius: 'var(--radius-container)',+ backgroundColor: 'var(--color-background-muted)',+ border: '1px solid var(--color-border)',+ },+ coverImg: {+ width: '100%',+ height: '100%',+ objectFit: 'cover',+ display: 'block',+ borderRadius: 'var(--radius-container)',+ },+ tagRow: {+ flexWrap: 'wrap',+ },+});++export interface BlogArticleProps {+ post: BlogPost;+}++export function BlogArticle({post}: BlogArticleProps) {+ return (+ <XDSSection maxWidth={800} padding={6} xstyle={styles.section}>+ <XDSVStack gap={10}>+ {/* Header — matches the docs page treatment */}+ <XDSVStack gap={4}>+ <XDSLink href="/blog" label="Back to blog">+ ← Blog+ </XDSLink>+ <XDSHStack gap={1} align="center" xstyle={styles.tagRow}>+ <XDSBadge label={POST_TYPE_LABELS[post.type]} variant="neutral" />+ </XDSHStack>+ <XDSHeading level={1} type="display-1">+ {post.title}+ </XDSHeading>+ <XDSText type="large" weight="normal" color="secondary">+ {post.description}+ </XDSText>+ <AuthorByline+ authors={post.authors}+ date={post.date}+ updatedAt={post.updatedAt}+ readingTimeMinutes={post.readingTimeMinutes}+ variant="full"+ />+ <XDSDivider />+ </XDSVStack>++ {/* Cover — custom image when provided, else a neutral placeholder */}+ {post.coverImage ? (+ <img+ src={post.coverImage}+ alt={post.coverAlt ?? ''}+ {...stylex.props(styles.cover, styles.coverImg)}+ />+ ) : (+ <div {...stylex.props(styles.cover)} aria-hidden="true" />+ )}++ {/* Body */}+ <XDSMarkdown headingLevelStart={2}>{post.body}</XDSMarkdown>++ {post.tags.length > 0 ? (+ <XDSHStack gap={1} xstyle={styles.tagRow}>+ {post.tags.map(tag => (+ <XDSBadge key={tag} label={tag} variant="neutral" />+ ))}+ </XDSHStack>+ ) : null}++ {/* Related docs — clickable cards, not styled links */}+ {post.relatedDocs && post.relatedDocs.length > 0 ? (+ <XDSVStack gap={4}>+ <XDSDivider />+ <XDSHeading level={2} type="display-3">+ Related+ </XDSHeading>+ <XDSVStack gap={2}>+ {post.relatedDocs.map(doc => (+ <XDSClickableCard+ key={doc.href}+ href={doc.href}+ label={doc.title}+ variant="muted">+ <XDSText type="body" weight="medium">+ {doc.title}+ </XDSText>+ </XDSClickableCard>+ ))}+ </XDSVStack>+ </XDSVStack>+ ) : null}++ <XDSDivider />+ <XDSLink href="/blog" label="Back to all posts">+ ← Back to all posts+ </XDSLink>+ </XDSVStack>+ </XDSSection>+ );+}diff --git a/apps/docsite/src/components/blog/BlogCard.tsx b/apps/docsite/src/components/blog/BlogCard.tsxnew file mode 100644index 0000000000..930de3f36e--- /dev/null+++ b/apps/docsite/src/components/blog/BlogCard.tsx@@ -0,0 +1,110 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file BlogCard.tsx+ *+ * A blog index card built on XDSClickableCard: a neutral+ * cover placeholder on top, then type badge, title, description excerpt,+ * byline, and tag chips. The whole card navigates to the post; nested elements+ * (tags, author links) remain independently interactive.+ *+ * The `feature` variant gives the latest post a larger treatment. This is+ * derived from sort order by the index page — never from per-post metadata.+ *+ * @input post (BlogPost), feature flag+ * @output A clickable card for the blog grid+ * @position Used by the /blog index grid+ */++import * as stylex from '@stylexjs/stylex';+import {XDSText, XDSHeading} from '@xds/core/Text';+import {XDSVStack, XDSHStack} from '@xds/core/Layout';+import {XDSBadge} from '@xds/core/Badge';+import {XDSClickableCard} from '@xds/core/ClickableCard';+import type {BlogPost} from '../../lib/blog/schema';+import {POST_TYPE_LABELS} from '../../lib/blog/schema';+import {AuthorByline} from './AuthorByline';++const styles = stylex.create({+ card: {+ height: '100%',+ },+ inner: {+ height: '100%',+ },+ // Neutral cover placeholder (cover generator deferred). Calm, theme-driven.+ cover: (feature: boolean) => ({+ width: '100%',+ aspectRatio: feature ? '16 / 7' : '16 / 9',+ borderRadius: 'var(--radius-container)',+ backgroundColor: 'var(--color-background-muted)',+ border: '1px solid var(--color-border)',+ }),+ coverImg: {+ width: '100%',+ height: '100%',+ objectFit: 'cover',+ display: 'block',+ borderRadius: 'var(--radius-container)',+ },+ excerpt: {+ display: '-webkit-box',+ WebkitLineClamp: 2,+ WebkitBoxOrient: 'vertical',+ overflow: 'hidden',+ },+ tagRow: {+ flexWrap: 'wrap',+ },+});++export interface BlogCardProps {+ post: BlogPost;+ feature?: boolean;+}++export function BlogCard({post, feature = false}: BlogCardProps) {+ return (+ <XDSClickableCard+ href={`/blog/${post.slug}`}+ label={post.title}+ padding={4}+ xstyle={styles.card}>+ <XDSVStack gap={3} xstyle={styles.inner}>+ {post.coverImage ? (+ <img+ src={post.coverImage}+ alt={post.coverAlt ?? ''}+ {...stylex.props(styles.cover(feature), styles.coverImg)}+ />+ ) : (+ <div {...stylex.props(styles.cover(feature))} aria-hidden="true" />+ )}+ <XDSVStack gap={2}>+ <XDSHStack gap={1} align="center" xstyle={styles.tagRow}>+ <XDSBadge label={POST_TYPE_LABELS[post.type]} variant="neutral" />+ </XDSHStack>+ <XDSVStack gap={1}>+ <XDSHeading level={feature ? 2 : 3}>{post.title}</XDSHeading>+ <XDSText type="body" color="secondary" xstyle={styles.excerpt}>+ {post.description}+ </XDSText>+ </XDSVStack>+ <AuthorByline+ authors={post.authors}+ date={post.date}+ readingTimeMinutes={post.readingTimeMinutes}+ variant="compact"+ />+ {post.tags.length > 0 ? (+ <XDSHStack gap={1} xstyle={styles.tagRow}>+ {post.tags.map(tag => (+ <XDSBadge key={tag} label={tag} variant="neutral" />+ ))}+ </XDSHStack>+ ) : null}+ </XDSVStack>+ </XDSVStack>+ </XDSClickableCard>+ );+}diff --git a/apps/docsite/src/components/blog/BlogIndex.tsx b/apps/docsite/src/components/blog/BlogIndex.tsxnew file mode 100644index 0000000000..15c50cc670--- /dev/null+++ b/apps/docsite/src/components/blog/BlogIndex.tsx@@ -0,0 +1,134 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file BlogIndex.tsx+ *+ * Client component for the /blog index. Renders a grid of+ * post cards with horizontal post-type filters and no sidebar. The latest post+ * gets a larger "feature" treatment, derived purely from sort order.+ *+ * Filters only show types that actually have published content (issue #2896:+ * "Only show filters/tags publicly when content exists for them").+ *+ * @input posts (BlogPost[], already sorted latest-first), available types+ * @output The interactive blog index UI+ * @position Rendered by app/blog/page.tsx+ */++'use client';++import {useState, useMemo} from 'react';+import * as stylex from '@stylexjs/stylex';+import {XDSText, XDSHeading} from '@xds/core/Text';+import {XDSVStack} from '@xds/core/Layout';+import {XDSSection} from '@xds/core/Section';+import {XDSGrid} from '@xds/core/Grid';+import {XDSCarousel} from '@xds/core/Carousel';+import {XDSTabList, XDSTab} from '@xds/core/TabList';+import type {BlogPost, BlogPostType} from '../../lib/blog/schema';+import {POST_TYPE_LABELS} from '../../lib/blog/schema';+import {BlogCard} from './BlogCard';++const styles = stylex.create({+ header: {+ maxWidth: 720,+ },+ filterRow: {+ marginBottom: 4,+ },+ empty: {+ paddingBlock: 48,+ textAlign: 'center',+ },+});++export interface BlogIndexProps {+ posts: BlogPost[];+ /** Post types that have at least one published post, in canonical order. */+ availableTypes: BlogPostType[];+}++export function BlogIndex({posts, availableTypes}: BlogIndexProps) {+ const [activeType, setActiveType] = useState<'all' | BlogPostType>('all');++ const filtered = useMemo(() => {+ if (activeType === 'all') {+ return posts;+ }+ return posts.filter(p => p.type === activeType);+ }, [posts, activeType]);++ const counts = useMemo(() => {+ const map: Record<string, number> = {all: posts.length};+ for (const t of availableTypes) {+ map[t] = posts.filter(p => p.type === t).length;+ }+ return map;+ }, [posts, availableTypes]);++ // Feature the latest post only in the unfiltered "all" view.+ const showFeature = activeType === 'all' && filtered.length > 0;+ const featurePost = showFeature ? filtered[0] : null;+ const restPosts = showFeature ? filtered.slice(1) : filtered;++ return (+ <XDSSection maxWidth={1100} padding={6}>+ <XDSVStack gap={6}>+ <XDSVStack gap={4} xstyle={styles.header}>+ <XDSHeading level={1} type="display-1">+ Blog+ </XDSHeading>+ <XDSText type="large" weight="normal" color="secondary">+ Notes on building Astryx — releases, guides, stories, and+ perspectives on designing a system for humans and agents.+ </XDSText>+ </XDSVStack>++ {availableTypes.length > 1 ? (+ <XDSCarousel gap={0}>+ <XDSTabList+ value={activeType}+ onChange={v => setActiveType(v as 'all' | BlogPostType)}+ size="md"+ xstyle={styles.filterRow}>+ <XDSTab value="all" label={`All (${counts.all})`} />+ {availableTypes.map(t => (+ <XDSTab+ key={t}+ value={t}+ label={`${POST_TYPE_LABELS[t]} (${counts[t]})`}+ />+ ))}+ </XDSTabList>+ </XDSCarousel>+ ) : null}++ {filtered.length === 0 ? (+ <div {...stylex.props(styles.empty)}>+ <XDSText type="body" color="secondary">+ No posts yet. Check back soon.+ </XDSText>+ </div>+ ) : (+ <XDSVStack gap={6}>+ {featurePost ? (+ <XDSGrid columns={1} gap={4}>+ <BlogCard post={featurePost} feature />+ </XDSGrid>+ ) : null}+ {restPosts.length > 0 ? (+ <XDSGrid+ columns={{minWidth: 320, repeat: 'fill'}}+ gap={4}+ rowGap={6}>+ {restPosts.map(post => (+ <BlogCard key={post.slug} post={post} />+ ))}+ </XDSGrid>+ ) : null}+ </XDSVStack>+ )}+ </XDSVStack>+ </XDSSection>+ );+}diff --git a/apps/docsite/src/content/blog/README.md b/apps/docsite/src/content/blog/README.mdnew file mode 100644index 0000000000..f5a65f876f--- /dev/null+++ b/apps/docsite/src/content/blog/README.md@@ -0,0 +1,141 @@+# Adding a Blog Post++The XDS docsite blog lives at `/blog` (index) and `/blog/<slug>` (post detail).+Posts are human-authored. Adding one is intentionally close to "drop in one+Markdown file."++> **Principle:** metadata organizes the blog; humans write the prose. There is+> no required article template — structure each post however reads best.++## 1. Create the post file++Add a Markdown file under:++```+apps/docsite/src/content/blog/posts/<slug>.md+```++The filename (minus `.md`) becomes the URL slug, e.g.+`introducing-astryx.md` → `/blog/introducing-astryx`.++Start it with YAML frontmatter, then write the body in Markdown:++```md+---+title: 'Designing agent-ready components'+description: 'How Astryx structures component APIs and docs so humans and agents can build with confidence.'+date: '2026-06-17'+type: 'guide'+authors:+ - 'your-handle'+tags:+ - 'AI'+ - 'Components'+ - 'Docs'+---++Write the post in human-authored prose here. Use any structure that fits —+headings, code blocks, lists, links. The body is rendered with `XDSMarkdown`.+```++## 2. Frontmatter reference++### Required++| Field | Type | Notes |+| ------------- | -------------- | -------------------------------------------------------------------------- |+| `title` | string | Article `h1`, card title, default page/social title. |+| `description` | string | Card excerpt, article dek, default meta description. |+| `date` | `YYYY-MM-DD` | Publish date and default sort key (latest first). |+| `type` | enum | One of `update`, `guide`, `design`, `story`, `perspective`, `engineering`. |+| `authors` | string[] | One or more author keys from the author registry (see step 3). |+| `tags` | string[] (1–4) | Topical tags for chips and discovery. |++### Optional++| Field | Type | Notes |+| ------------- | ---------------- | --------------------------------------------------------------- |+| `updatedAt` | `YYYY-MM-DD` | Shows an "Updated" date; does not replace `date`. |+| `draft` | boolean | `true` keeps the post in the repo but out of production output. |+| `coverImage` | string | Path to a custom cover image (e.g. `/blog/<slug>/cover.png`). |+| `coverAlt` | string | **Required when `coverImage` is set.** Alt text for the cover. |+| `relatedDocs` | `{title,href}[]` | Curated related-doc links rendered near the end of the article. |++Required frontmatter is validated at build time (`pnpm generate`) and in tests.+A missing or malformed field fails the build with a clear, slug-prefixed error.++### Post types++| Type | Use for |+| ------------- | ------------------------------------------------------------- |+| `update` | Functionality improvements, releases, new capabilities. |+| `guide` | Practical, educational posts. |+| `design` | Visual and design-craft posts: composition, color, motion. |+| `story` | User stories, community examples, adoption stories. |+| `perspective` | Design-system philosophy, industry observations, opinions. |+| `engineering` | Implementation details, infrastructure, technical deep dives. |++Each post has exactly one `type`. Type filters only appear on the index when+more than one type has published content.++## 3. Add yourself to the author registry (once)++Authors are referenced by key so profile metadata lives in one place:++```+apps/docsite/src/content/blog/authors.ts+```++```ts+export const authors = {+ 'your-handle': {+ name: 'Your Name',+ github: 'your-handle', // avatar + profile link are derived from GitHub+ role: 'Design', // optional+ },+} as const satisfies Record<string, AuthorProfile>;+```++For GitHub-backed authors, the avatar and profile link default to+`https://github.com/<handle>.png` and `https://github.com/<handle>` — no+build-time profile fetching. Then reference the key from your post:++```yaml+authors:+ - 'your-handle'+```++## 4. Cover images++A custom cover is optional. If you omit `coverImage`, the site renders a calm,+deterministic default cover derived from the post `type` and `slug` — so every+post has visual presence without bespoke artwork.++To use a custom cover, put the image under `public/blog/<slug>/` and reference+it with alt text:++```yaml+coverImage: '/blog/<slug>/cover.png'+coverAlt: 'Short description of the image'+```++## 5. Preview locally++```bash+cd apps/docsite+pnpm dev # runs `pnpm generate` first, then starts Next.js+```++Visit `/blog` and `/blog/<slug>`. Drafts (`draft: true`) render in dev but are+excluded from production builds.++## 6. Validate before you push++```bash+pnpm generate # discovers + validates posts into src/generated/blogRegistry.ts+pnpm test # runs blog discovery/validation tests+pnpm typecheck+```++That's it — no index pages to edit, no manual wiring. The post is discovered+automatically and sorted into place by date.diff --git a/apps/docsite/src/content/blog/authors.ts b/apps/docsite/src/content/blog/authors.tsnew file mode 100644index 0000000000..26721ca7eb--- /dev/null+++ b/apps/docsite/src/content/blog/authors.ts@@ -0,0 +1,80 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file authors.ts+ *+ * Shared author registry for the blog. Posts reference authors by key in their+ * frontmatter (`authors: ["xds-team"]`) so profile metadata is defined once.+ *+ * For GitHub-backed authors, set `github` and the site derives a stable avatar+ * and profile link from github.com without fetching profile data at build time.+ * For non-GitHub authors (e.g. a team identity), provide `avatar`/`href`+ * explicitly.+ *+ * @input Referenced by author key from post frontmatter+ * @output Resolved author profiles (name, role, avatar, href) for bylines/cards+ * @position Imported by blog pages and the byline component+ */++export interface AuthorProfile {+ /** Display name shown on cards and bylines. */+ name: string;+ /** GitHub handle. When set, avatar/href default to github.com/<github>. */+ github?: string;+ /** Optional role/title shown under the name. */+ role?: string;+ /** Explicit avatar URL. Defaults to the GitHub avatar when `github` is set. */+ avatar?: string;+ /** Explicit profile URL. Defaults to the GitHub profile when `github` is set. */+ href?: string;+}++export interface ResolvedAuthor extends Omit<AuthorProfile, 'avatar' | 'href'> {+ /** The registry key (also used as a stable React key). */+ key: string;+ /** Always-present avatar URL after resolution. */+ avatar: string;+ /** Profile URL, or null when none can be derived. */+ href: string | null;+}++/**+ * The author registry. Add an entry here, then reference its key from a post's+ * `authors` frontmatter list.+ */+export const authors = {+ cvkxx: {+ name: 'Catherine',+ github: 'cvkxx',+ role: 'Design',+ },+} as const satisfies Record<string, AuthorProfile>;++export type AuthorKey = keyof typeof authors;++/**+ * Resolve an author key to a complete profile, deriving GitHub avatar/href+ * defaults where applicable. Unknown keys resolve to a graceful fallback so a+ * typo in frontmatter never crashes the page (validation surfaces the warning).+ */+export function resolveAuthor(key: string): ResolvedAuthor {+ const profile = (authors as Record<string, AuthorProfile>)[key];++ if (!profile) {+ return {+ key,+ name: key,+ avatar: `https://github.com/${key}.png`,+ href: `https://github.com/${key}`,+ };+ }++ const avatar =+ profile.avatar ??+ (profile.github ? `https://github.com/${profile.github}.png` : '');+ const href =+ profile.href ??+ (profile.github ? `https://github.com/${profile.github}` : null);++ return {key, ...profile, avatar, href};+}diff --git a/apps/docsite/src/content/blog/posts/introducing-astryx.md b/apps/docsite/src/content/blog/posts/introducing-astryx.mdnew file mode 100644index 0000000000..3a24220a70--- /dev/null+++ b/apps/docsite/src/content/blog/posts/introducing-astryx.md@@ -0,0 +1,35 @@+---+title: 'Introducing Astryx by Meta: an open source design system built for how we build now'+description: "Astryx is an open source design system that's AI-fluent and fully customizable without dependencies — now available in Beta."+date: '2026-06-18'+type: 'update'+authors:+ - 'cvkxx'+tags:+ - 'Release'+ - 'AI'+ - 'Design systems'+relatedDocs:+ - title: 'Getting started'+ href: '/docs/getting-started'+ - title: 'Components'+ href: '/components'+---++Open source is how the best ideas in our industry travel. The tools we reach for every day, like React, StyleX, PyTorch, got better because someone decided to share them, and a community made them stronger. Today, we're adding one more.++We're excited to introduce Astryx by Meta, an open source design system that's AI fluent and fully customizable without dependencies. It's a complete, production-ready (and growing) toolkit with 150+ accessible components, brand-level theming, dark mode, ready-to-ship templates, and a CLI – all as one cohesive system, built on React and StyleX.++Astryx isn't new. It's matured within Meta for the last eight years and powers over 13,000 apps, shaped by the designers, engineers, and product teams who depend on it every day. What's new is that it's now yours, too.++## Start anywhere, change anything, and ship faster++Most design systems make you choose. Adopt a big company system and you inherit its brand – your app ends up looking like someone else's product. Reach for copy/paste component collections and you get freedom, but every project forks its own snippets with no shared coherence, no upstream fixes, no upgrade path, and accessibility quietly becomes your problem.++Astryx is built to end that trade-off. The system controls behavior, accessibility, and quality, while themes control how it looks. You customize at the token level (color, typography, radius, motion), so that you can make it unmistakably yours without starting from scratch and without rewrites. Builders can stop reinventing the basics and start shipping ideas faster.++## Built for people and the agents building alongside them++The way we build software is changing, and Astryx is designed for people and the agents building alongside them. Design systems have historically been designed for human consumption but as more code is written by agents, we have to rethink how design systems are structured and the role that they play. Astryx was built ground-up to be AI-operable, opposed to retrofitting existing design systems to play nicely with agent behaviors. It's an open source design system built for how we build in this new world.++Astryx is in Beta and ready for you to build with today. Try it out at [astryxdesign.com](https://astryxdesign.com) and on [GitHub](https://github.com/facebookexperimental/xds).diff --git a/apps/docsite/src/lib/blog/posts.mjs b/apps/docsite/src/lib/blog/posts.mjsnew file mode 100644index 0000000000..fef7afc8e3--- /dev/null+++ b/apps/docsite/src/lib/blog/posts.mjs@@ -0,0 +1,407 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file posts.mjs+ *+ * Build-time blog post discovery, frontmatter parsing, and validation.+ *+ * This module is the single source of truth for how blog posts are read and+ * validated. It is consumed both by the docsite data generator+ * (scripts/generate-data.mjs) and by the test suite (src/__tests__/blog.test.ts),+ * so the same rules apply at build time and in CI.+ *+ * Authoring model (see issue #2896): a blog post is a single Markdown file with+ * YAML frontmatter under src/content/blog/posts/<slug>.md. No bespoke wiring is+ * required — files are discovered automatically and sorted latest-first.+ *+ * Why a hand-written frontmatter parser instead of a YAML dependency: the+ * frontmatter schema is small and fixed (scalars, string sequences, and a+ * sequence of {title, href} maps for relatedDocs). Keeping the parser local+ * avoids adding a dependency to the lockfile of a public repo for a build-only+ * concern, and it is fully covered by tests.+ *+ * @input src/content/blog/posts/<slug>.md files with YAML frontmatter+ * @output Array of validated post objects ({ ...frontmatter, slug, body, readingTimeMinutes })+ * @position Imported by scripts/generate-data.mjs and src/__tests__/blog.test.ts+ */++import * as fs from 'node:fs';+import * as path from 'node:path';++/**+ * The small, stable set of editorial post types used for primary filtering.+ * Keep this in sync with the proposal in issue #2896.+ */+export const POST_TYPES = ['update', 'guide', 'design', 'story', 'perspective', 'engineering'];++/** Maximum number of tags allowed per post (keeps the index calm and scannable). */+export const MAX_TAGS = 4;++// ── Frontmatter parsing ────────────────────────────────────────────────++/** Strip one layer of matching surrounding quotes and unescape common sequences. */+function unquote(value) {+ const trimmed = value.trim();+ if (trimmed.length >= 2) {+ const first = trimmed[0];+ const last = trimmed[trimmed.length - 1];+ if ((first === '"' && last === '"') || (first === "'" && last === "'")) {+ const inner = trimmed.slice(1, -1);+ if (first === '"') {+ return inner.replace(/\\"/g, '"').replace(/\\n/g, '\n').replace(/\\\\/g, '\\');+ }+ return inner;+ }+ }+ return trimmed;+}++/** Coerce an unquoted scalar into boolean/null where appropriate, else string. */+function coerceScalar(raw) {+ const trimmed = raw.trim();+ if (trimmed === 'true') return true;+ if (trimmed === 'false') return false;+ if (trimmed === 'null' || trimmed === '~' || trimmed === '') return null;+ return unquote(trimmed);+}++/** Parse an inline flow sequence: ["a", "b"] or [a, b]. */+function parseInlineSequence(raw) {+ const inner = raw.trim().slice(1, -1).trim();+ if (inner === '') return [];+ // Split on commas not inside quotes.+ const items = [];+ let buf = '';+ let quote = null;+ for (const ch of inner) {+ if (quote) {+ if (ch === quote) quote = null;+ buf += ch;+ } else if (ch === '"' || ch === "'") {+ quote = ch;+ buf += ch;+ } else if (ch === ',') {+ items.push(buf);+ buf = '';+ } else {+ buf += ch;+ }+ }+ if (buf.trim() !== '') items.push(buf);+ return items.map(coerceScalar);+}++/** Indentation width (number of leading spaces) of a line. */+function indentOf(line) {+ const match = line.match(/^( *)/);+ return match ? match[1].length : 0;+}++/**+ * Parse the limited subset of YAML used in blog frontmatter.+ *+ * Supported shapes:+ * key: scalar → string | boolean | null+ * key: ["a", "b"] → string[]+ * key:\n - "a"\n - "b" → string[]+ * key:\n - title: x\n href: y → Array<Record<string,string>>+ *+ * Throws on structurally malformed input (e.g. a list item under a scalar).+ *+ * @param {string} text+ * @returns {Record<string, unknown>}+ */+export function parseYamlFrontmatter(text) {+ const rawLines = text.split('\n');+ // Drop comment-only and blank lines while preserving structure for sequences.+ const lines = rawLines.filter(l => {+ const t = l.trim();+ return t !== '' && !t.startsWith('#');+ });++ const result = {};+ let i = 0;++ while (i < lines.length) {+ const line = lines[i];+ if (indentOf(line) !== 0) {+ throw new Error(`Unexpected indentation at frontmatter line: "${line}"`);+ }+ const keyMatch = line.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);+ if (!keyMatch) {+ throw new Error(`Malformed frontmatter line: "${line}"`);+ }+ const key = keyMatch[1];+ const rest = keyMatch[2];+ i += 1;++ if (rest.trim() !== '') {+ // Inline value on the same line.+ if (rest.trim().startsWith('[')) {+ result[key] = parseInlineSequence(rest);+ } else {+ result[key] = coerceScalar(rest);+ }+ continue;+ }++ // Block value: collect more-indented following lines.+ const block = [];+ while (i < lines.length && indentOf(lines[i]) > 0) {+ block.push(lines[i]);+ i += 1;+ }++ if (block.length === 0) {+ result[key] = null;+ continue;+ }++ // Block sequence (items begin with "- ").+ const itemIndent = indentOf(block[0]);+ const seq = [];+ let j = 0;+ while (j < block.length) {+ const bLine = block[j];+ const trimmed = bLine.trim();+ if (!trimmed.startsWith('- ')) {+ throw new Error(`Expected a "- " sequence item under "${key}", got: "${bLine}"`);+ }+ const afterDash = trimmed.slice(2);+ const mapField = afterDash.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);+ if (mapField && mapField[2].trim() !== '') {+ // Sequence of maps: first field on the dash line, more fields below.+ const obj = {};+ obj[mapField[1]] = coerceScalar(mapField[2]);+ j += 1;+ while (+ j < block.length &&+ !block[j].trim().startsWith('- ') &&+ indentOf(block[j]) > itemIndent+ ) {+ const fld = block[j].trim().match(/^([A-Za-z0-9_-]+):\s*(.*)$/);+ if (!fld) {+ throw new Error(`Malformed map field under "${key}": "${block[j]}"`);+ }+ obj[fld[1]] = coerceScalar(fld[2]);+ j += 1;+ }+ seq.push(obj);+ } else {+ // Sequence of scalars.+ seq.push(coerceScalar(afterDash));+ j += 1;+ }+ }+ result[key] = seq;+ }++ return result;+}++/**+ * Split a raw file into { data, body }. Frontmatter is delimited by leading+ * "---" lines. A file without frontmatter yields empty data and full body.+ *+ * @param {string} raw+ * @returns {{data: Record<string, unknown>, body: string}}+ */+export function parseFrontmatter(raw) {+ const normalized = raw.replace(/^\uFEFF/, '');+ const match = normalized.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);+ if (!match) {+ return {data: {}, body: normalized.trim()};+ }+ return {data: parseYamlFrontmatter(match[1]), body: match[2].trim()};+}++// ── Validation ─────────────────────────────────────────────────────────++function isValidDate(value) {+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;+ const d = new Date(value + 'T00:00:00Z');+ return !Number.isNaN(d.getTime()) && d.toISOString().startsWith(value);+}++/**+ * Validate a parsed post's frontmatter against the v1 schema. Throws an Error+ * with a clear, slug-prefixed message on the first problem found.+ *+ * Returns a normalized data object (defaults applied: draft=false, arrays kept).+ */+export function validatePostFrontmatter(slug, data) {+ const err = msg => {+ throw new Error(`Blog post "${slug}": ${msg}`);+ };++ const requireString = field => {+ if (typeof data[field] !== 'string' || data[field].trim() === '') {+ err(`missing required string field "${field}"`);+ }+ };++ requireString('title');+ requireString('description');+ requireString('date');+ requireString('type');++ if (!isValidDate(data.date)) {+ err(`"date" must be an ISO date (YYYY-MM-DD), got "${data.date}"`);+ }+ if (!POST_TYPES.includes(data.type)) {+ err(`"type" must be one of ${POST_TYPES.join(', ')}; got "${data.type}"`);+ }++ if (!Array.isArray(data.authors) || data.authors.length === 0) {+ err('"authors" must be a non-empty list of author handles');+ }+ for (const a of data.authors) {+ if (typeof a !== 'string' || a.trim() === '') {+ err('every entry in "authors" must be a non-empty string handle');+ }+ }++ if (!Array.isArray(data.tags) || data.tags.length === 0) {+ err('"tags" must be a non-empty list');+ }+ if (data.tags.length > MAX_TAGS) {+ err(`"tags" allows at most ${MAX_TAGS} entries; got ${data.tags.length}`);+ }+ for (const t of data.tags) {+ if (typeof t !== 'string' || t.trim() === '') {+ err('every entry in "tags" must be a non-empty string');+ }+ }++ if (data.coverImage != null && typeof data.coverImage !== 'string') {+ err('"coverImage" must be a string path when provided');+ }+ if (data.coverImage != null) {+ if (typeof data.coverAlt !== 'string' || data.coverAlt.trim() === '') {+ err('"coverAlt" is required (non-empty) when "coverImage" is set');+ }+ }++ if (data.updatedAt != null && !isValidDate(data.updatedAt)) {+ err(`"updatedAt" must be an ISO date (YYYY-MM-DD), got "${data.updatedAt}"`);+ }++ if (data.draft != null && typeof data.draft !== 'boolean') {+ err('"draft" must be a boolean when provided');+ }++ if (data.relatedDocs != null) {+ if (!Array.isArray(data.relatedDocs)) {+ err('"relatedDocs" must be a list when provided');+ }+ for (const doc of data.relatedDocs) {+ if (+ !doc ||+ typeof doc.title !== 'string' ||+ doc.title.trim() === '' ||+ typeof doc.href !== 'string' ||+ doc.href.trim() === ''+ ) {+ err('every "relatedDocs" entry needs non-empty "title" and "href"');+ }+ }+ }++ return {+ title: data.title,+ description: data.description,+ date: data.date,+ type: data.type,+ authors: data.authors,+ tags: data.tags,+ updatedAt: data.updatedAt ?? null,+ draft: data.draft === true,+ coverImage: data.coverImage ?? null,+ coverAlt: data.coverAlt ?? null,+ relatedDocs: data.relatedDocs ?? null,+ };+}++// ── Reading time ───────────────────────────────────────────────────────++/** Estimate reading time in minutes from a markdown body (~200 wpm, min 1). */+export function estimateReadingTime(body) {+ const words = body+ .replace(/```[\s\S]*?```/g, ' ') // drop code fences from the count+ .replace(/[#>*_`~\-]/g, ' ')+ .split(/\s+/)+ .filter(Boolean).length;+ return Math.max(1, Math.round(words / 200));+}++// ── Discovery ──────────────────────────────────────────────────────────++/** Slug from a post filename, e.g. "my-post.md" → "my-post". */+export function slugFromFilename(filename) {+ return filename.replace(/\.mdx?$/, '');+}++/**+ * Discover, parse, and validate all blog posts in a directory.+ *+ * @param {string} postsDir Absolute path to the posts directory.+ * @param {{includeDrafts?: boolean}} [options]+ * @returns Array of validated posts, sorted by date descending (latest first).+ */+export function discoverPosts(postsDir, options = {}) {+ const includeDrafts = options.includeDrafts ?? false;+ if (!fs.existsSync(postsDir)) return [];++ const files = fs+ .readdirSync(postsDir)+ .filter(f => /\.mdx?$/.test(f))+ .sort();++ const posts = [];+ const seenSlugs = new Set();++ for (const file of files) {+ const slug = slugFromFilename(file);+ if (seenSlugs.has(slug)) {+ throw new Error(`Duplicate blog post slug "${slug}" (file ${file})`);+ }+ seenSlugs.add(slug);++ const raw = fs.readFileSync(path.join(postsDir, file), 'utf-8');+ const {data, body} = parseFrontmatter(raw);+ const meta = validatePostFrontmatter(slug, data);++ if (body.trim() === '') {+ throw new Error(`Blog post "${slug}": body is empty`);+ }++ posts.push({+ slug,+ ...meta,+ body,+ readingTimeMinutes: estimateReadingTime(body),+ });+ }++ const visible = includeDrafts ? posts : posts.filter(p => !p.draft);++ visible.sort((a, b) => {+ if (a.date === b.date) return a.slug.localeCompare(b.slug);+ return a.date < b.date ? 1 : -1; // descending+ });++ return visible;+}++/** Distinct post types present in the given posts (ordered by POST_TYPES). */+export function collectTypes(posts) {+ const present = new Set(posts.map(p => p.type));+ return POST_TYPES.filter(t => present.has(t));+}++/** Distinct tags present in the given posts (alphabetical). */+export function collectTags(posts) {+ const tags = new Set();+ for (const p of posts) for (const t of p.tags) tags.add(t);+ return [...tags].sort((a, b) => a.localeCompare(b));+}diff --git a/apps/docsite/src/lib/blog/schema.ts b/apps/docsite/src/lib/blog/schema.tsnew file mode 100644index 0000000000..44c4807bd3--- /dev/null+++ b/apps/docsite/src/lib/blog/schema.ts@@ -0,0 +1,76 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file schema.ts+ *+ * Shared TypeScript types for the blog. These describe the shape of a validated+ * blog post as produced by the build-time generator (src/generated/blogRegistry.ts)+ * and consumed by the blog pages.+ *+ * The runtime discovery/validation rules live in ./posts.mjs (used by the data+ * generator and tests). This file is the type-level mirror of that contract.+ *+ * @input none (type declarations)+ * @output BlogPost and related types+ * @position Imported by src/generated/blogRegistry.ts and blog pages/components+ */++/** The small, stable set of editorial post types used for primary filtering. */+export const POST_TYPES = [+ 'update',+ 'guide',+ 'design',+ 'story',+ 'perspective',+ 'engineering',+] as const;++export type BlogPostType = (typeof POST_TYPES)[number];++/** Human-friendly labels for each post type, used in filters and badges. */+export const POST_TYPE_LABELS: Record<BlogPostType, string> = {+ update: 'Update',+ guide: 'Guide',+ design: 'Design',+ story: 'Story',+ perspective: 'Perspective',+ engineering: 'Engineering',+};++/** A curated related-doc link rendered near the end of an article. */+export interface RelatedDoc {+ title: string;+ href: string;+}++/** A fully validated blog post as emitted into the generated registry. */+export interface BlogPost {+ /** URL-friendly slug derived from the filename (e.g. 'designing-agent-ready-components'). */+ slug: string;+ /** Article h1, card title, and default page/social title. */+ title: string;+ /** Card excerpt, article dek, and default meta description. */+ description: string;+ /** Publish date (ISO YYYY-MM-DD). Default sort key. */+ date: string;+ /** Primary editorial organization/filter. */+ type: BlogPostType;+ /** Author registry keys (resolved to profiles at render time). */+ authors: string[];+ /** 1–4 topical tags for chips and discovery. */+ tags: string[];+ /** Optional updated date for evergreen posts (does not replace `date`). */+ updatedAt: string | null;+ /** Work-in-progress flag; drafts are excluded from production output. */+ draft: boolean;+ /** Optional custom cover image path. */+ coverImage: string | null;+ /** Alt text for the cover image (required when coverImage is set). */+ coverAlt: string | null;+ /** Optional curated related-doc links. */+ relatedDocs: RelatedDoc[] | null;+ /** Markdown body (frontmatter stripped). */+ body: string;+ /** Estimated reading time in minutes. */+ readingTimeMinutes: number;+}