All files / scripts/political-intelligence/render page.ts

100% Statements 64/64
69.23% Branches 18/26
100% Functions 10/10
100% Lines 56/56

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314                                                                        1x 1x   1x 1x   1x 1x 1x 1x   1x           30x                 30x 30x 30x 30x 30x   30x 30x 30x 1890x   30x 30x 30x   30x 30x 420x 1470x   30x 30x   30x                                                         30x           420x         30x           660x       30x           1200x         30x                 30x             30x                     30x           30x 30x 30x                 30x 232x   30x 66x 120x   30x   30x   30x 30x 420x     30x                                             30x                                                                                                                                               150x             30x          
/**
 * @module Infrastructure/PoliticalIntelligence/Render/Page
 * @category Intelligence Operations / Supporting Infrastructure
 * @name Top-level political-intelligence page builder
 *
 * @description
 * Orchestrates a single rendered `political-intelligence_${lang}.html`
 * page. Calls the catalog/daily-streams collectors, slices recent vs.
 * older days, builds the JSON-LD blocks (CollectionPage, ItemList,
 * BreadcrumbList, Organization, WebSite), then composes the body and
 * wraps it in chrome.
 *
 * Round-6 split: extracted from `scripts/generate-political-intelligence.ts`.
 *
 * @author Hack23 AB (Infrastructure Team)
 * @license Apache-2.0
 */
 
import path from 'path';
import { fileURLToPath } from 'url';
 
import type { Language } from '../../types/language.js';
import { LANGUAGE_META, escapeHtml } from '../../sitemap-html/index.js';
import { buildChrome } from '../../render-lib/chrome.js';
import { getFaqItems, FAQ_HEADING } from '../../render-lib/faq-i18n.js';
 
import { collectCatalog } from '../catalog.js';
import { collectDailyDays } from '../daily-streams.js';
import { METHODOLOGY_META } from '../i18n/methodology-i18n.js';
import { TEMPLATE_META } from '../i18n/template-i18n.js';
import { PI_TRANSLATIONS } from '../i18n/page-translations.js';
 
import { renderCatalogGrid } from './grid.js';
import { renderDailyDay } from './daily-day.js';
import { PI_EXTRA_STYLE } from './style.js';
 
const BASE_URL = 'https://riksdagsmonitor.com';
const GITHUB_TREE = 'https://github.com/Hack23/riksdagsmonitor/tree/main';
 
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
 
const ROOT_DIR = path.join(__dirname, '..', '..', '..');
const ANALYSIS_DIR = path.join(ROOT_DIR, 'analysis');
const METHODOLOGIES_DIR = path.join(ANALYSIS_DIR, 'methodologies');
const TEMPLATES_DIR = path.join(ANALYSIS_DIR, 'templates');
 
const LANGUAGES: readonly Language[] = [
  'en', 'sv', 'da', 'no', 'fi', 'de', 'fr', 'es', 'nl', 'ar', 'he', 'ja', 'ko', 'zh',
];
 
/** Map a `Language` file-suffix code to its BCP-47 hreflang code. */
function hreflangCodeOf(lang: Language): string {
  return LANGUAGE_META[lang].hreflang;
}
 
/**
 * Render a complete `political-intelligence_${lang}.html` page for the
 * requested language. Pure with respect to its inputs (the filesystem is
 * read by the catalog/daily-streams collectors but no output is written).
 */
