Merge pull request #1596 from ludovic111/feat/website-mods
🤖 Agent: merged after verify passed; mod-registry-land-1's combined check (pr_ready --quick on all seven, launcher tests 125, website 25/25, no harness affected) and live end-to-end on horizon-mods.
This commit is contained in:
+10
-2
@@ -20,7 +20,7 @@
|
||||
Referrer-Policy strict-origin-when-cross-origin
|
||||
X-Frame-Options DENY
|
||||
Permissions-Policy "interest-cohort=(), browsing-topics=(), camera=(), microphone=(), geolocation=()"
|
||||
Content-Security-Policy "default-src 'self'; script-src 'self' {$CSP_SCRIPT}; style-src 'self' {$CSP_STYLE}; img-src 'self' data: https://avatars.githubusercontent.com; font-src 'self'; connect-src 'self' https://api.github.com https://raw.githubusercontent.com https://telemetry.playhorizon.dev; frame-ancestors 'none'; base-uri 'self'; form-action 'self'"
|
||||
Content-Security-Policy "default-src 'self'; script-src 'self' {$CSP_SCRIPT}; style-src 'self' {$CSP_STYLE}; img-src 'self' data: https://avatars.githubusercontent.com https://ludovic111.github.io; font-src 'self'; connect-src 'self' https://api.github.com https://raw.githubusercontent.com https://telemetry.playhorizon.dev https://ludovic111.github.io; frame-ancestors 'none'; base-uri 'self'; form-action 'self'"
|
||||
-Server
|
||||
}
|
||||
@assets path /assets/*
|
||||
@@ -35,7 +35,15 @@
|
||||
rewrite /benchmarks /benchmarks.html
|
||||
@doc path_regexp doc ^/docs/([a-z-]+)$
|
||||
rewrite @doc /docs/{re.doc.1}.html
|
||||
@pages path / /index.html /404.html /privacy.html /releases /releases.html /benchmarks /benchmarks.html /benchmarks.json /docs /docs/* /sitemap.xml
|
||||
# The registry: /mods, and /mods/<id> baked at build time, else the list page, whose script shows a project
|
||||
# published since.
|
||||
rewrite /mods /mods.html
|
||||
@mod {
|
||||
path_regexp ^/mods/[a-z0-9_]+$
|
||||
file {path}.html /mods.html
|
||||
}
|
||||
rewrite @mod {file_match.relative}
|
||||
@pages path / /index.html /404.html /privacy.html /releases /releases.html /benchmarks /benchmarks.html /benchmarks.json /docs /docs/* /mods /mods.html /mods/* /sitemap.xml
|
||||
header @pages Cache-Control "no-cache"
|
||||
@legal path /LEGAL.md /fonts/*.txt
|
||||
header @legal Content-Type "text/plain; charset=utf-8"
|
||||
|
||||
+5
-2
@@ -25,12 +25,14 @@ src/404.html the not-found page
|
||||
src/privacy.html what the launcher can send when players allow it, retention, deletion (/privacy)
|
||||
src/releases.html every release, newest first, with what it adds and fixes, its notes and downloads (/releases)
|
||||
src/benchmarks.html Horizon against vanilla 26.3 on our machines, the hardware picker, players' results (/benchmarks)
|
||||
src/mods.html the registry's list (/mods) and a page per project (/mods/<id>), one template
|
||||
src/docs.html the template of every documentation page (/docs/...), with its left navigation
|
||||
src/tokens.css the design tokens, generated from crates/horizon-theme (do not edit)
|
||||
src/style.css every style, on top of the tokens
|
||||
src/main.js the home page: download buttons, recent releases, links, contributors, nav, tabs, lightbox, motion
|
||||
src/chrome.js the light/dark switch, the phone menu and GitHub fetching, shared by the pages
|
||||
src/releases-page.js the Releases page: the channel filter and the refresh from GitHub
|
||||
src/mods.js the registry's markup (list, project page), shared by build and page; mods-page.js: the filter, the search, the refresh
|
||||
src/benchmarks-page.js the Benchmarks page: players' results from the telemetry server, the picker
|
||||
src/docs-page.js the Docs pages: the shared theme switch and phone menu
|
||||
src/bench.js the Benchmarks tables, shared by build and page
|
||||
@@ -52,14 +54,15 @@ shots/ (gitignored) full-page screenshots at 360–1920 px, a 1250×
|
||||
|
||||
## What comes from where
|
||||
|
||||
- **Built in** (`build.mjs`): the parity table, its score, harness count and audit date,
|
||||
- **Built in** (`build.mjs`): Horizon's registry (`/mods`, one page per project) from the index ludovic111/horizon-mods
|
||||
publishes (`HORIZON_MOD_INDEX=<file>` builds from a test index; docs/api/mod-index.md); the parity table, its score, harness count and audit date,
|
||||
all from `README.md`; the documentation pages (`/docs`) from `website/docs/`; the Discord and Sponsor links from
|
||||
`launcher/links.json`; the latest releases and the contributors (`/repos/ludovic111/horizon/contributors`,
|
||||
bots left out, the owner first), when GitHub answers; without an answer the build still succeeds and
|
||||
the Contributors block and its menu entries stay hidden until the page loads them. Locally these come from
|
||||
the checkout; on Railway, which builds only this folder, from `main` on GitHub. The build
|
||||
fails if the README has no parity table, so a broken README never deploys.
|
||||
- **Fetched by the page**: the releases (the download button picks the newest
|
||||
- **Fetched by the page**: the registry's index (a project merged after the build shows at once), the releases (the download button picks the newest
|
||||
`launcher-v*` release's asset for the visitor's OS, the home page lists the newest game releases, and
|
||||
the Releases page reloads its list when GitHub has a newer release), players' benchmark results
|
||||
(`GET https://telemetry.playhorizon.dev/v1/benchmarks/summary`, 3-second timeout), the contributors (avatars come from `avatars.githubusercontent.com`),
|
||||
|
||||
+65
-6
@@ -16,6 +16,7 @@ import { machinesHtml, playersHtml } from "./src/bench.js";
|
||||
import { CPUS, GPUS, singleThread } from "./src/hardware.js";
|
||||
import { isGame, isLauncher, launcherVersion, newestFirst } from "./src/versions.js";
|
||||
import { contributorsFrom, contributorsHtml } from "./src/contributors.js";
|
||||
import { INDEX_URL, KINDS, SUBMIT, listHtml, projectHtml, readIndex } from "./src/mods.js";
|
||||
|
||||
const site = dirname(fileURLToPath(import.meta.url));
|
||||
const dist = join(site, "dist");
|
||||
@@ -41,6 +42,21 @@ try {
|
||||
console.warn(`links.json: ${e.message}; using the built-in links`);
|
||||
}
|
||||
|
||||
// Horizon's registry (/mods): the index its repository publishes, or HORIZON_MOD_INDEX (a file or an address) to
|
||||
// try a test registry. Without an answer the pages are built empty and load the index themselves.
|
||||
let modProjects = [];
|
||||
let modIndex = null;
|
||||
try {
|
||||
const from = process.env.HORIZON_MOD_INDEX || INDEX_URL;
|
||||
const text = from.startsWith("https://")
|
||||
? await fetch(from, { signal: AbortSignal.timeout(15000) }).then((r) => (r.ok ? r.text() : Promise.reject(new Error(`${r.status}`))))
|
||||
: await readFile(from, "utf8");
|
||||
modIndex = JSON.parse(text);
|
||||
modProjects = readIndex(modIndex) ?? (console.warn("mod index: a schema this site doesn't read"), []);
|
||||
} catch (e) {
|
||||
console.warn(`mod index: ${e.message}; the pages will load it themselves`);
|
||||
}
|
||||
|
||||
// An optional token (a Railway variable, or `gh auth token` locally) lifts the rate limit.
|
||||
const githubHeaders = { Accept: "application/vnd.github+json", ...(process.env.GITHUB_TOKEN ? { Authorization: `Bearer ${process.env.GITHUB_TOKEN}` } : {}) };
|
||||
// Every release (the Releases page lists them all), a page of 100 at a time.
|
||||
@@ -170,7 +186,7 @@ await writeFile(join(dist, "favicon.ico"), Buffer.concat([ico, png32]));
|
||||
const names = {};
|
||||
const rewrite = (code) => code.replace(/"\.\/(\w+\.js)"/g, (all, file) => (names[file] ? `"./${names[file]}"` : all));
|
||||
// Dependencies before what imports them.
|
||||
const modules = ["markdown.js", "versions.js", "chrome.js", "hardware.js", "estimate.js", "releases.js", "contributors.js", "bench.js", "main.js", "releases-page.js", "benchmarks-page.js", "docs-page.js"];
|
||||
const modules = ["markdown.js", "versions.js", "chrome.js", "hardware.js", "estimate.js", "releases.js", "contributors.js", "bench.js", "main.js", "releases-page.js", "benchmarks-page.js", "docs-page.js", "mods.js", "mods-page.js"];
|
||||
for (const file of modules) {
|
||||
const code = rewrite(await readFile(join(site, "src", file), "utf8"));
|
||||
names[file] = `${file.replace(".js", "")}.${fingerprint(code)}.js`;
|
||||
@@ -203,7 +219,7 @@ const unavailable = `<p class="lede">The release notes could not be loaded here.
|
||||
|
||||
// One top bar and phone menu for Home, Releases, Benchmarks and every Docs page.
|
||||
const navSections = [["/#about", "About"], ["/#screenshots", "In game"], ["/#parity", "Parity"], ["/#launcher", "Launcher"], ["/#recent", "New", "Recently added"], ["/#community", "Community"]];
|
||||
const navPages = [["/releases", "Releases"], ["/benchmarks", "Benchmarks"], ["/docs/", "Docs", "Documentation"]];
|
||||
const navPages = [["/mods", "Mods"], ["/releases", "Releases"], ["/benchmarks", "Benchmarks"], ["/docs/", "Docs", "Documentation"]];
|
||||
const navLink = ([href, label, menuLabel], current, menu = false) =>
|
||||
`<a href="${href}"${href === current ? ' aria-current="page"' : ""}${href === "/#contributors" ? ` data-contributors${contributors.length ? "" : " hidden"}` : ""}>${menu && menuLabel ? menuLabel : label}</a>`;
|
||||
const siteNav = (current) => ` <header class="nav" id="top">
|
||||
@@ -233,7 +249,7 @@ const siteFooter = ` <footer class="footer">
|
||||
<div class="container">
|
||||
<div class="footer-bar">
|
||||
<span class="footer-mark">Made in the open, in Rust.</span>
|
||||
<nav class="footer-links" aria-label="Elsewhere"><a href="/">Home</a><a href="/releases">Releases</a><a href="/benchmarks">Benchmarks</a><a href="/docs/">Docs</a><a href="/docs/how-horizon-is-built">How it's built</a><a href="https://github.com/${REPO}">GitHub</a><a href="/privacy">Privacy</a><a href="/LEGAL.md">Assets</a></nav>
|
||||
<nav class="footer-links" aria-label="Elsewhere"><a href="/">Home</a><a href="/mods">Mods</a><a href="/releases">Releases</a><a href="/benchmarks">Benchmarks</a><a href="/docs/">Docs</a><a href="/docs/how-horizon-is-built">How it's built</a><a href="https://github.com/${REPO}">GitHub</a><a href="/privacy">Privacy</a><a href="/LEGAL.md">Assets</a></nav>
|
||||
</div>
|
||||
</div>
|
||||
<p class="footer-word" aria-hidden="true">horizon</p>
|
||||
@@ -370,6 +386,49 @@ for (const page of pages) {
|
||||
html = html.replace(/href="\/(favicon\.svg|favicon-32\.png|apple-touch-icon\.png)"/g, (all, icon) => `href="/${icon}?v=${iconVersions[icon]}"`);
|
||||
await writeFile(join(dist, page), html);
|
||||
}
|
||||
// The registry: /mods (the list) and /mods/<id> (a page per project), one template.
|
||||
const modsTemplate = await readFile(join(site, "src", "mods.html"), "utf8");
|
||||
const modsList = ` <p class="kicker"><span>Mods</span>Made for Horizon, reviewed</p>
|
||||
<h1 class="display page-title">Horizon mods</h1>
|
||||
<p class="lede">Mods, modpacks and resource packs made for Horizon. Each one was reviewed before it was listed, and the launcher checks every file before it installs it. Mods run in a sandbox and can only do what their page says.</p>
|
||||
<p class="mod-actions"><a class="button primary" href="${SUBMIT}">Submit yours</a> <a class="button secondary" href="/docs/mods">Make a mod</a></p>
|
||||
<div class="mod-tools">
|
||||
<input class="mod-search" id="mod-search" type="search" placeholder="Search" aria-label="Search the registry" autocomplete="off">
|
||||
<div class="release-filter" role="group" aria-label="Show">
|
||||
<button type="button" class="button secondary small" data-kind-filter="all" aria-pressed="true">All</button>
|
||||
${KINDS.map(([k, label]) => ` <button type="button" class="button secondary small" data-kind-filter="${k}" aria-pressed="false">${label}</button>`).join("\n")}
|
||||
</div>
|
||||
</div>
|
||||
<p class="meta release-count" data-mod-count>${modProjects.length} of ${modProjects.length}</p>
|
||||
<div class="mod-list" id="mod-list" aria-live="polite">
|
||||
${listHtml(modProjects)}
|
||||
</div>`;
|
||||
const modPages = [
|
||||
{ file: "mods.html", path: "/mods", title: "Mods", description: "Mods, modpacks and resource packs made for Horizon, reviewed, each with what it may do and how to install it.", main: modsList },
|
||||
...modProjects.map((p) => ({ file: `mods/${p.id}.html`, path: `/mods/${p.id}`, title: p.name, description: p.summary || p.name, main: projectHtml(p) })),
|
||||
];
|
||||
await mkdir(join(dist, "mods"), { recursive: true });
|
||||
const modsData = JSON.stringify(modIndex && modProjects.length ? { schema: modIndex.schema, projects: modProjects } : null).replace(/</g, "\\u003c");
|
||||
for (const page of modPages) {
|
||||
const own = {
|
||||
...values,
|
||||
SITE_NAV: siteNav("/mods"),
|
||||
MODS_TITLE: escape(page.title),
|
||||
MODS_DESCRIPTION: escape(page.description),
|
||||
MODS_PATH: page.path,
|
||||
MODS_JS: `/assets/${names["mods-page.js"]}`,
|
||||
MODS_MAIN: page.main,
|
||||
MODS_DATA: modsData,
|
||||
MODS_BAKED_AT: escape(modIndex?.generated || ""),
|
||||
};
|
||||
let html = modsTemplate.replace(/\{\{(\w+)\}\}/g, (all, key) => {
|
||||
if (!(key in own)) throw new Error(`mods.html: unknown placeholder ${all}`);
|
||||
return own[key];
|
||||
});
|
||||
html = html.replace(/href="\/(favicon\.svg|favicon-32\.png|apple-touch-icon\.png)"/g, (all, icon) => `href="/${icon}?v=${iconVersions[icon]}"`);
|
||||
await writeFile(join(dist, page.file), html);
|
||||
}
|
||||
|
||||
const docTemplate = await readFile(join(site, "src", "docs.html"), "utf8");
|
||||
for (const { file, values: own } of docPages) {
|
||||
let html = docTemplate.replace(/\{\{(\w+)\}\}/g, (all, key) => {
|
||||
@@ -384,12 +443,12 @@ for (const { file, values: own } of docPages) {
|
||||
|
||||
// The pages' inline scripts (they mark the page as scripted and apply the saved theme before CSS
|
||||
// applies) and the inlined stylesheet: the Content-Security-Policy in the Caddyfile allows them by hash.
|
||||
const allHtml = (await Promise.all([...pages, ...docPageFiles].map((page) => readFile(join(dist, page), "utf8")))).join("\n");
|
||||
const allHtml = (await Promise.all([...pages, ...docPageFiles, ...modPages.map((p) => p.file)].map((page) => readFile(join(dist, page), "utf8")))).join("\n");
|
||||
const hashes = (re) => [...new Set([...allHtml.matchAll(re)].map((m) => `'sha256-${createHash("sha256").update(m[1]).digest("base64")}'`))].join(" ");
|
||||
await writeFile(join(dist, ".csp-script"), hashes(/<script>([\s\S]*?)<\/script>/g));
|
||||
await writeFile(join(dist, ".csp-style"), hashes(/<style>([\s\S]*?)<\/style>/g));
|
||||
|
||||
const urls = ["/", "/releases", "/benchmarks", ...docs.map((d) => d.path), "/privacy"];
|
||||
const urls = ["/", "/mods", ...modPages.slice(1).map((p) => p.path), "/releases", "/benchmarks", ...docs.map((d) => d.path), "/privacy"];
|
||||
await writeFile(
|
||||
join(dist, "sitemap.xml"),
|
||||
`<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urls.map((u) => ` <url><loc>https://playhorizon.dev${u}</loc></url>`).join("\n")}\n</urlset>\n`,
|
||||
@@ -397,5 +456,5 @@ await writeFile(
|
||||
|
||||
console.log(
|
||||
`built dist/ from ${readmeFrom}: ${body.length} subsystems, ${percent}, ${harnesses} harnesses, ` +
|
||||
`${ours.length} releases (${game.length} game)${launcher ? `, launcher ${launcher.tag_name}` : ""}, ${benchSummary.groups.length} benchmark rows, ${contributors.length} contributors, ${docs.length} docs pages`,
|
||||
`${ours.length} releases (${game.length} game)${launcher ? `, launcher ${launcher.tag_name}` : ""}, ${benchSummary.groups.length} benchmark rows, ${contributors.length} contributors, ${docs.length} docs pages, ${modProjects.length} registry projects`,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
// /mods and /mods/<id>: the registry's list (kind filter, search) and a project's page. The pages are baked from
|
||||
// the index at build time; this fetches the published index again so a project merged since shows at once.
|
||||
import { INDEX_URL, KINDS, listHtml, matches, projectHtml, readIndex } from "./mods.js";
|
||||
import { cached, setUpMenu, setUpTheme } from "./chrome.js";
|
||||
|
||||
const root = document.getElementById("mods");
|
||||
const baked = readIndex(JSON.parse(document.getElementById("mods-index").textContent || "null")) || [];
|
||||
let projects = baked;
|
||||
let kind = "all";
|
||||
let text = "";
|
||||
|
||||
const id = (location.pathname.match(/^\/mods\/([a-z0-9_]+)\/?$/) || [])[1];
|
||||
|
||||
function showList() {
|
||||
const list = root.querySelector("#mod-list");
|
||||
if (!list) return;
|
||||
const shown = projects.filter((p) => matches(p, kind, text));
|
||||
list.innerHTML = listHtml(shown);
|
||||
root.querySelector("[data-mod-count]").textContent = `${shown.length} of ${projects.length}`;
|
||||
root.querySelectorAll("[data-kind-filter]").forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.kindFilter === kind)));
|
||||
}
|
||||
|
||||
function showProject() {
|
||||
const p = projects.find((x) => x.id === id);
|
||||
const page = root.querySelector(".mod-page, .mod-missing");
|
||||
if (!page) return;
|
||||
if (p) {
|
||||
page.outerHTML = projectHtml(p);
|
||||
document.title = `${p.name} · Horizon`;
|
||||
} else {
|
||||
page.outerHTML = `<div class="mod-missing"><h1 class="display page-title">Not in the registry</h1><p class="lede">No project is called ${id} here. It may not be published yet, or it was taken down.</p><a class="button secondary" href="/mods">Every mod</a></div>`;
|
||||
}
|
||||
}
|
||||
|
||||
function render() {
|
||||
if (id) showProject();
|
||||
else showList();
|
||||
}
|
||||
|
||||
if (!id) {
|
||||
root.querySelectorAll("[data-kind-filter]").forEach((b) =>
|
||||
b.addEventListener("click", () => {
|
||||
kind = b.dataset.kindFilter;
|
||||
showList();
|
||||
}),
|
||||
);
|
||||
root.querySelector("#mod-search")?.addEventListener("input", (e) => {
|
||||
text = e.target.value;
|
||||
showList();
|
||||
});
|
||||
const wanted = new URLSearchParams(location.search).get("kind");
|
||||
if (KINDS.some(([k]) => k === wanted)) kind = wanted;
|
||||
}
|
||||
|
||||
setUpTheme();
|
||||
setUpMenu();
|
||||
render();
|
||||
cached("horizon:mod-index", () => fetch(INDEX_URL).then((r) => (r.ok ? r.json() : Promise.reject(new Error(`${r.status}`)))))
|
||||
.then((index) => {
|
||||
const fresh = readIndex(index);
|
||||
if (fresh) {
|
||||
projects = fresh;
|
||||
render();
|
||||
}
|
||||
})
|
||||
.catch(() => {});
|
||||
@@ -0,0 +1,37 @@
|
||||
<!doctype html>
|
||||
<html lang="en" class="no-js">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<title>{{MODS_TITLE}} · Horizon</title>
|
||||
<meta name="description" content="{{MODS_DESCRIPTION}}">
|
||||
<meta name="theme-color" content="#ece7f7" media="(prefers-color-scheme: light)">
|
||||
<meta name="theme-color" content="#0f0d17" media="(prefers-color-scheme: dark)">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<link rel="canonical" href="https://playhorizon.dev{{MODS_PATH}}">
|
||||
<link rel="icon" href="/favicon.svg" type="image/svg+xml">
|
||||
<link rel="icon" href="/favicon-32.png" sizes="32x32" type="image/png">
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:site_name" content="Horizon">
|
||||
<meta property="og:title" content="{{MODS_TITLE}} · Horizon">
|
||||
<meta property="og:description" content="{{MODS_DESCRIPTION}}">
|
||||
<meta property="og:url" content="https://playhorizon.dev{{MODS_PATH}}">
|
||||
<meta property="og:image" content="https://playhorizon.dev/og.png">
|
||||
<style>{{STYLE}}</style>
|
||||
<script>document.documentElement.classList.replace("no-js", "js"); try { const t = localStorage.getItem("theme"); if (t === "light" || t === "dark") document.documentElement.dataset.theme = t } catch {}</script>
|
||||
<script type="module" src="{{MODS_JS}}"></script>
|
||||
</head>
|
||||
<body class="subpage">
|
||||
<a class="skip" href="#main">Skip to the content</a>
|
||||
{{SITE_NAV}}
|
||||
<main id="main" class="section page-main">
|
||||
<div class="container" id="mods" data-baked="{{MODS_BAKED_AT}}">
|
||||
{{MODS_MAIN}}
|
||||
<p class="disclaimer">Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft.</p>
|
||||
</div>
|
||||
</main>
|
||||
{{SITE_FOOTER}}
|
||||
<script type="application/json" id="mods-index">{{MODS_DATA}}</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,110 @@
|
||||
// Horizon's registry on the site (/mods): the list with its kind filter and search, and a page per project.
|
||||
// Shared by build.mjs (baked into the pages) and mods-page.js (refreshed from the published index).
|
||||
// The index's format is docs/api/mod-index.md in the repository.
|
||||
import { markdown, escape } from "./markdown.js";
|
||||
|
||||
export const INDEX_URL = "https://ludovic111.github.io/horizon-mods/index.json";
|
||||
const REGISTRY = "https://github.com/ludovic111/horizon-mods";
|
||||
export const SUBMIT = `${REGISTRY}#submit`;
|
||||
export const SCHEMA = 1;
|
||||
|
||||
// The kinds the site shows, in the filter's order. Kinds a newer index adds are left out until the site knows them.
|
||||
export const KINDS = [
|
||||
["mod", "Mods"],
|
||||
["modpack", "Modpacks"],
|
||||
["resourcepack", "Resource packs"],
|
||||
["shader", "Shader packs"],
|
||||
];
|
||||
const KIND_NAMES = { mod: "Mod", modpack: "Modpack", resourcepack: "Resource pack", shader: "Shader pack" };
|
||||
|
||||
// What a capability lets a mod do, as the game and the launcher say it (horizon_mods::Capability::describe).
|
||||
export const CAPABILITIES = {
|
||||
"game-read": "see your position, health and the time",
|
||||
chat: "show you chat messages",
|
||||
hud: "draw text on your screen",
|
||||
storage: "save its own settings to disk",
|
||||
registries: "add blocks and items to your worlds",
|
||||
};
|
||||
|
||||
// The index's projects this site can show, or null when it isn't an index it reads.
|
||||
export function readIndex(index) {
|
||||
if (!index || typeof index !== "object" || index.schema > SCHEMA || !Array.isArray(index.projects)) return null;
|
||||
const known = new Set(KINDS.map(([k]) => k));
|
||||
return index.projects.filter((p) => known.has(p.kind) && /^[a-z0-9_]{1,64}$/.test(p.id) && p.versions?.length);
|
||||
}
|
||||
|
||||
const https = (url) => (typeof url === "string" && url.startsWith("https://") ? url : "");
|
||||
const size = (bytes) => (bytes >= 1 << 20 ? `${(bytes / (1 << 20)).toFixed(1)} MB` : `${Math.max(1, Math.round(bytes / 1024))} KB`);
|
||||
const trust = (p) =>
|
||||
p.key ? `<span class="badge badge-signed" title="Every file is signed with the author's key">Signed</span>` : `<span class="badge badge-unsigned" title="The file is pinned by its checksum, not signed">Unsigned</span>`;
|
||||
const initial = (p) => escape((p.name || p.id).trim().charAt(0).toUpperCase());
|
||||
const icon = (p) =>
|
||||
https(p.icon) ? `<img class="mod-icon" src="${escape(p.icon)}" alt="" width="48" height="48" loading="lazy">` : `<span class="mod-icon" aria-hidden="true">${initial(p)}</span>`;
|
||||
|
||||
export function matches(p, kind, text) {
|
||||
if (kind !== "all" && p.kind !== kind) return false;
|
||||
const hay = `${p.id} ${p.name} ${p.summary} ${(p.authors || []).join(" ")}`.toLowerCase();
|
||||
return text.toLowerCase().split(/\s+/).filter(Boolean).every((w) => hay.includes(w));
|
||||
}
|
||||
|
||||
// The list: a row per project, newest version and kind on the right.
|
||||
export function listHtml(projects) {
|
||||
if (!projects.length) return `<p class="lede mod-empty">Nothing here yet. <a href="${SUBMIT}">Submit yours</a>.</p>`;
|
||||
return projects
|
||||
.map(
|
||||
(p) => `<a class="mod-row" href="/mods/${p.id}" data-kind="${escape(p.kind)}" data-search="${escape(`${p.id} ${p.name} ${p.summary} ${(p.authors || []).join(" ")}`.toLowerCase())}">
|
||||
${icon(p)}
|
||||
<span class="mod-text"><span class="mod-name">${escape(p.name)}</span><span class="mod-summary">${escape(p.summary || "")}</span></span>
|
||||
<span class="mod-side"><span class="badge">${escape(KIND_NAMES[p.kind] || p.kind)}</span><span class="mod-version">${escape(p.versions[0].version)} · ${escape((p.authors || []).join(", "))}</span></span>
|
||||
</a>`,
|
||||
)
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
function installHtml(p, v) {
|
||||
const file = escape(v.file.name);
|
||||
const cli = `horizon-launcher mods install --source horizon ${p.id}`;
|
||||
const where = {
|
||||
mod: `put it in <code>horizon-mods/</code> beside <code>options.txt</code> in the game folder, then turn it on in the game: Options > Mods`,
|
||||
resourcepack: `put it in <code>resourcepacks/</code> beside <code>options.txt</code>, then turn it on in Options > Resource Packs`,
|
||||
modpack: `a modpack lists registry mods: install them one by one, or wait for the launcher to install modpacks`,
|
||||
shader: `Horizon's own shader packs aren't installed yet`,
|
||||
}[p.kind];
|
||||
return `<ol class="mod-steps">
|
||||
<li>In the launcher: <strong>Mods</strong>, pick <strong>Horizon</strong> beside Modrinth, find ${escape(p.name)} and press <strong>Install</strong>. It checks the file's checksum${p.key ? " and signature" : ""} first.</li>
|
||||
<li>From a terminal or an agent: <code>${escape(cli)}</code></li>
|
||||
<li>By hand: download <a href="${escape(https(v.file.url))}">${file}</a> (${size(v.file.size)}), check its SHA-256 below, and ${where}.</li>
|
||||
</ol>`;
|
||||
}
|
||||
|
||||
// One project's page.
|
||||
export function projectHtml(p) {
|
||||
const v = p.versions[0];
|
||||
const caps = v.capabilities || [];
|
||||
const capsHtml = caps.length
|
||||
? `<ul class="mod-caps">${caps.map((c) => `<li>May ${escape(CAPABILITIES[c] || c)}</li>`).join("")}</ul>`
|
||||
: `<p>It asks for nothing beyond writing its own log.</p>`;
|
||||
const requires = (v.requires || []).length
|
||||
? `<h2 class="heading">Its mods</h2><ul class="mod-caps">${v.requires.map((r) => `<li><a href="/mods/${escape(r.id)}">${escape(r.id)}</a> ${escape(r.version)}</li>`).join("")}</ul>`
|
||||
: "";
|
||||
const versions = p.versions
|
||||
.map((x) => `<li><strong>${escape(x.version)}</strong> <span class="mod-version">${escape(x.published || "")} · for ${escape(x.game)}${x.api ? ` · API ${escape(x.api)}` : ""}</span>${x.changelog ? `<div class="prose">${markdown(x.changelog)}</div>` : ""}</li>`)
|
||||
.join("");
|
||||
return `<article class="mod-page" data-id="${escape(p.id)}">
|
||||
<header class="mod-head">${icon(p)}<div><p class="kicker"><span>${escape(KIND_NAMES[p.kind] || p.kind)}</span>${escape((p.authors || []).join(", "))}</p>
|
||||
<h1 class="display page-title">${escape(p.name)}</h1><p class="lede">${escape(p.summary || "")}</p>
|
||||
<p class="mod-badges">${trust(p)} <span class="badge">${escape(p.license)}</span> <span class="badge">${escape(v.version)}</span>${v.side ? ` <span class="badge">${escape(v.side)}</span>` : ""}</p></div></header>
|
||||
${p.description ? `<div class="prose">${markdown(p.description)}</div>` : ""}
|
||||
${p.kind === "mod" ? `<h2 class="heading">What it may do</h2>${capsHtml}<p class="meta">Mods run in a sandbox with no file, network or clock access. The game refuses a mod whose code uses more than this list.</p>` : ""}
|
||||
${requires}
|
||||
<h2 class="heading">Install</h2>
|
||||
${installHtml(p, v)}
|
||||
<h2 class="heading">File</h2>
|
||||
<dl class="mod-file"><dt>Name</dt><dd><a href="${escape(https(v.file.url))}">${escape(v.file.name)}</a></dd><dt>Size</dt><dd>${size(v.file.size)}</dd><dt>SHA-256</dt><dd><code>${escape(v.file.sha256)}</code></dd>${p.key ? `<dt>Signing key</dt><dd><code>${escape(p.key)}</code></dd>` : ""}</dl>
|
||||
<h2 class="heading">Versions</h2>
|
||||
<ul class="mod-versions">${versions}</ul>
|
||||
<p class="mod-links">${https(p.source) ? `<a class="link-arrow" href="${escape(p.source)}">Source code<span aria-hidden="true">→</span></a>` : ""}
|
||||
<a class="link-arrow" href="${REGISTRY}/blob/main/mods/${escape(p.id)}.toml">Its entry in the registry<span aria-hidden="true">→</span></a>
|
||||
<a class="link-arrow" href="${REGISTRY}/issues/new?template=report.yml&title=${escape(p.id)}">Report it<span aria-hidden="true">→</span></a></p>
|
||||
</article>`;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { CAPABILITIES, listHtml, matches, projectHtml, readIndex } from "./mods.js";
|
||||
|
||||
const project = (over = {}) => ({
|
||||
id: "coords_hud", kind: "mod", name: "Coordinates HUD", summary: "Where you are.", authors: ["Horizon"],
|
||||
license: "MIT", source: "https://example.org/src",
|
||||
versions: [{ version: "0.1.0", api: "0.1", side: "client", capabilities: ["game-read", "hud"], game: "26.3",
|
||||
file: { name: "coords_hud-0.1.0.hmod", url: "https://github.com/ludovic111/horizon-mods/releases/download/x/coords_hud-0.1.0.hmod", size: 438, sha256: "e".repeat(64) } }],
|
||||
...over,
|
||||
});
|
||||
|
||||
test("reads schema 1, keeps the kinds it knows and refuses a newer schema", () => {
|
||||
const index = { schema: 1, projects: [project(), project({ id: "map", kind: "world" }), project({ id: "Bad id" })] };
|
||||
assert.deepEqual(readIndex(index).map((p) => p.id), ["coords_hud"]);
|
||||
assert.equal(readIndex({ schema: 2, projects: [project()] }), null);
|
||||
assert.equal(readIndex(null), null);
|
||||
});
|
||||
|
||||
test("filters by kind and every word", () => {
|
||||
const p = project();
|
||||
assert.ok(matches(p, "all", "coordinates horizon"));
|
||||
assert.ok(matches(p, "mod", ""));
|
||||
assert.ok(!matches(p, "modpack", ""));
|
||||
assert.ok(!matches(p, "all", "zoom"));
|
||||
});
|
||||
|
||||
test("escapes what authors wrote and only links https addresses", () => {
|
||||
const evil = project({ name: "<script>x</script>", source: "javascript:alert(1)", summary: '"><img src=x onerror=alert(1)>' });
|
||||
const html = listHtml([evil]) + projectHtml(evil);
|
||||
assert.ok(!html.includes("<script>x"));
|
||||
assert.ok(!html.includes("<img src=x"));
|
||||
assert.ok(!html.includes("javascript:"));
|
||||
});
|
||||
|
||||
test("a mod's page says what it may do, as the game does", () => {
|
||||
const html = projectHtml(project());
|
||||
assert.ok(html.includes(`May ${CAPABILITIES["game-read"]}`));
|
||||
assert.ok(html.includes("Unsigned"));
|
||||
assert.ok(projectHtml(project({ key: "RWT" })).includes("Signed"));
|
||||
assert.ok(html.includes("horizon-launcher mods install --source horizon coords_hud"));
|
||||
});
|
||||
@@ -726,3 +726,51 @@ code { border-radius: 0; background: var(--well); box-shadow: 0 0 0 1px var(--ou
|
||||
.release-detail { padding-left: 0; margin-left: 0; }
|
||||
.machine { padding: 16px; }
|
||||
}
|
||||
|
||||
/* The registry (/mods): a search and the kind filter, rows as panels, then a page per project. */
|
||||
.mod-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 24px; }
|
||||
.mod-tools { display: flex; flex-wrap: wrap; align-items: center; gap: 16px; margin-top: 32px; }
|
||||
.mod-tools .release-filter { margin-top: 0; }
|
||||
.mod-search {
|
||||
height: 36px; min-width: min(320px, 100%); padding: 0 12px; font: var(--text-ui) / 1 var(--sans); color: var(--ink);
|
||||
background: var(--well); border: var(--block-outline) solid var(--outline); border-radius: 0;
|
||||
}
|
||||
.mod-search:focus-visible { outline: 2px solid var(--accent); outline-offset: 0; }
|
||||
.mod-list { display: grid; gap: 8px; }
|
||||
.mod-row {
|
||||
display: grid; grid-template-columns: 48px minmax(0, 1fr) auto; align-items: center; gap: 16px; padding: 14px 20px;
|
||||
background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); color: var(--ink); text-decoration: none;
|
||||
}
|
||||
.mod-row:hover { background: var(--raised); }
|
||||
.mod-row:hover .mod-name { color: var(--accent); }
|
||||
.mod-icon {
|
||||
display: grid; place-items: center; width: 48px; height: 48px; flex: none; image-rendering: pixelated;
|
||||
font: 600 22px / 1 var(--pixel); color: var(--ink); background: var(--well); box-shadow: 0 0 0 var(--block-outline) var(--outline);
|
||||
}
|
||||
.mod-text { display: grid; gap: 4px; min-width: 0; }
|
||||
.mod-name { font: 500 var(--text-heading) / 1.2 var(--pixel); }
|
||||
.mod-summary { color: var(--muted); font-size: var(--text-ui); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.mod-side { display: grid; justify-items: end; gap: 6px; }
|
||||
.mod-side .badge { margin-right: 0; }
|
||||
.mod-version { font: var(--text-micro) / 1.4 var(--mono); letter-spacing: var(--text-micro-tracking); color: var(--muted); }
|
||||
.mod-empty a { color: var(--accent); }
|
||||
.badge-signed { background: color-mix(in srgb, var(--success) 22%, var(--panel)); color: var(--ink); }
|
||||
.badge-unsigned { background: color-mix(in srgb, var(--warn) 24%, var(--panel)); color: var(--ink); }
|
||||
.mod-page { display: grid; gap: 16px; max-width: calc(var(--measure) + 240px); }
|
||||
.mod-page .heading { margin-top: 24px; }
|
||||
.mod-head { display: grid; grid-template-columns: 96px minmax(0, 1fr); gap: 24px; align-items: start; }
|
||||
.mod-head .mod-icon { width: 96px; height: 96px; font-size: 44px; }
|
||||
.mod-head .page-title { margin-top: 0; }
|
||||
.mod-badges { margin-top: 16px; }
|
||||
.mod-caps, .mod-steps, .mod-versions { display: grid; gap: 8px; padding-left: 20px; font-size: var(--text-ui); }
|
||||
.mod-caps li::marker, .mod-steps li::marker { color: var(--accent); }
|
||||
.mod-file { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 8px 16px; font-size: var(--text-ui); }
|
||||
.mod-file dt { color: var(--muted); }
|
||||
.mod-file code, .mod-steps code { font-family: var(--mono); font-size: 13px; overflow-wrap: anywhere; }
|
||||
.mod-links { display: flex; flex-wrap: wrap; gap: 24px; margin-top: 24px; }
|
||||
@media (max-width: 640px) {
|
||||
.mod-row { grid-template-columns: 40px minmax(0, 1fr); }
|
||||
.mod-side { grid-column: 2; justify-items: start; }
|
||||
.mod-icon { width: 40px; height: 40px; }
|
||||
.mod-head { grid-template-columns: 1fr; }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user