diff --git a/.github/workflows/clean-urls.yml b/.github/workflows/clean-urls.yml new file mode 100644 index 0000000..575bad7 --- /dev/null +++ b/.github/workflows/clean-urls.yml @@ -0,0 +1,50 @@ +name: Clean URLs + +on: + pull_request: + push: + branches: [main] + workflow_dispatch: + inputs: + deploy: + description: 'Publish _site only after an approved switch to Pages GitHub Actions' + type: boolean + default: false + +permissions: + contents: read + +concurrency: + group: clean-urls-${{ github.ref }} + cancel-in-progress: false + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 20 + - run: npm run build + - run: npm run test:urls + - run: npm run validate:urls + - run: npm run validate:events + - uses: actions/upload-pages-artifact@v4 + with: + path: _site + + # Raw main/root publication remains supported until an approved Pages cutover. + deploy: + if: github.event_name == 'workflow_dispatch' && inputs.deploy && github.ref == 'refs/heads/main' + needs: build + runs-on: ubuntu-latest + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - uses: actions/deploy-pages@v4 + id: deployment diff --git a/.github/workflows/update-search-index.yml b/.github/workflows/update-search-index.yml index 8e5f225..4886c17 100644 --- a/.github/workflows/update-search-index.yml +++ b/.github/workflows/update-search-index.yml @@ -8,6 +8,8 @@ on: - "data/events.json" - "data/news.json" - "scripts/build-search-index.mjs" + - "scripts/site-routes.mjs" + - "js/site-urls.js" permissions: contents: write diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..57510a2 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +_site/ diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..1b20549 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "liveServer.settings.root": "/_site", + "liveServer.settings.port": 5500 +} diff --git a/html/components/header.html b/html/components/header.html index 852c35b..d46c76a 100644 --- a/html/components/header.html +++ b/html/components/header.html @@ -1,6 +1,6 @@
diff --git a/js/events.js b/js/events.js index 94ef40a..52ccffc 100644 --- a/js/events.js +++ b/js/events.js @@ -10,7 +10,7 @@ document.addEventListener('DOMContentLoaded', async () => { let eventItems; try { - const response = await fetch("../data/events.json"); + const response = await fetch("/data/events.json"); if (!response.ok) throw new Error(`Request failed with status ${response.status}`); eventItems = await response.json(); @@ -96,7 +96,12 @@ document.addEventListener('DOMContentLoaded', async () => { }; const COURSE_SESSION_URL_MARKER = 'ai-and-ecology-course-'; - const COURSE_SERIES_URL = 'tools-resources/experiential-introduction-ai-ecology-course-2026-2027.html'; + const COURSE_SERIES_URL = window.ImageomicsUrls + ? '/tools-resources/experiential-introduction-ai-ecology-course-2026-2027/' + : 'tools-resources/experiential-introduction-ai-ecology-course-2026-2027.html'; + const CONFERENCE_URL = window.ImageomicsUrls + ? '/events/2027-imageomics-conference/' + : 'events/2027-imageomics-conference.html'; const FEATURED_UPCOMING_WINDOW_DAYS = 14; const MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000; @@ -156,7 +161,7 @@ document.addEventListener('DOMContentLoaded', async () => { const today = getToday(); const featureCandidates = items.flatMap((item) => item.seriesItems?.length ? item.seriesItems : [item]); const conference = featureCandidates.find((item) => - item.url === 'events/2027-imageomics-conference.html' && !isPastEvent(item)); + item.url === CONFERENCE_URL && !isPastEvent(item)); if (conference) { return { item: conference, status: 'Save the Date!' }; } diff --git a/js/homepage.js b/js/homepage.js index 6cb264c..8e1f98d 100644 --- a/js/homepage.js +++ b/js/homepage.js @@ -57,7 +57,7 @@ function getPageUrl(item) { if (/^https?:\/\//.test(item.url || '')) return item.url; - return `html/${String(item.url || '').replace(/^\/?html\//, '')}`; + return window.ImageomicsUrls?.page(item.url) || `html/${String(item.url || '').replace(/^\/?html\//, '')}`; } function makeSnippet(value, maximumLength = 135) { @@ -237,7 +237,8 @@ if (!upcomingEvent) return [...featuredItems]; const conference = featuredItems.find((item) => item.url === 'events/2027-imageomics-conference.html'); - if (upcomingEvent.url === conference?.url) return [...featuredItems]; + const comparableUrl = (url) => window.ImageomicsUrls?.page(url) || url; + if (comparableUrl(upcomingEvent.url) === comparableUrl(conference?.url)) return [...featuredItems]; return [ ...(conference ? [conference] : []), @@ -275,7 +276,7 @@ const getStoryUrl = (story) => { if (/^https?:\/\//.test(story.url || '')) return story.url; - return `html/${String(story.url || '').replace(/^\/?html\//, '')}`; + return window.ImageomicsUrls?.page(story.url) || `html/${String(story.url || '').replace(/^\/?html\//, '')}`; }; const createSlide = (story, isClone = false) => { diff --git a/js/load-components.js b/js/load-components.js index 358bead..9dcb6ef 100644 --- a/js/load-components.js +++ b/js/load-components.js @@ -2,35 +2,10 @@ (function() { 'use strict'; - const COMPONENT_CACHE_VERSION = '14'; + const COMPONENT_CACHE_VERSION = 'clean-urls-2'; - function getPathPrefix() { - const path = window.location.pathname; - - if (path.endsWith('/') || (path.endsWith('/index.html') && !path.includes('/html/'))) { - return ''; - } - - const htmlIndex = path.indexOf('/html/'); - if (htmlIndex !== -1) { - const afterHtml = path.substring(htmlIndex + 6); - const depth = (afterHtml.match(/\//g) || []).length; - return '../'.repeat(depth + 1); - } - - return '../'; - } - - function adjustPaths(html, prefix) { - if (!prefix) return html; - - html = html.replace(/src="(images|css|js|html)\//g, `src="${prefix}$1/`); - html = html.replace(/href="(images|css|js|html)\//g, `href="${prefix}$1/`); - html = html.replace(/href="index\.html"/g, `href="${prefix}index.html"`); - html = html.replace(/href="\.\.\/index\.html"/g, `href="${prefix}index.html"`); - - return html; - } + const script = document.querySelector('script[src*="js/load-components.js"]'); + const siteRoot = new URL('../', script?.src || new URL('/js/load-components.js', window.location.href)); function getCachedComponent(url) { try { @@ -62,8 +37,17 @@ return; } - const prefix = getPathPrefix(); - target.innerHTML = adjustPaths(html, prefix); + target.innerHTML = html; + // Source fragments use root-relative authoring paths; generated fragments + // already have absolute paths. Both must work from nested pages. + target.querySelectorAll('[href], [src]').forEach((element) => { + for (const attribute of ['href', 'src']) { + const value = element.getAttribute(attribute); + if (!value || /^(?:[a-z][a-z\d+.-]*:|\/|#)/i.test(value)) continue; + const url = new URL(value, siteRoot); + element.setAttribute(attribute, url.pathname + url.search + url.hash); + } + }); if (targetId === 'header-placeholder') { if (typeof window.initHamburger === 'function') { @@ -115,21 +99,20 @@ }); } - function ensureFavicon(prefix) { + function ensureFavicon() { if (document.querySelector('link[rel~="icon"]')) return; const favicon = document.createElement('link'); favicon.rel = 'icon'; favicon.type = 'image/png'; - favicon.href = `${prefix}images/Imageomics-logo.png`; + favicon.href = new URL('images/Imageomics-logo.png', siteRoot).href; document.head.appendChild(favicon); } function initComponents() { - const prefix = getPathPrefix(); - const componentsPath = `${prefix}html/components/`; + const componentsPath = new URL('html/components/', siteRoot).href; - ensureFavicon(prefix); + ensureFavicon(); loadComponent(`${componentsPath}header.html`, 'header-placeholder'); loadComponent(`${componentsPath}footer.html`, 'footer-placeholder'); } diff --git a/js/news.js b/js/news.js index bc9d8a0..6f57167 100644 --- a/js/news.js +++ b/js/news.js @@ -13,7 +13,7 @@ document.addEventListener('DOMContentLoaded', async () => { let unsortedNewsItems; try { - const response = await fetch("../data/news.json"); + const response = await fetch("/data/news.json"); if (!response.ok) throw new Error(`Request failed with status ${response.status}`); unsortedNewsItems = await response.json(); diff --git a/js/redirect.js b/js/redirect.js new file mode 100644 index 0000000..a17e735 --- /dev/null +++ b/js/redirect.js @@ -0,0 +1,9 @@ +// Runs before meta refresh. Retain query strings/fragments and avoid a Back loop. +(function () { + 'use strict'; + const canonical = document.querySelector('link[rel="canonical"]'); + if (!canonical) return; + const target = new URL(canonical.href); + const destination = target.pathname + (window.location.search || target.search) + (window.location.hash || target.hash); + if (destination !== window.location.pathname + window.location.search + window.location.hash) window.location.replace(destination); +})(); diff --git a/js/script.js b/js/script.js index 63060f1..93d7292 100644 --- a/js/script.js +++ b/js/script.js @@ -36,8 +36,8 @@ document.addEventListener('DOMContentLoaded', () => { const wholeTermPattern = (term) => `(? { - if (url === 'index.html') return 'Home'; - const section = url.split('/')[1] || ''; + if (url === '/' || url === 'index.html') return 'Home'; + const section = url.replace(/^\/?html\//, '').replace(/^\//, '').split('/')[0].replace(/\.html$/, ''); return { about: 'About', conference: 'Conference', @@ -443,7 +443,7 @@ document.addEventListener('DOMContentLoaded', () => { section.textContent = page.section; const path = document.createElement('span'); path.className = 'search-result-path'; - path.textContent = page.url === 'index.html' ? 'imageomics.org' : page.url.replace(/^html\//, '').replace(/\.html$/, ''); + path.textContent = page.url === '/' || page.url === 'index.html' ? 'imageomics.org' : page.url.replace(/^html\//, '').replace(/\.html$/, ''); meta.append(section, path); const title = document.createElement('div'); @@ -521,7 +521,7 @@ document.addEventListener('DOMContentLoaded', () => { links[activeResultIndex >= 0 ? activeResultIndex : 0].click(); } else if (searchBar.value.trim()) { window.clearTimeout(searchTimer); - const target = new URL('html/search.html', siteRootUrl); + const target = new URL(window.ImageomicsUrls ? 'search/' : 'html/search.html', siteRootUrl); target.searchParams.set('q', searchBar.value.trim()); window.location.assign(target.href); } else { @@ -821,12 +821,13 @@ document.addEventListener('DOMContentLoaded', () => { if (!navMenu) return; const currentUrl = new URL(window.location.href); - const currentPath = currentUrl.pathname.replace(/\/index\.html$/, '/'); + const normalizeNavPath = (pathname) => pathname.replace(/^\/html\//, '/').replace(/\/index\.html$/, '/').replace(/\.html$/, '/'); + const currentPath = normalizeNavPath(currentUrl.pathname); const links = navMenu.querySelectorAll('a[href]'); const getLinkPath = (link) => { const linkUrl = new URL(link.getAttribute('href'), window.location.href); - return linkUrl.pathname.replace(/\/index\.html$/, '/'); + return normalizeNavPath(linkUrl.pathname); }; links.forEach((link) => { @@ -843,7 +844,7 @@ document.addEventListener('DOMContentLoaded', () => { } }); - const sectionMatch = currentPath.match(/\/html\/(about|research|tools-resources|events|news|conference)(?:\/|\.html$)/); + const sectionMatch = currentPath.match(/^\/(about|research|tools-resources|events|news|conference)\//); if (!sectionMatch) return; const section = sectionMatch[1] === 'conference' ? 'events' : sectionMatch[1]; @@ -858,7 +859,7 @@ document.addEventListener('DOMContentLoaded', () => { return; } - const sectionIndexPath = `/html/${section}.html`; + const sectionIndexPath = `/${section}/`; const sectionLink = Array.from(links).find((link) => getLinkPath(link).endsWith(sectionIndexPath)); if (sectionLink) { sectionLink.classList.add('is-current'); diff --git a/js/site-urls.js b/js/site-urls.js new file mode 100644 index 0000000..a9f0bac --- /dev/null +++ b/js/site-urls.js @@ -0,0 +1,27 @@ +// Shared by Node build tools and browser code; no runtime dependencies. +(function (root) { + 'use strict'; + function cleanPath(pathname) { + if (pathname.startsWith('/html/components/')) return pathname; + const page = pathname.replace(/^\/html\//, '/'); + if (page.endsWith('/index.html')) return page.slice(0, -10); + if (page.endsWith('.html')) return page.slice(0, -5) + '/'; + return page; + } + function page(value) { + if (!value || /^(?:[a-z][a-z\d+.-]*:|\/\/|#)/i.test(value)) return value; + const url = new URL(value, 'https://imageomics.org/html/'); + return cleanPath(url.pathname) + url.search + url.hash; + } + function normalizeIndex(location) { + if (location.pathname.endsWith('/index.html')) { + location.replace(location.pathname.slice(0, -10) + location.search + location.hash); + } + } + const api = { cleanPath, page, normalizeIndex }; + if (typeof module !== 'undefined' && module.exports) module.exports = api; + else { + root.ImageomicsUrls = api; + normalizeIndex(root.location); + } +})(typeof window === 'undefined' ? globalThis : window); diff --git a/package.json b/package.json index 2094014..2ee2043 100644 --- a/package.json +++ b/package.json @@ -1,8 +1,10 @@ { "private": true, "scripts": { - "build": "npm run build:search", + "build": "node scripts/build-site.mjs && node scripts/build-search-index.mjs _site/data/search-index.json", "build:search": "node scripts/build-search-index.mjs", - "validate:events": "node scripts/validate-events.mjs" + "validate:events": "node scripts/validate-events.mjs", + "validate:urls": "node scripts/validate-site.mjs", + "test:urls": "node --test scripts/clean-urls.test.mjs" } } diff --git a/scripts/build-search-index.mjs b/scripts/build-search-index.mjs index 56fd326..eb97975 100644 --- a/scripts/build-search-index.mjs +++ b/scripts/build-search-index.mjs @@ -1,9 +1,13 @@ import { readdir, readFile, writeFile } from 'node:fs/promises'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; +import { readRoutes, origin as siteOrigin } from './site-routes.mjs'; const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); -const outputPath = path.join(projectRoot, 'data', 'search-index.json'); +const outputPath = process.argv[2] ? path.resolve(process.argv[2]) : path.join(projectRoot, 'data', 'search-index.json'); +const cleanUrls = Boolean(process.argv[2]); +const routes = await readRoutes(); +const canonicalSources = new Map([...routes.values()].filter((route) => !route.alias).map((route) => [route.url, route.source.slice(1)])); const structuredContentPaths = [ path.join(projectRoot, 'data', 'events.json'), path.join(projectRoot, 'data', 'news.json') @@ -110,19 +114,20 @@ for (const filePath of htmlFiles.sort()) { const relativePath = path.relative(projectRoot, filePath).split(path.sep).join('/'); const html = await readFile(filePath, 'utf8'); markupByUrl.set(relativePath, html); - if (excludedPaths.has(relativePath)) continue; + if (excludedPaths.has(relativePath) || routes.get('/' + relativePath)?.alias) continue; documents.push(extractDocument(html, relativePath)); } -const siteOrigin = 'https://imageomics.org'; function resolvePageUrl(value, sourcePath) { try { const url = new URL(decodeEntities(value), `${siteOrigin}/${sourcePath}`); if (url.origin !== siteOrigin) return null; let pagePath = decodeURIComponent(url.pathname).replace(/^\/+/, ''); if (!pagePath || pagePath.endsWith('/')) pagePath += 'index.html'; - return markupByUrl.has(pagePath) ? pagePath : null; + const route = routes.get('/' + pagePath); + const clean = route ? route.target : url.pathname; + return canonicalSources.get(clean) || (markupByUrl.has(pagePath) ? pagePath : null); } catch { return null; } @@ -176,6 +181,7 @@ while (pending.length) { pending.push(...(listingLinks.get(pagePath) || [])); } -const linkedDocuments = documents.filter((document) => reachable.has(document.url)); +const linkedDocuments = documents.filter((document) => reachable.has(document.url)) + .map((document) => ({ ...document, url: cleanUrls ? routes.get('/' + document.url).target : document.url })); await writeFile(outputPath, `${JSON.stringify(linkedDocuments)}\n`, 'utf8'); console.log(`Indexed ${linkedDocuments.length} linked HTML pages in ${path.relative(projectRoot, outputPath)}; excluded ${documents.length - linkedDocuments.length} unlinked pages.`); diff --git a/scripts/build-site.mjs b/scripts/build-site.mjs new file mode 100644 index 0000000..ab88721 --- /dev/null +++ b/scripts/build-site.mjs @@ -0,0 +1,67 @@ +import { cp, mkdir, readFile, writeFile, rm, stat } from 'node:fs/promises'; +import path from 'node:path'; +import { root, output, origin, walk, readRoutes, rewriteHtml, rewriteUrl, escapeAttribute } from './site-routes.mjs'; + +const routes = await readRoutes(); +// Output is fixed and ignored; never remove or rewrite authoring source files. +await rm(output, { recursive: true, force: true }); +await mkdir(output, { recursive: true }); +async function write(relative, content) { + const file = path.join(output, relative); + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, content); +} +// Copy every non-page resource, including future document/asset directories. +const excluded = new Set(['.git', '.github', '.vscode', '_site', 'node_modules', 'scripts', 'package.json', 'package-lock.json', 'README.md', 'LICENSE', 'CITATION.cff']); +for (const file of await walk(root, excluded)) { + const relative = path.relative(root, file).split(path.sep).join('/'); + if (relative.split('/').some((part) => part.startsWith('.') || excluded.has(part))) continue; + if (routes.has('/' + relative)) continue; + await mkdir(path.dirname(path.join(output, relative)), { recursive: true }); + await cp(file, path.join(output, relative)); +} +const redirect = (target) => ` +Page moved | Imageomics Institute + + + +

Continue to this page.

+`; +const locations = []; +for (const route of routes.values()) { + const destination = path.join(route.url, 'index.html'); + // Fail instead of silently replacing an asset with a generated page. + try { await stat(path.join(output, destination)); throw new Error(`Output collision at ${destination}`); } + catch (error) { if (error.code !== 'ENOENT') throw error; } + if (route.alias) await write(destination, redirect(route.target)); + else { + let html = rewriteHtml(route.html, route.source, routes); + html = html.replace(/\s*]*rel=["']canonical["'][^>]*>/gi, ''); + html = html.replace(/]*>/gi, (tag) => { + if (!/\b(?:property|name)=["'](?:og:url|twitter:url)["']/i.test(tag)) return tag; + return tag.replace(/\bcontent=(["'])(.*?)\1/i, `content="${origin}${route.url}"`); + }); + html = html.replace(/]*>/i, (head) => `${head}\n `); + html = html.replace('', ` \n`); + await write(destination, html); + if (route.url !== '/search/') locations.push(origin + route.url); + } + if (route.source !== '/index.html') await write(route.source, redirect(route.target)); +} +for (const file of await walk(path.join(root, 'html/components'))) { + if (!file.endsWith('.html')) continue; + const relative = path.relative(root, file).split(path.sep).join('/'); + // Header/footer URLs are authored relative to the site root; the saved popup is relative to /html/. + const source = file.endsWith('conference-registration-popup.html') ? '/' + relative : '/index.html'; + await write(relative, rewriteHtml(await readFile(file, 'utf8'), source, routes)); +} +for (const name of ['news', 'events']) { + const records = JSON.parse(await readFile(path.join(root, `data/${name}.json`), 'utf8')); + for (const record of records) for (const field of ['url', 'image']) { + if (record[field]) record[field] = rewriteUrl(record[field], `/html/${name}.html`, routes); + } + await write(`data/${name}.json`, JSON.stringify(records, null, 2) + '\n'); +} +await write('.nojekyll', ''); +await write('sitemap.xml', `\n\n${locations.sort().map((url) => ` ${escapeAttribute(url)}`).join('\n')}\n\n`); +console.log(`Built ${routes.size} clean routes and ${routes.size - 1} legacy redirects in _site/.`); diff --git a/scripts/clean-urls.test.mjs b/scripts/clean-urls.test.mjs new file mode 100644 index 0000000..7186201 --- /dev/null +++ b/scripts/clean-urls.test.mjs @@ -0,0 +1,86 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtemp, mkdir, writeFile, readFile, rm } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import vm from 'node:vm'; +import { cleanPath, readRoutes, rewriteUrl, root } from './site-routes.mjs'; +import urls from '../js/site-urls.js'; + +async function fixture(t, files) { + const directory = await mkdtemp(path.join(os.tmpdir(), 'imageomics-route-test-')); + t.after(() => rm(directory, { recursive: true, force: true })); + for (const [name, value] of Object.entries({ 'index.html': 'Home', ...files })) { + const file = path.join(directory, name); + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, value); + } + return directory; +} +test('clean paths include future pages, directory indexes, and dotted slugs', () => { + for (const [source, expected] of [ + ['/index.html', '/'], ['/html/news.html', '/news/'], ['/html/about/vision.html', '/about/vision/'], + ['/html/future/deep/page.html', '/future/deep/page/'], ['/html/events/conference/index.html', '/events/conference/'], + ['/html/news/dr.-name..html', '/news/dr.-name./'] + ]) assert.equal(cleanPath(source), expected); + assert.equal(cleanPath('/html/components/header.html'), '/html/components/header.html'); + assert.equal(urls.page('news/story.html?year=2026#section'), '/news/story/?year=2026#section'); + assert.equal(urls.page('https://example.org/paper.html'), 'https://example.org/paper.html'); +}); +test('new source files are discovered and existing aliases resolve in one hop', async (t) => { + const directory = await fixture(t, { + 'html/future/page.html': 'New page', + 'html/old.html': '', + 'html/older.html': '' + }); + const routes = await readRoutes(directory); + assert.equal(routes.get('/html/future/page.html').url, '/future/page/'); + assert.equal(routes.get('/html/older.html').target, '/future/page/'); + assert.equal(rewriteUrl('older.html?q=ai&page=2#section', '/html/news.html', routes), '/future/page/?q=ai&page=2#section'); + assert.equal(rewriteUrl('/future/page/?q=ai#s', '/index.html', routes), '/future/page/?q=ai#s'); + assert.equal(rewriteUrl('//imageomics.org/html/older.html', '/index.html', routes), '/future/page/'); + assert.equal(rewriteUrl('../images/x.png', '/html/news.html', routes), '/images/x.png'); + assert.equal(rewriteUrl('https://external.org/news.html', '/index.html', routes), 'https://external.org/news.html'); +}); +test('duplicate routes, redirect loops, and missing destinations fail the build', async (t) => { + const collision = await fixture(t, { 'html/news.html': 'News', 'html/news/index.html': 'Duplicate' }); + await assert.rejects(readRoutes(collision), /collision/); + const overlap = await fixture(t, { 'html/html/news.html': 'Nested', 'html/news/index.html': 'Index' }); + await assert.rejects(readRoutes(overlap), /collision/); + const cycle = await fixture(t, { + 'html/a.html': '', + 'html/b.html': '' + }); + await assert.rejects(readRoutes(cycle), /loop/); + const missing = await fixture(t, { 'html/a.html': '' }); + await assert.rejects(readRoutes(missing), /Missing redirect/); +}); +test('legacy redirects preserve queries/fragments and never loop', async () => { + const code = await readFile(path.join(root, 'js/redirect.js'), 'utf8'); + for (const target of ['/', '/news/', '/events/conference/']) { + let replacement; + const location = { pathname: '/html/old.html', search: '?q=ai&page=2', hash: '#section', replace(value) { replacement = value; } }; + const document = { querySelector: () => ({ href: 'https://imageomics.org' + target }) }; + vm.runInNewContext(code, { URL, document, window: { location } }); + assert.equal(replacement, target + '?q=ai&page=2#section'); + location.pathname = target; replacement = undefined; + vm.runInNewContext(code, { URL, document, window: { location } }); + assert.equal(replacement, undefined); + } +}); +test('explicit index.html bookmarks normalize to directory URLs', async () => { + for (const pathname of ['/index.html', '/news/index.html', '/about/vision/index.html']) { + let replacement; + const location = { pathname, search: '?from=bookmark', hash: '#section', replace(value) { replacement = value; } }; + urls.normalizeIndex(location); + assert.equal(replacement, pathname.slice(0, -10) + '?from=bookmark#section'); + } +}); +test('tracked search index works when publishing the repository root', async () => { + const pages = JSON.parse(await readFile(path.join(root, 'data/search-index.json'), 'utf8')); + assert(pages.length > 0); + for (const page of pages) { + assert(!page.url.startsWith('/') && page.url.endsWith('.html'), `Source index must use source paths: ${page.url}`); + await readFile(path.join(root, page.url)); + } +}); diff --git a/scripts/site-routes.mjs b/scripts/site-routes.mjs new file mode 100644 index 0000000..52c5d05 --- /dev/null +++ b/scripts/site-routes.mjs @@ -0,0 +1,81 @@ +import { readdir, readFile } from 'node:fs/promises'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import urls from '../js/site-urls.js'; +export const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +export const origin = 'https://imageomics.org'; +export const output = path.join(root, '_site'); +export const { cleanPath } = urls; +export const escapeAttribute = (value) => value.replace(/&/g, '&').replace(/"/g, '"').replace(/ value.replace(/&/g, '&').replace(/"/g, '"').replace(/'|'/g, "'"); +export async function walk(directory, excluded = new Set()) { + const files = []; + for (const entry of await readdir(directory, { withFileTypes: true })) { + if (entry.name.startsWith('.') || excluded.has(entry.name)) continue; + const full = path.join(directory, entry.name); + if (entry.isDirectory()) files.push(...await walk(full, excluded)); + else if (entry.isFile()) files.push(full); + } + return files.sort(); +} +export async function readRoutes(projectRoot = root) { + const files = [path.join(projectRoot, 'index.html'), ...(await walk(path.join(projectRoot, 'html'))).filter((file) => file.endsWith('.html'))]; + const routes = new Map(); + const occupied = new Map(); + for (const file of files) { + const source = '/' + path.relative(projectRoot, file).split(path.sep).join('/'); + if (source.startsWith('/html/components/')) continue; + const html = await readFile(file, 'utf8'); + const url = cleanPath(source); + if (occupied.has(url)) throw new Error(`URL collision: ${source} and ${occupied.get(url)} both map to ${url}`); + occupied.set(url, source); + const refresh = html.match(/]*http-equiv=["']refresh["'][^>]*content=["'][^"';]*;\s*url=([^"']+)/i); + routes.set(source, { source, url, html, alias: refresh ? new URL(decodeAttribute(refresh[1]), origin + source) : null }); + } + const generatedFiles = new Map(); + for (const route of routes.values()) { + for (const file of new Set([route.url + 'index.html', route.source])) { + if (generatedFiles.has(file)) throw new Error(`Output collision at ${file}: ${route.source} and ${generatedFiles.get(file)}`); + generatedFiles.set(file, route.source); + } + } + const byClean = new Map([...routes.values()].map((route) => [route.url, route])); + function final(route, visited = new Set()) { + if (visited.has(route.source)) throw new Error(`Redirect loop at ${route.source}`); + if (!route.alias) return route.url; + if (route.alias.origin !== origin) throw new Error(`Review external redirect at ${route.source}: ${route.alias}`); + visited.add(route.source); + const next = routes.get(route.alias.pathname) || byClean.get(cleanPath(route.alias.pathname)); + if (!next) throw new Error(`Missing redirect destination: ${route.source} -> ${route.alias.pathname}`); + return final(next, visited) + route.alias.search + route.alias.hash; + } + for (const route of routes.values()) route.target = final(route); + routes.byClean = byClean; + return routes; +} +export function rewriteUrl(value, source, routes) { + if (!value || /^(?:#|mailto:|tel:|data:|javascript:)/i.test(value)) return value; + if (/^https?:\/[^/]/i.test(value)) return value; // Preserve malformed historical external links for content review. + const decoded = decodeAttribute(value); + const url = new URL(decoded, origin + source); + if (url.origin !== origin) return value; + const pagePath = url.pathname.endsWith('/') ? url.pathname + 'index.html' : url.pathname; + const route = routes.get(pagePath) || routes.byClean.get(url.pathname); + const target = route ? new URL(route.target, origin) : url; + const rewritten = target.pathname + (url.search || target.search) + (url.hash || target.hash); + return /^https?:/i.test(value) ? origin + rewritten : rewritten; +} +// HTML is authored with quoted URL attributes. Preserve markup, prose, and inline code. +export function rewriteHtml(html, source, routes) { + return html.replace(/\b(href|src|action|poster)\s*=\s*(["'])(.*?)\2/gi, (match, name, quote, value) => { + const rewritten = rewriteUrl(value, source, routes); + return rewritten === value ? match : `${name}=${quote}${escapeAttribute(rewritten)}${quote}`; + }).replace(/\bsrcset\s*=\s*(["'])(.*?)\1/gi, (match, quote, value) => { + if (value.startsWith('data:')) return match; + const entries = value.split(',').map((entry) => { + const [url, ...descriptor] = entry.trim().split(/\s+/); + return [rewriteUrl(url, source, routes), ...descriptor].join(' '); + }); + return `srcset=${quote}${escapeAttribute(entries.join(', '))}${quote}`; + }).replace(/url\(\s*(["']?)([^)'"\s]+)\1\s*\)/g, (match, quote, value) => `url(${quote}${rewriteUrl(value, source, routes)}${quote})`); +} diff --git a/scripts/validate-site.mjs b/scripts/validate-site.mjs new file mode 100644 index 0000000..fcd27e4 --- /dev/null +++ b/scripts/validate-site.mjs @@ -0,0 +1,78 @@ +import assert from 'node:assert/strict'; +import { readFile, stat } from 'node:fs/promises'; +import path from 'node:path'; +import { output, root, origin, readRoutes, walk, decodeAttribute, rewriteHtml } from './site-routes.mjs'; +const routes = await readRoutes(); +const errors = []; +const warnings = new Set(); +const ids = new Map(); +let references = 0; +async function localFile(value) { + const file = path.join(output, decodeURIComponent(value)); + return (await stat(file)).isDirectory() ? path.join(file, 'index.html') : file; +} +async function check(value, source, attribute = 'href') { + if (!value || /^(?:mailto:|tel:|data:|javascript:)/i.test(value)) return; + // Retain and report these two historical content issues without changing event copy. + if (value.startsWith('https:/osu.zoom.us/meeting/register/')) { warnings.add('Existing malformed Zoom registration link (February 2024 event).'); return; } + const url = new URL(decodeAttribute(value), origin + source); + if (url.origin !== origin) return; + if (url.pathname === '/allhands') { warnings.add('Existing /allhands registration link has no repository page.'); return; } + references++; + let file; + try { file = await localFile(url.pathname); await stat(file); } + catch { errors.push(`${source}: missing ${attribute} ${value}`); return; } + if (attribute === 'href' && routes.has(url.pathname) && url.pathname !== '/index.html') errors.push(`${source}: internal legacy page link ${value}`); + if (attribute === 'href' && url.hash && file.endsWith('.html')) { + if (!ids.has(file)) ids.set(file, new Set([...(await readFile(file, 'utf8')).matchAll(/\b(?:id|name)=["']([^"']+)["']/g)].map((match) => match[1]))); + if (!ids.get(file).has(decodeURIComponent(url.hash.slice(1)))) errors.push(`${source}: missing anchor ${value}`); + } +} +for (const file of await walk(output)) { + const source = '/' + path.relative(output, file).split(path.sep).join('/'); + if (file.endsWith('.html')) { + const html = await readFile(file, 'utf8'); + for (const match of html.matchAll(/\b(href|src|action|poster)\s*=\s*(["'])(.*?)\2/gi)) await check(match[3], source, match[1]); + for (const match of html.matchAll(/\bsrcset\s*=\s*(["'])(.*?)\1/gi)) { + if (!match[2].startsWith('data:')) for (const entry of match[2].split(',')) await check(entry.trim().split(/\s+/)[0], source, 'srcset'); + } + } else if (file.endsWith('.css')) { + for (const match of (await readFile(file, 'utf8')).matchAll(/url\(\s*["']?([^)'"\s]+)["']?\s*\)/g)) await check(match[1], source, 'CSS asset'); + } +} +const sitemap = await readFile(path.join(output, 'sitemap.xml'), 'utf8'); +for (const route of routes.values()) { + const html = await readFile(await localFile(route.url), 'utf8'); + const canonicals = [...html.matchAll(/]*rel="canonical"[^>]*href="([^"]+)"/g)]; + assert.equal(canonicals.length, 1, `Expected one canonical for ${route.url}`); + assert.equal(decodeAttribute(canonicals[0][1]), origin + route.target); + if (!route.alias) { + assert(!/http-equiv="refresh"/.test(html), `Unexpected redirect ${route.url}`); + const body = (value) => value.match(/]*>([\s\S]*)<\/body>/i)?.[1]; + assert.equal(body(html), body(rewriteHtml(route.html, route.source, routes)), `Content changed for ${route.source}`); + if (route.url !== '/search/') assert(sitemap.includes(`${origin}${route.url}`)); + } + if (route.source !== '/index.html') { + const legacy = await readFile(path.join(output, route.source), 'utf8'); + assert(legacy.includes('/js/redirect.js'), `Missing state-preserving redirect ${route.source}`); + assert(legacy.includes(`href="${origin}${route.target}"`), `Incorrect legacy destination ${route.source}`); + const target = new URL(route.target, origin); + assert(!/http-equiv="refresh"/.test(await readFile(await localFile(target.pathname), 'utf8')), `Redirect chain for ${route.source}`); + } +} +for (const name of ['news', 'events', 'search-index']) { + const records = JSON.parse(await readFile(path.join(output, `data/${name}.json`), 'utf8')); + for (const item of records) for (const field of ['url', 'image']) if (item[field]) { + await check(item[field], '/', field === 'url' ? 'href' : 'src'); + if (field === 'url' && item[field].startsWith('/')) assert(item[field].endsWith('/'), `Unclean ${name} URL: ${item[field]}`); + } +} +for (const name of ['css', 'js', 'images']) { + // The build must preserve assets byte-for-byte; JS changes are made in source. + for (const file of await walk(path.join(root, name))) assert.deepEqual(await readFile(file), await readFile(path.join(output, path.relative(root, file)))); +} +const header = await readFile(path.join(output, 'html/components/header.html'), 'utf8'); +assert.match(header, /class="logo"[\s\S]*?/, 'Logo must link to /'); +for (const warning of warnings) console.warn(warning); +if (errors.length) { console.error(errors.join('\n')); process.exitCode = 1; } +else console.log(`Validated ${routes.size} routes, ${references} local references, redirects, sitemap, anchors, content and unchanged assets.`);