export function generatePoliticalIntelligenceHtml(lang: Language): string {
  const t = PI_TRANSLATIONS[lang];
  const isEnglish = lang === 'en';
  const selfFile = isEnglish ? 'political-intelligence.html' : `political-intelligence_${lang}.html`;
  const indexFile = isEnglish ? 'index.html' : `index_${lang}.html`;
  const sitemapFile = isEnglish ? 'sitemap.html' : `sitemap_${lang}.html`;
 
  const methodologies = collectCatalog(METHODOLOGIES_DIR, 'analysis/methodologies', METHODOLOGY_META, 'methodologies');
  const templates = collectCatalog(TEMPLATES_DIR, 'analysis/templates', TEMPLATE_META, 'templates');
  const days = collectDailyDays();
  const totalArtifacts = days.reduce((a, d) => a + d.totalArtifacts, 0);
 
  const RECENT = 14;
  const recentDays = days.slice(0, RECENT);
  const olderDays = days.slice(RECENT);
 
  const methodologyCardsHtml = renderCatalogGrid(methodologies, t.openOnGithub, lang);
  const templateCardsHtml = renderCatalogGrid(templates, t.openOnGithub, lang);
  const recentDaysHtml = recentDays.map((d) => renderDailyDay(d, t, lang)).join('\n');
  const olderDaysHtml = olderDays.map((d) => renderDailyDay(d, t, lang)).join('\n');
 
  const latestDate = days[0]?.date ?? new Date().toISOString().slice(0, 10);
  const buildIso = new Date().toISOString();
 
  const collectionPageLd = {
    '@context': 'https://schema.org',
    '@type': 'CollectionPage',
    name: `${t.title} β€” Riksdagsmonitor`,
    headline: `${t.title} β€” Riksdagsmonitor`,
    description: t.metaDescription,
    keywords: t.metaKeywords,
    inLanguage: hreflangCodeOf(lang),
    url: `${BASE_URL}/${selfFile}`,
    mainEntityOfPage: `${BASE_URL}/${selfFile}`,
    dateModified: latestDate,
    dateCreated: '2026-04-01',
    isPartOf: { '@id': `${BASE_URL}/#website` },
    publisher: {
      '@type': 'Organization', name: 'Hack23 AB', url: 'https://www.hack23.com',
      logo: { '@type': 'ImageObject', url: `${BASE_URL}/images/logo.png` },
    },
    about: [
      { '@type': 'Thing', name: 'Swedish Parliament political intelligence' },
      { '@type': 'Thing', name: 'OSINT methodologies' },
      { '@type': 'Thing', name: 'Political risk assessment' },
    ],
    hasPart: [
      { '@type': 'CreativeWork', name: t.methodologies, url: `${GITHUB_TREE}/analysis/methodologies`, description: t.methodologiesDesc },
      { '@type': 'CreativeWork', name: t.templates, url: `${GITHUB_TREE}/analysis/templates`, description: t.templatesDesc },
      { '@type': 'Dataset', name: t.dailyArtifacts, url: `${GITHUB_TREE}/analysis/daily`, description: t.dailyArtifactsDesc },
    ],
  };
 
  const recentDaysItemList = recentDays.length > 0 ? {
    '@context': 'https://schema.org',
    '@type': 'ItemList',
    name: t.recentDays,
    numberOfItems: recentDays.length,
    itemListOrder: 'https://schema.org/ItemListOrderDescending',
    itemListElement: recentDays.map((d, i) => ({
      '@type': 'ListItem', position: i + 1, name: d.date, url: d.githubUrl,
    })),
  } : null;
 
  const methodologiesItemList = methodologies.length > 0 ? {
    '@context': 'https://schema.org',
    '@type': 'ItemList',
    '@id': `${BASE_URL}/${selfFile}#methodologies-itemlist`,
    name: t.methodologies,
    numberOfItems: methodologies.length,
    itemListElement: methodologies.map((m, i) => ({
      '@type': 'ListItem', position: i + 1, name: m.title, url: m.githubUrl,
    })),
  } : null;
  const templatesItemList = templates.length > 0 ? {
    '@context': 'https://schema.org',
    '@type': 'ItemList',
    '@id': `${BASE_URL}/${selfFile}#templates-itemlist`,
    name: t.templates,
    numberOfItems: templates.length,
    itemListElement: templates.map((tpl, i) => ({
      '@type': 'ListItem', position: i + 1, name: tpl.title, url: tpl.githubUrl,
    })),
  } : null;
 
  const breadcrumbLd = {
    '@context': 'https://schema.org',
    '@type': 'BreadcrumbList',
    itemListElement: [
      { '@type': 'ListItem', position: 1, name: t.home, item: `${BASE_URL}/${indexFile}` },
      { '@type': 'ListItem', position: 2, name: t.title, item: `${BASE_URL}/${selfFile}` },
    ],
  };
 
  const organizationLd = {
    '@context': 'https://schema.org',
    '@type': 'Organization',
    name: 'Hack23 AB',
    url: 'https://www.hack23.com',
    logo: `${BASE_URL}/images/android-chrome-512x512.png`,
  };
  const websiteLd = {
    '@context': 'https://schema.org',
    '@type': 'WebSite',
    '@id': `${BASE_URL}/#website`,
    name: 'Riksdagsmonitor',
    url: BASE_URL,
    description: 'Swedish Parliament Intelligence Platform - Real-time monitoring, coalition predictions, and comprehensive political analysis',
    inLanguage: ['en', 'sv', 'da', 'nb', 'fi', 'de', 'fr', 'es', 'nl', 'ar', 'he', 'ja', 'ko', 'zh'],
    publisher: { '@type': 'Organization', name: 'Hack23 AB', url: 'https://www.hack23.com' },
  };
 
  const jsonLd: unknown[] = [
    organizationLd,
    websiteLd,
    collectionPageLd,
    breadcrumbLd,
  ];
  Eif (recentDaysItemList) jsonLd.push(recentDaysItemList);
  Eif (methodologiesItemList) jsonLd.push(methodologiesItemList);
  Eif (templatesItemList) jsonLd.push(templatesItemList);
 
  // The `t.metaKeywords` seed is already localized per language. The
  // methodology and template filenames are stored under their English
  // slugs (e.g. `Admiralty Rubric`, `Calibration Ledger`) β€” appending
  // them verbatim into a non-EN keyword string leaks English titles
  // into the `<meta keywords>` and `news_keywords` of every localized
  // PI page. Only the EN page should mix the catalog titles into its
  // keyword string; other locales ship the localized seed alone.
  const keywordSet = new Set<string>(
    t.metaKeywords.split(',').map((s) => s.trim()).filter(Boolean),
  );
  if (isEnglish) {
    for (const m of methodologies) keywordSet.add(m.title);
    for (const tpl of templates) keywordSet.add(tpl.title);
  }
  const aggregatedKeywords = Array.from(keywordSet).slice(0, 30).join(', ');
 
  const faqItems = getFaqItems('politicalIntelligence', lang);
 
  const hreflangAlternates: Partial<Record<Language, string>> = {};
  for (const l of LANGUAGES) {
    hreflangAlternates[l] = l === 'en' ? 'political-intelligence.html' : `political-intelligence_${l}.html`;
  }
 
  const chrome = buildChrome({
    lang,
    title: t.title,
    description: t.metaDescription,
    keywords: aggregatedKeywords,
    canonicalPath: selfFile,
    hreflangAlternates,
    defaultAlternateBase: 'political-intelligence.html',
    ogType: 'website',
    section: t.title,
    publishedIso: `${latestDate}T00:00:00Z`,
    modifiedIso: buildIso,
    rssHref: '/rss.xml',
    breadcrumb: [
      { label: t.home, href: indexFile },
      { label: t.title },
    ],
    jsonLd,
    extraStyle: PI_EXTRA_STYLE,
    faqItems,
    speakableSelectors: ['.pi-page-hero h1', '.pi-page-hero .pi-subtitle'],
  });
 
  const body = `    <div class="pi-container">
        <header class="pi-page-hero">
            <h1><span aria-hidden="true">🧠</span> ${escapeHtml(t.title)}</h1>
            <p class="pi-subtitle">${escapeHtml(t.subtitle)}</p>
            <p class="pi-intro">${escapeHtml(t.intro)}</p>
            <div class="pi-stats" role="list">
                <span class="pi-stat" role="listitem"><strong>${methodologies.length}</strong> ${escapeHtml(t.methodologies)}</span>
                <span class="pi-stat" role="listitem"><strong>${templates.length}</strong> ${escapeHtml(t.templates)}</span>
                <span class="pi-stat" role="listitem"><strong>${days.length}</strong> ${escapeHtml(t.dailyArtifacts)}</span>
                <span class="pi-stat" role="listitem"><strong>${totalArtifacts}</strong> ${escapeHtml(t.artifacts)}</span>
            </div>
        </header>
 
        <nav class="toc-nav" aria-label="${escapeHtml(t.quickJumpTo)}">
            <h2>${escapeHtml(t.quickJumpTo)}</h2>
            <ul class="toc-list">
                <li><a href="#methodologies"><span aria-hidden="true">πŸ“š</span> ${escapeHtml(t.methodologies)}</a></li>
                <li><a href="#templates"><span aria-hidden="true">πŸ“‹</span> ${escapeHtml(t.templates)}</a></li>
                <li><a href="#daily"><span aria-hidden="true">πŸ“…</span> ${escapeHtml(t.dailyArtifacts)}</a></li>
                <li><a href="/${sitemapFile}"><span aria-hidden="true">πŸ—ΊοΈ</span> ${escapeHtml(t.sitemap)}</a></li>
            </ul>
        </nav>
 
        <section id="methodologies" class="pi-section">
            <div class="pi-section-header">
                <h2><span aria-hidden="true">πŸ“š</span> ${escapeHtml(t.methodologies)}</h2>
                <span class="pi-section-link"><a href="${GITHUB_TREE}/analysis/methodologies" target="_blank" rel="noopener noreferrer">${escapeHtml(t.browseDirectoryOnGithub)} <span aria-hidden="true">β†—</span></a></span>
            </div>
            <p class="pi-section-desc">${escapeHtml(t.methodologiesDesc)}</p>
            <div class="pi-grid">
${methodologyCardsHtml}
            </div>
        </section>
 
        <section id="templates" class="pi-section">
            <div class="pi-section-header">
                <h2><span aria-hidden="true">πŸ“‹</span> ${escapeHtml(t.templates)}</h2>
                <span class="pi-section-link"><a href="${GITHUB_TREE}/analysis/templates" target="_blank" rel="noopener noreferrer">${escapeHtml(t.browseDirectoryOnGithub)} <span aria-hidden="true">β†—</span></a></span>
            </div>
            <p class="pi-section-desc">${escapeHtml(t.templatesDesc)}</p>
            <div class="pi-grid">
${templateCardsHtml}
            </div>
        </section>
 
        <section id="daily" class="pi-section">
            <div class="pi-section-header">
                <h2><span aria-hidden="true">πŸ“…</span> ${escapeHtml(t.dailyArtifacts)}</h2>
                <span class="pi-section-link"><a href="${GITHUB_TREE}/analysis/daily" target="_blank" rel="noopener noreferrer">${escapeHtml(t.browseAllDays)} <span aria-hidden="true">β†—</span></a></span>
            </div>
            <p class="pi-section-desc">${escapeHtml(t.dailyArtifactsDesc)}</p>
 
            <h3 style="font-family: var(--font-heading, 'Orbitron', sans-serif); color: var(--primary-yellow, #ffbe0b); font-size: 1.1rem; margin-top: 1.5rem;">${escapeHtml(t.recentDays)}</h3>
${recentDaysHtml}
${olderDays.length > 0 ? `
            <details class="pi-older-details" id="pi-older-days-wrapper">
              <summary class="pi-older-toggle">
                <span aria-hidden="true">πŸ•°οΈ</span> ${escapeHtml(t.olderDays)} (${olderDays.length}) β€” ${escapeHtml(t.showMore)}
              </summary>
              <div id="pi-older-days" class="pi-older-content">
${olderDaysHtml}
              </div>
            </details>` : ''}
        </section>
 
        <!-- FAQ section (round-7 SEO uplift) β€” visible companion to the
             auto-emitted FAQPage JSON-LD; uses native <details>/<summary>
             so progressive disclosure stays crawlable without JS. -->
        <section id="faq" class="pi-section pi-faq" aria-labelledby="pi-faq-heading">
            <div class="pi-section-header">
              <h2 id="pi-faq-heading"><span aria-hidden="true">❓</span> ${escapeHtml(FAQ_HEADING[lang])}</h2>
            </div>
${faqItems.map((f) => `            <details class="pi-faq-item">
              <summary>${escapeHtml(f.question)}</summary>
              <p>${escapeHtml(f.answer)}</p>
            </details>`).join('\n')}
        </section>
    </div>`;
 
  return `${chrome.head}
${chrome.headerHtml}
${body}
${chrome.footerHtml}`;
}