feat(seo): implement FAQPage schema, sub-sitemaps and local Lalezar WOFF2 font (SEO-P1-07, SEO-P1-10, SEO-P2-16)
Deploy Canina / deploy (push) Successful in 2m10s
Deploy Canina / deploy (push) Successful in 2m10s
- SEO-P1-07: extract FAQs and accordion items from blog content and inject JSON-LD FAQPage schema - SEO-P1-10: add dynamic sub-sitemaps /sitemap-blog.xml and /sitemap-wiki.xml and register in robots.ts - SEO-P2-16: host Lalezar font locally as optimized WOFF2 with preload enabled in lib/fonts.ts - Add full regression test suites with 100% pass rate
This commit is contained in:
1 parent
5cf2863987
commit
f8f9329c50
11 files changed
+556
-6
No files matched your search
@@ -0,0 +1,104 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import React from 'react';
|
||||
import BlogPostPage from './page';
|
||||
|
||||
vi.mock('../../../lib/seo', () => ({
|
||||
getSeoConfig: vi.fn().mockResolvedValue({
|
||||
brandNameFa: 'کنینا ایران',
|
||||
canonicalBaseUrl: 'https://canina.ir',
|
||||
ogImageUrl: '/assets/og.jpg',
|
||||
defaultMetaDescription: 'توضیحات پیشفرض',
|
||||
titleSeparator: '|',
|
||||
titlePosition: 'suffix',
|
||||
}),
|
||||
formatPageTitle: vi.fn((title) => `${title} | کنینا ایران`),
|
||||
}));
|
||||
|
||||
vi.mock('../../../components/BlogPostClient', () => ({
|
||||
default: () => <div data-testid="blog-post-client" />,
|
||||
}));
|
||||
|
||||
describe('BlogPostPage FAQPage Schema injection (SEO-P1-07)', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubEnv('INTERNAL_API_URL', 'http://backend:3000/api');
|
||||
vi.stubEnv('NEXT_PUBLIC_SITE_URL', 'https://canina.ir');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
it('injects FAQPage JSON-LD schema when article contains questions and answers', async () => {
|
||||
const blogData = {
|
||||
slug: 'joint-health',
|
||||
title: 'سلامت مفاصل سگ',
|
||||
content: `
|
||||
<article>
|
||||
<p>مقدمهای درباره مفاصل سگ.</p>
|
||||
<details>
|
||||
<summary>آیا این مکمل برای سگ مسن مناسب است؟</summary>
|
||||
<p>بله، بسیار توصیه میشود و روند تخریب مفصل را کند میکند.</p>
|
||||
</details>
|
||||
</article>
|
||||
`,
|
||||
createdAt: '2026-01-01',
|
||||
publishedAt: '2026-01-01',
|
||||
};
|
||||
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => blogData,
|
||||
})
|
||||
);
|
||||
|
||||
const jsx = await BlogPostPage({ params: Promise.resolve({ slug: 'joint-health' }) });
|
||||
expect(jsx).toBeDefined();
|
||||
|
||||
// Verify scripts in JSX tree
|
||||
const scripts = React.Children.toArray(jsx.props.children).filter(
|
||||
(child: any) => child?.type === 'script' && child?.props?.['type'] === 'application/ld+json'
|
||||
);
|
||||
|
||||
// There should be 3 schemas: Article, Breadcrumb, and FAQPage
|
||||
expect(scripts.length).toBe(3);
|
||||
|
||||
const faqScript: any = scripts.find((s: any) => s.props['data-testid'] === 'faq-schema');
|
||||
expect(faqScript).toBeDefined();
|
||||
|
||||
const faqJson = JSON.parse(faqScript.props.dangerouslySetInnerHTML.__html);
|
||||
expect(faqJson['@type']).toBe('FAQPage');
|
||||
expect(faqJson.mainEntity).toHaveLength(1);
|
||||
expect(faqJson.mainEntity[0].name).toBe('آیا این مکمل برای سگ مسن مناسب است؟');
|
||||
});
|
||||
|
||||
it('does not inject FAQPage schema when article does not have FAQs', async () => {
|
||||
const blogData = {
|
||||
slug: 'nutrition',
|
||||
title: 'تغذیه سگ',
|
||||
content: '<p>یک مقاله ساده بدون سوال و جواب یا آکاردئون.</p>',
|
||||
createdAt: '2026-01-01',
|
||||
publishedAt: '2026-01-01',
|
||||
};
|
||||
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => blogData,
|
||||
})
|
||||
);
|
||||
|
||||
const jsx = await BlogPostPage({ params: Promise.resolve({ slug: 'nutrition' }) });
|
||||
const scripts = React.Children.toArray(jsx.props.children).filter(
|
||||
(child: any) => child?.type === 'script' && child?.props?.['type'] === 'application/ld+json'
|
||||
);
|
||||
|
||||
// Only Article and Breadcrumb schemas
|
||||
expect(scripts.length).toBe(2);
|
||||
const faqScript = scripts.find((s: any) => s.props['data-testid'] === 'faq-schema');
|
||||
expect(faqScript).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import BlogPostClient from "../../../components/BlogPostClient";
|
||||
import { getSeoConfig, formatPageTitle } from "../../../lib/seo";
|
||||
import { safeJsonLd } from "../../../lib/schema";
|
||||
import { sanitizeBlogHtml } from "../../../lib/sanitizeBlogHtml";
|
||||
import { extractFaqsFromHtml, generateFAQPageSchema } from "../../../lib/extractFaqs";
|
||||
|
||||
function safeIso(val: any, fallback?: string): string | undefined {
|
||||
if (!val) return fallback;
|
||||
@@ -82,7 +83,7 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
|
||||
const ogTitle = blog.ogTitle || title;
|
||||
const ogDesc = blog.ogDescription || description;
|
||||
|
||||
const isStaging =
|
||||
const isStaging =
|
||||
process.env.NEXT_PUBLIC_APP_ENV === 'staging' ||
|
||||
process.env.NODE_ENV !== 'production' ||
|
||||
siteUrl.includes('stage') ||
|
||||
@@ -267,6 +268,10 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
|
||||
],
|
||||
};
|
||||
|
||||
// SEO-P1-07: Auto-detect and inject FAQPage Schema when article content contains Q&As or accordion structures
|
||||
const extractedFaqs = extractFaqsFromHtml(blog.content || '');
|
||||
const faqPageSchema = generateFAQPageSchema(extractedFaqs);
|
||||
|
||||
return (
|
||||
<>
|
||||
<script
|
||||
@@ -277,6 +282,13 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
|
||||
type="application/ld+json"
|
||||
dangerouslySetInnerHTML={{ __html: safeJsonLd(breadcrumbJsonLd) }}
|
||||
/>
|
||||
{faqPageSchema && (
|
||||
<script
|
||||
type="application/ld+json"
|
||||
data-testid="faq-schema"
|
||||
dangerouslySetInnerHTML={{ __html: safeJsonLd(faqPageSchema) }}
|
||||
/>
|
||||
)}
|
||||
<BlogPostClient
|
||||
blog={blog}
|
||||
publishedDate={publishedDate}
|
||||
|
||||
@@ -37,6 +37,8 @@ export default function robots(): MetadataRoute.Robots {
|
||||
`${baseUrl}/sitemap.xml`,
|
||||
`${baseUrl}/sitemap-products.xml`,
|
||||
`${baseUrl}/sitemap-categories.xml`,
|
||||
`${baseUrl}/sitemap-blog.xml`,
|
||||
`${baseUrl}/sitemap-wiki.xml`,
|
||||
],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
export const revalidate = 3600; // Revalidate every hour
|
||||
|
||||
type SitemapBlog = {
|
||||
slug: string;
|
||||
noIndex?: boolean;
|
||||
status: string;
|
||||
updatedAt?: string;
|
||||
createdAt?: string;
|
||||
featured?: boolean;
|
||||
title?: string;
|
||||
imageUrl?: string;
|
||||
ogImage?: string;
|
||||
};
|
||||
|
||||
export async function GET() {
|
||||
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://canina.ir';
|
||||
const apiUrl =
|
||||
process.env.INTERNAL_API_URL || process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4001/api';
|
||||
const normalizedApiUrl = apiUrl.replace(/\/$/, '');
|
||||
const apiBase = normalizedApiUrl.endsWith('/api') ? normalizedApiUrl : `${normalizedApiUrl}/api`;
|
||||
|
||||
const blogRoutes: SitemapBlog[] = [];
|
||||
|
||||
try {
|
||||
let page = 1;
|
||||
let lastPage = 1;
|
||||
do {
|
||||
const res = await fetch(`${apiBase}/blogs?page=${page}&limit=20`, { cache: 'no-store' });
|
||||
if (!res.ok) throw new Error(`Blog sitemap request failed: ${res.status}`);
|
||||
const data = await res.json();
|
||||
const blogsList: SitemapBlog[] = data.data || [];
|
||||
if (!blogsList.length) break;
|
||||
|
||||
const validBlogs = blogsList.filter((b) => !b.noIndex && b.status === 'PUBLISHED');
|
||||
blogRoutes.push(...validBlogs);
|
||||
|
||||
lastPage = Number(data.meta?.lastPage) || 1;
|
||||
page += 1;
|
||||
} while (page <= lastPage);
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch blogs for sitemap-blog.xml:', err);
|
||||
}
|
||||
|
||||
const urlsXml = blogRoutes
|
||||
.map((blog) => {
|
||||
const loc = `${baseUrl}/blog/${encodeURIComponent(blog.slug)}`;
|
||||
const lastmod = blog.updatedAt
|
||||
? new Date(blog.updatedAt).toISOString()
|
||||
: blog.createdAt
|
||||
? new Date(blog.createdAt).toISOString()
|
||||
: new Date().toISOString();
|
||||
const priority = blog.featured ? '0.9' : '0.7';
|
||||
const primaryImg = blog.ogImage || blog.imageUrl;
|
||||
const title = blog.title || 'مقاله وبلاگ تخصصی کنینا';
|
||||
|
||||
const imageTag = primaryImg
|
||||
? `\n <image:image>\n <image:loc>${
|
||||
primaryImg.startsWith('http') ? primaryImg : `${baseUrl}${primaryImg.startsWith('/') ? '' : '/'}${primaryImg}`
|
||||
}</image:loc>\n <image:title><![CDATA[${title}]]></image:title>\n </image:image>`
|
||||
: '';
|
||||
|
||||
return ` <url>\n <loc>${loc}</loc>\n <lastmod>${lastmod}</lastmod>\n <changefreq>weekly</changefreq>\n <priority>${priority}</priority>${imageTag}\n </url>`;
|
||||
})
|
||||
.join('\n');
|
||||
|
||||
const xmlContent = `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"\n xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">\n${urlsXml}\n</urlset>`;
|
||||
|
||||
return new NextResponse(xmlContent, {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': 'application/xml; charset=utf-8',
|
||||
'Cache-Control': 'public, max-age=3600, s-maxage=3600, stale-while-revalidate=86400',
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
export const revalidate = 86400; // Revalidate daily
|
||||
|
||||
type SitemapWikiTerm = {
|
||||
key: string;
|
||||
term: string;
|
||||
definition?: string;
|
||||
updatedAt?: string;
|
||||
createdAt?: string;
|
||||
};
|
||||
|
||||
export async function GET() {
|
||||
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://canina.ir';
|
||||
const apiUrl =
|
||||
process.env.INTERNAL_API_URL || process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4001/api';
|
||||
const normalizedApiUrl = apiUrl.replace(/\/$/, '');
|
||||
const apiBase = normalizedApiUrl.endsWith('/api') ? normalizedApiUrl : `${normalizedApiUrl}/api`;
|
||||
|
||||
const wikiRoutes: SitemapWikiTerm[] = [];
|
||||
|
||||
try {
|
||||
let page = 1;
|
||||
let lastPage = 1;
|
||||
do {
|
||||
const res = await fetch(`${apiBase}/wiki?page=${page}&limit=50`, { cache: 'no-store' });
|
||||
if (!res.ok) throw new Error(`Wiki sitemap request failed: ${res.status}`);
|
||||
const data = await res.json();
|
||||
const wikiList: SitemapWikiTerm[] = data.data || [];
|
||||
if (!wikiList.length) break;
|
||||
|
||||
wikiRoutes.push(...wikiList);
|
||||
|
||||
lastPage = Number(data.meta?.lastPage) || 1;
|
||||
page += 1;
|
||||
} while (page <= lastPage);
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch wiki terms for sitemap-wiki.xml:', err);
|
||||
}
|
||||
|
||||
const urlsXml = wikiRoutes
|
||||
.map((item) => {
|
||||
const loc = `${baseUrl}/wiki/${encodeURIComponent(item.key)}`;
|
||||
const lastmod = item.updatedAt
|
||||
? new Date(item.updatedAt).toISOString()
|
||||
: item.createdAt
|
||||
? new Date(item.createdAt).toISOString()
|
||||
: new Date().toISOString();
|
||||
|
||||
return ` <url>\n <loc>${loc}</loc>\n <lastmod>${lastmod}</lastmod>\n <changefreq>weekly</changefreq>\n <priority>0.8</priority>\n </url>`;
|
||||
})
|
||||
.join('\n');
|
||||
|
||||
const xmlContent = `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urlsXml}\n</urlset>`;
|
||||
|
||||
return new NextResponse(xmlContent, {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': 'application/xml; charset=utf-8',
|
||||
'Cache-Control': 'public, max-age=86400, s-maxage=86400, stale-while-revalidate=604800',
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import robots from './robots';
|
||||
import { GET as getBlogSitemap } from './sitemap-blog.xml/route';
|
||||
import { GET as getWikiSitemap } from './sitemap-wiki.xml/route';
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
describe('Sub-sitemaps and robots.ts integration (SEO-P1-10)', () => {
|
||||
it('registers sitemap-blog.xml and sitemap-wiki.xml in robots.ts', () => {
|
||||
vi.stubEnv('NEXT_PUBLIC_APP_ENV', 'production');
|
||||
vi.stubEnv('NODE_ENV', 'production');
|
||||
vi.stubEnv('NEXT_PUBLIC_SITE_URL', 'https://canina.ir');
|
||||
|
||||
const config = robots();
|
||||
const sitemaps = Array.isArray(config.sitemap) ? config.sitemap : [config.sitemap];
|
||||
|
||||
expect(sitemaps).toContain('https://canina.ir/sitemap.xml');
|
||||
expect(sitemaps).toContain('https://canina.ir/sitemap-products.xml');
|
||||
expect(sitemaps).toContain('https://canina.ir/sitemap-categories.xml');
|
||||
expect(sitemaps).toContain('https://canina.ir/sitemap-blog.xml');
|
||||
expect(sitemaps).toContain('https://canina.ir/sitemap-wiki.xml');
|
||||
});
|
||||
|
||||
it('generates sitemap-blog.xml correctly with published blogs and image tags', async () => {
|
||||
vi.stubEnv('INTERNAL_API_URL', 'http://backend:3000/api');
|
||||
vi.stubEnv('NEXT_PUBLIC_SITE_URL', 'https://canina.ir');
|
||||
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
data: [
|
||||
{
|
||||
slug: 'puppy-nutrition',
|
||||
title: 'تغذیه توله سگ',
|
||||
status: 'PUBLISHED',
|
||||
updatedAt: '2026-10-10T12:00:00.000Z',
|
||||
featured: true,
|
||||
imageUrl: '/uploads/puppy.jpg',
|
||||
},
|
||||
{
|
||||
slug: 'hidden-blog',
|
||||
title: 'مقاله پیشنویس',
|
||||
status: 'DRAFT',
|
||||
},
|
||||
],
|
||||
meta: { lastPage: 1 },
|
||||
}),
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const res = await getBlogSitemap();
|
||||
expect(res.status).toBe(200);
|
||||
const xml = await res.text();
|
||||
|
||||
expect(xml).toContain('<loc>https://canina.ir/blog/puppy-nutrition</loc>');
|
||||
expect(xml).toContain('<priority>0.9</priority>');
|
||||
expect(xml).toContain('<image:loc>https://canina.ir/uploads/puppy.jpg</image:loc>');
|
||||
expect(xml).toContain('تغذیه توله سگ');
|
||||
expect(xml).not.toContain('hidden-blog');
|
||||
});
|
||||
|
||||
it('generates sitemap-wiki.xml correctly with scientific terms', async () => {
|
||||
vi.stubEnv('INTERNAL_API_URL', 'http://backend:3000/api');
|
||||
vi.stubEnv('NEXT_PUBLIC_SITE_URL', 'https://canina.ir');
|
||||
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
data: [
|
||||
{
|
||||
key: 'omega-3',
|
||||
term: 'امگا ۳',
|
||||
updatedAt: '2026-09-01T10:00:00.000Z',
|
||||
},
|
||||
],
|
||||
meta: { lastPage: 1 },
|
||||
}),
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const res = await getWikiSitemap();
|
||||
expect(res.status).toBe(200);
|
||||
const xml = await res.text();
|
||||
|
||||
expect(xml).toContain('<loc>https://canina.ir/wiki/omega-3</loc>');
|
||||
expect(xml).toContain('<priority>0.8</priority>');
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user