import { readFileSync, writeFileSync, mkdirSync, existsSync } from "fs"; import { resolve, dirname } from "path"; import { fileURLToPath } from "url"; const __dirname = dirname(fileURLToPath(import.meta.url)); async function getProducts() { try { const response = await fetch('https://pvh.projects.rustprogersteam.ru/api/productList'); const data = await response.json(); if (Array.isArray(data)) { console.log(`✅ Загружено ${data.length} товаров`); return data; } return []; } catch (error) { console.error('Ошибка:', error.message); return []; } } // Получаем товары const products = await getProducts(); const distPath = resolve(__dirname, "../dist"); const indexHtmlPath = resolve(distPath, "index.html"); if (!existsSync(indexHtmlPath)) { console.error("❌ Сначала запустите npm run build"); process.exit(1); } // Читаем исходный HTML let baseHtml = readFileSync(indexHtmlPath, "utf-8"); // ============================================ // ФУНКЦИИ ДЛЯ ГЕНЕРАЦИИ КОНТЕНТА // ============================================ function escapeHtml(text) { if (!text) return ''; return String(text) .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"') .replace(/'/g, '''); } // Генерация страницы товара function generateProductPage(product) { return `

${escapeHtml(product.full_name)}

${escapeHtml(product.description || 'Описание отсутствует')}

Артикул: ${product.id}

`; } // Генерация главной страницы function generateHomePage(products) { const topProducts = products.slice(0, 6).map(product => `

${escapeHtml(product.full_name || `Товар ${product.id}`)}

Подробнее
`).join(''); return `

Добро пожаловать в магазин труб RK PLASTIC technology!

Широкий выбор канализационных труб, фитингов, колен, отводов, муфт, переходов, заглушек, тройников и ревизий.

Популярные товары

${topProducts}
Перейти в каталог
`; } // Генерация страницы каталога function generateCatalogPage(products) { const allProducts = products.map(product => `

${escapeHtml(product.full_name || `Товар ${product.id}`)}

${escapeHtml((product.description || '').slice(0, 150))}...

Подробнее
`).join(''); return `

Каталог товаров

${allProducts}
`; } // Генерация страницы "О нас" function generateAboutPage() { return `

О магазине

Мы занимаемся продажей качественных труб и остальных комплектующих для канализации.

Наши преимущества:

`; } const routes = [ { path: "/", title: "Магазин труб - Главная", description: "Купить канализационные трубы, фитинги и комплектующие по низким ценам.", getContent: () => generateHomePage(products) }, { path: "/products", title: "Каталог труб и фитингов для канализации", description: "Широкий выбор канализационных труб ПВХ, фитингов, тройников, переходов, колен.", getContent: () => generateCatalogPage(products) }, { path: "/about", title: "О магазине труб - Доставка и гарантия", description: "Информация о нашей компании. Как мы работаем, условия доставки.", getContent: () => generateAboutPage() } ]; // Добавляем страницы товаров for (const product of products) { routes.push({ path: `/product/${product.slug || product.id}`, title: product.full_name, description: (product.description || ''), getContent: () => generateProductPage(product) }); } console.log(`\n📄 Всего страниц для генерации: ${routes.length}\n`); let successCount = 0; for (const route of routes) { try { // Генерируем контент для этой страницы const pageContent = route.getContent(); // Вставляем контент в #root let html = baseHtml; // Меняем title html = html.replace(/.*?<\/title>/, `<title>${escapeHtml(route.title)}`); // Меняем meta description html = html.replace(//, ``); // Вставляем контент в #root (ВАЖНО!) html = html.replace('
', `
${pageContent}
`); // Добавляем Open Graph теги html = html.replace( "", ` ` ); // Определяем путь для сохранения let outputPath; if (route.path === "/") { outputPath = indexHtmlPath; } else { const routeDir = resolve(distPath, route.path.substring(1)); if (!existsSync(routeDir)) { mkdirSync(routeDir, { recursive: true }); } outputPath = resolve(routeDir, "index.html"); } writeFileSync(outputPath, html); console.log(`✅ ${route.path}`); successCount++; } catch (error) { console.error(`❌ Ошибка при генерации ${route.path}:`, error.message); } } const urls = routes.map(route => ({ url: route.path, lastmod: new Date().toISOString().split('T')[0], priority: route.path === '/' ? 1.0 : route.path.startsWith('/product') ? 0.8 : 0.7 })); function generateSitemap(urls, baseUrl) { return ` ${urls.map(item => ` ${baseUrl}${item.url} ${item.lastmod} ${item.priority} `).join('\n')} `; } const sitemapContent = generateSitemap(urls, 'https://pvh.projects.rustprogersteam.ru'); const sitemapPath = resolve(distPath, 'sitemap.xml'); writeFileSync(sitemapPath, sitemapContent); console.log(`\n✨ Готово! Сгенерировано ${successCount} страниц.`); console.log(`🗺️ Sitemap: ${sitemapPath}`);