« get me outta code hell

hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/write
diff options
context:
space:
mode:
Diffstat (limited to 'src/write')
-rw-r--r--src/write/bind-utilities.js73
-rw-r--r--src/write/build-modes/index.js3
-rw-r--r--src/write/build-modes/live-dev-server.js505
-rw-r--r--src/write/build-modes/repl.js156
-rw-r--r--src/write/build-modes/static-build.js507
-rw-r--r--src/write/common-templates.js57
6 files changed, 1301 insertions, 0 deletions
diff --git a/src/write/bind-utilities.js b/src/write/bind-utilities.js
new file mode 100644
index 0000000..3d4ecc7
--- /dev/null
+++ b/src/write/bind-utilities.js
@@ -0,0 +1,73 @@
+// Ties lots and lots of functions together in a convenient package accessible
+// to page write functions. This is kept in a separate file from other write
+// areas to keep imports neat and isolated.
+
+import chroma from 'chroma-js';
+
+import {getColors} from '#colors';
+import {bindFind} from '#find';
+import * as html from '#html';
+import {bindOpts} from '#sugar';
+import {thumb} from '#urls';
+
+import {
+  checkIfImagePathHasCachedThumbnails,
+  getDimensionsOfImagePath,
+  getThumbnailEqualOrSmaller,
+  getThumbnailsAvailableForDimensions,
+} from '#thumbs';
+
+export function bindUtilities({
+  absoluteTo,
+  cachebust,
+  defaultLanguage,
+  getSizeOfAdditionalFile,
+  getSizeOfImagePath,
+  language,
+  languages,
+  missingImagePaths,
+  pagePath,
+  thumbsCache,
+  to,
+  urls,
+  wikiData,
+}) {
+  const bound = {};
+
+  Object.assign(bound, {
+    absoluteTo,
+    cachebust,
+    defaultLanguage,
+    getSizeOfAdditionalFile,
+    getSizeOfImagePath,
+    getThumbnailsAvailableForDimensions,
+    html,
+    language,
+    languages,
+    missingImagePaths,
+    pagePath,
+    thumb,
+    to,
+    urls,
+    wikiData,
+    wikiInfo: wikiData.wikiInfo,
+  });
+
+  bound.getColors = bindOpts(getColors, {chroma});
+
+  bound.find = bindFind(wikiData, {mode: 'warn'});
+
+  bound.checkIfImagePathHasCachedThumbnails =
+    (imagePath) =>
+      checkIfImagePathHasCachedThumbnails(imagePath, thumbsCache);
+
+  bound.getDimensionsOfImagePath =
+    (imagePath) =>
+      getDimensionsOfImagePath(imagePath, thumbsCache);
+
+  bound.getThumbnailEqualOrSmaller =
+    (preferred, imagePath) =>
+      getThumbnailEqualOrSmaller(preferred, imagePath, thumbsCache);
+
+  return bound;
+}
diff --git a/src/write/build-modes/index.js b/src/write/build-modes/index.js
new file mode 100644
index 0000000..3ae2cfc
--- /dev/null
+++ b/src/write/build-modes/index.js
@@ -0,0 +1,3 @@
+export * as 'live-dev-server' from './live-dev-server.js';
+export * as 'repl' from './repl.js';
+export * as 'static-build' from './static-build.js';
diff --git a/src/write/build-modes/live-dev-server.js b/src/write/build-modes/live-dev-server.js
new file mode 100644
index 0000000..24e1832
--- /dev/null
+++ b/src/write/build-modes/live-dev-server.js
@@ -0,0 +1,505 @@
+import {spawn} from 'node:child_process';
+import * as http from 'node:http';
+import {readFile, stat} from 'node:fs/promises';
+import * as path from 'node:path';
+import {inspect as nodeInspect} from 'node:util';
+
+import {ENABLE_COLOR, logInfo, logWarn, progressCallAll} from '#cli';
+import {watchContentDependencies} from '#content-dependencies';
+import {quickEvaluate} from '#content-function';
+import * as html from '#html';
+import * as pageSpecs from '#page-specs';
+import {serializeThings} from '#serialize';
+
+import {
+  getPagePathname,
+  getURLsFrom,
+  getURLsFromRoot,
+} from '#urls';
+
+import {bindUtilities} from '../bind-utilities.js';
+import {generateRandomLinkDataJSON, generateRedirectHTML} from '../common-templates.js';
+
+const defaultHost = '0.0.0.0';
+const defaultPort = 8002;
+
+export const description = `Hosts a local HTTP server which generates page content as it is requested, instead of all at once; reacts to changes in data files, so new reloads will be up-to-date with on-disk YAML data (<- not implemented yet, check back soon!)\n\nIntended for local development ONLY; this custom HTTP server is NOT rigorously tested and almost certainly has security flaws`;
+
+export const config = {
+  fileSizes: {
+    default: true,
+  },
+
+  languageReloading: {
+    default: true,
+  },
+
+  mediaValidation: {
+    default: true,
+  },
+
+  thumbs: {
+    default: true,
+  },
+};
+
+function inspect(value, opts = {}) {
+  return nodeInspect(value, {colors: ENABLE_COLOR, ...opts});
+}
+
+export function getCLIOptions() {
+  return {
+    host: {
+      help: `Hostname to which HTTP server is bound\nDefaults to ${defaultHost}`,
+      type: 'value',
+    },
+
+    port: {
+      help: `Port to which HTTP server is bound\nDefaults to ${defaultPort}`,
+      type: 'value',
+      validate(size) {
+        if (parseInt(size) !== parseFloat(size)) return 'an integer';
+        if (parseInt(size) < 1024 || parseInt(size) > 49151) return 'a user/registered port (1024-49151)';
+        return true;
+      },
+    },
+
+    'loud-responses': {
+      help: `Enables outputting [200] and [404] responses in the server log, which are suppressed by default`,
+      type: 'flag',
+    },
+
+    'show-timings': {
+      help: `Enables outputting timings in the server log for how long pages to take to generate`,
+      type: 'flag',
+    },
+
+    'serve-sfx': {
+      help: `Plays the specified sound file once the HTTP server is ready (this requires mpv)`,
+      type: 'value',
+    },
+
+    'skip-serving': {
+      help: `Causes the build to exit when it would start serving over HTTP instead\n\nMainly useful for testing performance`,
+      type: 'flag',
+    },
+  };
+}
+
+export async function go({
+  cliOptions,
+  _dataPath,
+  mediaPath,
+  mediaCachePath,
+
+  defaultLanguage,
+  languages,
+  missingImagePaths,
+  srcRootPath,
+  thumbsCache,
+  urls,
+  wikiData,
+
+  cachebust,
+  developersComment: _developersComment,
+  getSizeOfAdditionalFile,
+  getSizeOfImagePath,
+  niceShowAggregate,
+}) {
+  const showError = (error) => {
+    if (niceShowAggregate) {
+      if (error.errors || error.cause) {
+        niceShowAggregate(error);
+        return;
+      }
+    }
+
+    console.error(inspect(error, {depth: Infinity}));
+  };
+
+  const host = cliOptions['host'] ?? defaultHost;
+  const port = parseInt(cliOptions['port'] ?? defaultPort);
+  const loudResponses = cliOptions['loud-responses'] ?? false;
+  const showTimings = cliOptions['show-timings'] ?? false;
+  const skipServing = cliOptions['skip-serving'] ?? false;
+  const serveSFX = cliOptions['serve-sfx'] ?? null;
+
+  const contentDependenciesWatcher = await watchContentDependencies({
+    showAggregate: niceShowAggregate,
+  });
+
+  const {contentDependencies} = contentDependenciesWatcher;
+
+  contentDependenciesWatcher.on('error', () => {});
+  await new Promise(resolve => contentDependenciesWatcher.once('ready', resolve));
+
+  let targetSpecPairs = getPageSpecsWithTargets({wikiData});
+  const pages = progressCallAll(`Computing page data & paths for ${targetSpecPairs.length} targets.`,
+    targetSpecPairs.flatMap(({
+      pageSpec,
+      target,
+      targetless,
+    }) => () => {
+      if (targetless) {
+        const result = pageSpec.pathsTargetless({wikiData});
+        return Array.isArray(result) ? result : [result];
+      } else {
+        return pageSpec.pathsForTarget(target);
+      }
+    })).flat();
+
+  logInfo`Will be serving a total of ${pages.length} pages.`;
+
+  const urlToPageMap = Object.fromEntries(pages
+    .filter(page => page.type === 'page' || page.type === 'redirect')
+    .flatMap(page => {
+      let servePath;
+      if (page.type === 'page')
+        servePath = page.path;
+      else if (page.type === 'redirect')
+        servePath = page.fromPath;
+
+      return Object.values(languages).map(language => {
+        const baseDirectory =
+          language === defaultLanguage ? '' : language.code;
+
+        const pathname = getPagePathname({
+          baseDirectory,
+          pagePath: servePath,
+          urls,
+        });
+
+        return [pathname, {
+          baseDirectory,
+          language,
+          page,
+          servePath,
+        }];
+      });
+    }));
+
+  const server = http.createServer(async (request, response) => {
+    const contentTypeHTML = {'Content-Type': 'text/html; charset=utf-8'};
+    const contentTypeJSON = {'Content-Type': 'application/json; charset=utf-8'};
+    const contentTypePlain = {'Content-Type': 'text/plain; charset=utf-8'};
+
+    const requestTime = new Date().toLocaleDateString('en-US', {hour: '2-digit', minute: '2-digit', second: '2-digit'});
+    const requestHead =
+      (loudResponses
+        ? `${requestTime} - ${request.socket.remoteAddress}`
+        : `${requestTime}`);
+
+    let url;
+    try {
+      url = new URL(request.url, `http://${request.headers.host}`);
+    } catch (error) {
+      response.writeHead(500, contentTypePlain);
+      response.end('Failed to parse request URL\n');
+      return;
+    }
+
+    const {pathname} = url;
+
+    // Specialized routes
+
+    if (pathname === '/random-link-data.json') {
+      try {
+        const json = generateRandomLinkDataJSON({
+          serializeThings,
+          wikiData,
+        });
+
+        response.writeHead(200, contentTypeJSON);
+        response.end(json);
+        if (loudResponses) console.log(`${requestHead} [200] ${pathname}`);
+      } catch (error) {
+        response.writeHead(500, contentTypeJSON);
+        response.end(`Internal error serializing wiki JSON`);
+        console.error(`${requestHead} [500] ${pathname}`);
+        showError(error);
+      }
+      return;
+    }
+
+    const {
+      area: localFileArea,
+      path: localFilePath
+    } = pathname.match(/^\/(?<area>static|util|media|thumb)\/(?<path>.*)/)?.groups ?? {};
+
+    if (localFileArea) {
+      // Not security tested, man, this is a dev server!!
+      const safePath = path.posix.resolve('/', localFilePath).replace(/^\//, '');
+
+      let localDirectory;
+      if (localFileArea === 'static' || localFileArea === 'util') {
+        localDirectory = path.join(srcRootPath, localFileArea);
+      } else if (localFileArea === 'media') {
+        localDirectory = mediaPath;
+      } else if (localFileArea === 'thumb') {
+        localDirectory = mediaCachePath;
+      }
+
+      let filePath;
+      try {
+        filePath = path.resolve(localDirectory, decodeURI(safePath.split('/').join(path.sep)));
+      } catch (error) {
+        response.writeHead(404, contentTypePlain);
+        response.end(`No ${localFileArea} file found for: ${safePath}`);
+        console.log(`${requestHead} [404] ${pathname}`);
+        console.log(`Failed to decode request pathname`);
+      }
+
+      try {
+        await stat(filePath);
+      } catch (error) {
+        if (error.code === 'ENOENT') {
+          response.writeHead(404, contentTypePlain);
+          response.end(`No ${localFileArea} file found for: ${safePath}`);
+          console.log(`${requestHead} [404] ${pathname}`);
+          console.log(`ENOENT for stat: ${filePath}`);
+        } else {
+          response.writeHead(500, contentTypePlain);
+          response.end(`Internal error accessing ${localFileArea} file for: ${safePath}`);
+          console.error(`${requestHead} [500] ${pathname}`);
+          showError(error);
+        }
+        return;
+      }
+
+      const extname = path.extname(safePath).slice(1).toLowerCase();
+
+      const contentType = {
+        // BRB covering all my bases
+        'aac': 'audio/aac',
+        'bmp': 'image/bmp',
+        'css': 'text/css',
+        'csv': 'text/csv',
+        'gif': 'image/gif',
+        'ico': 'image/vnd.microsoft.icon',
+        'jpg': 'image/jpeg',
+        'jpeg': 'image/jpeg',
+        'js': 'text/javascript',
+        'mjs': 'text/javascript',
+        'mp3': 'audio/mpeg',
+        'mp4': 'video/mp4',
+        'oga': 'audio/ogg',
+        'ogg': 'audio/ogg',
+        'ogv': 'video/ogg',
+        'opus': 'audio/opus',
+        'png': 'image/png',
+        'pdf': 'application/pdf',
+        'svg': 'image/svg+xml',
+        'ttf': 'font/ttf',
+        'txt': 'text/plain',
+        'wav': 'audio/wav',
+        'weba': 'audio/webm',
+        'webm': 'video/webm',
+        'woff': 'font/woff',
+        'woff2': 'font/woff2',
+        'xml': 'application/xml',
+        'zip': 'application/zip',
+      }[extname];
+
+      try {
+        const {size} = await stat(filePath);
+        const buffer = await readFile(filePath)
+        response.writeHead(200, contentType ? {
+          'Content-Type': contentType,
+          'Content-Length': size,
+        } : {});
+        response.end(buffer);
+        if (loudResponses) console.log(`${requestHead} [200] ${pathname}`);
+      } catch (error) {
+        response.writeHead(500, contentTypePlain);
+        response.end(`Failed during file-to-response pipeline`);
+        console.error(`${requestHead} [500] ${pathname}`);
+        showError(error);
+      }
+      return;
+    }
+
+    // Other routes determined by page and URL specs
+
+    // URL to page map expects trailing slash but no leading slash.
+    const pathnameKey = pathname.replace(/^\//, '') + (pathname.endsWith('/') ? '' : '/');
+
+    if (!Object.hasOwn(urlToPageMap, pathnameKey)) {
+      response.writeHead(404, contentTypePlain);
+      response.end(`No page found for: ${pathnameKey}\n`);
+      if (loudResponses) console.log(`${requestHead} [404] ${pathname}`);
+      return;
+    }
+
+    // All pages expect to be served at a URL with a trailing slash, which must
+    // be fulfilled for relative URLs (ex. href="../lofam5/") to work. Redirect
+    // if there is no trailing slash in the request URL.
+    if (!pathname.endsWith('/')) {
+      const target = pathname + '/';
+      response.writeHead(301, {
+        ...contentTypePlain,
+        'Location': target,
+      });
+      response.end(`Redirecting to: ${target}\n`);
+      console.log(`${requestHead} [301] (trl. slash) ${pathname}`);
+      return;
+    }
+
+    const {
+      baseDirectory,
+      language,
+      page,
+      servePath,
+    } = urlToPageMap[pathnameKey];
+
+    const to = getURLsFrom({
+      baseDirectory,
+      pagePath: servePath,
+      urls,
+    });
+
+    const absoluteTo = getURLsFromRoot({
+      baseDirectory,
+      urls,
+    });
+
+    try {
+      if (page.type === 'redirect') {
+        const title =
+          page.title ??
+          page.getTitle?.({language});
+
+        const target = to('localized.' + page.toPath[0], ...page.toPath.slice(1));
+
+        response.writeHead(301, {
+          ...contentTypeHTML,
+          'Location': target,
+        });
+
+        const redirectHTML = generateRedirectHTML(title, target, {language});
+
+        response.end(redirectHTML);
+
+        console.log(`${requestHead} [301] (redirect) ${pathname}`);
+        return;
+      }
+
+      const timeStart = Date.now();
+
+      const bound = bindUtilities({
+        absoluteTo,
+        cachebust,
+        defaultLanguage,
+        getSizeOfAdditionalFile,
+        getSizeOfImagePath,
+        language,
+        languages,
+        missingImagePaths,
+        pagePath: servePath,
+        thumbsCache,
+        to,
+        urls,
+        wikiData,
+      });
+
+      const topLevelResult =
+        quickEvaluate({
+          contentDependencies,
+          extraDependencies: {...bound, appendIndexHTML: false},
+
+          name: page.contentFunction.name,
+          args: page.contentFunction.args ?? [],
+        });
+
+      const {pageHTML} = html.resolve(topLevelResult);
+
+      const timeEnd = Date.now();
+      const timeDelta = timeEnd - timeStart;
+
+      if (showTimings) {
+        const timeString =
+          (timeDelta > 100
+            ? `${(timeDelta / 1000).toFixed(2)}s`
+            : `${timeDelta}ms`);
+
+        console.log(`${requestHead} [200, ${timeString}] ${pathname}`);
+      } else if (loudResponses) {
+        console.log(`${requestHead} [200] ${pathname}`);
+      }
+
+      response.writeHead(200, contentTypeHTML);
+      response.end(pageHTML);
+    } catch (error) {
+      console.error(`${requestHead} [500] ${pathname}`);
+      showError(error);
+      response.writeHead(500, contentTypePlain);
+      response.end(`Error generating page, view server log for details\n`);
+    }
+  });
+
+  const address = `http://${host}:${port}/`;
+
+  server.on('error', error => {
+    if (error.code === 'EADDRINUSE') {
+      logWarn`Port ${port} is already in use - will (continually) retry after 10 seconds.`;
+      logWarn`Press ^C here (control+C) to exit and change ${'--port'} number, or stop the server currently running on port ${port}.`;
+      setTimeout(() => {
+        server.close();
+        server.listen(port, host);
+      }, 10_000);
+    } else {
+      console.error(`Server error detected (code: ${error.code})`);
+      showError(error);
+    }
+  });
+
+  server.on('listening', () => {
+    logInfo`${'All done!'} Listening at: ${address}`;
+    logInfo`Press ^C here (control+C) to stop the server and exit.`;
+    if (showTimings && loudResponses) {
+      logInfo`Printing all HTTP responses, plus page generation timings.`;
+    } else if (showTimings) {
+      logInfo`Printing page generation timings.`;
+    } else if (loudResponses) {
+      logInfo`Printing all HTTP responses.`
+    } else {
+      logInfo`Suppressing [200] and [404] response logging.`
+      logInfo`(Pass --loud-responses to show these.)`;
+    }
+
+    if (serveSFX) {
+      spawn('mpv', [serveSFX, '--volume=75']);
+    }
+  });
+
+  if (skipServing) {
+    logInfo`Ready to serve! But --skip-serving was passed, so all done.`;
+  } else {
+    process.on('SIGINT', () => {
+      process.stdout.write('\n');
+      server.close();
+    });
+
+    await new Promise(resolve => {
+      server.listen(port, host);
+      server.on('close', () => resolve());
+    });
+  }
+
+  return true;
+}
+
+function getPageSpecsWithTargets({
+  wikiData,
+}) {
+  return Object.values(pageSpecs)
+    .filter(pageSpec => pageSpec.condition?.({wikiData}) ?? true)
+    .flatMap(pageSpec => [
+      ...pageSpec.targets
+        ? pageSpec.targets({wikiData})
+            .map(target => ({pageSpec, target}))
+        : [],
+      Object.hasOwn(pageSpec, 'pathsTargetless') &&
+        {pageSpec, targetless: true},
+    ])
+    .filter(Boolean);
+}
diff --git a/src/write/build-modes/repl.js b/src/write/build-modes/repl.js
new file mode 100644
index 0000000..2098559
--- /dev/null
+++ b/src/write/build-modes/repl.js
@@ -0,0 +1,156 @@
+export const description = `Provide command-line interactive access to wiki data objects`;
+
+export const config = {
+  fileSizes: {
+    default: 'skip',
+  },
+
+  languageReloading: {
+    default: true,
+  },
+
+  mediaValidation: {
+    default: 'skip',
+  },
+
+  thumbs: {
+    applicable: false,
+  },
+};
+
+export function getCLIOptions() {
+  return {
+    'no-repl-history': {
+      help: `Disable locally logging commands entered into the REPL in your home directory`,
+      type: 'flag',
+    },
+  };
+}
+
+import * as os from 'node:os';
+import * as path from 'node:path';
+import * as repl from 'node:repl';
+
+import _find, {bindFind} from '#find';
+import CacheableObject from '#cacheable-object';
+import {logWarn} from '#cli';
+import {debugComposite} from '#composite';
+import * as serialize from '#serialize';
+import * as sort from '#sort';
+import * as sugar from '#sugar';
+import thingConstructors from '#things';
+import * as wikiDataUtils from '#wiki-data';
+
+export async function getContextAssignments({
+  dataPath,
+  mediaPath,
+  mediaCachePath,
+
+  defaultLanguage,
+  languages,
+  missingImagePaths,
+  thumbsCache,
+  urls,
+  wikiData,
+
+  getSizeOfAdditionalFile,
+  getSizeOfImagePath,
+  niceShowAggregate,
+}) {
+  let find;
+  try {
+    find = bindFind(wikiData);
+  } catch (error) {
+    console.error(error);
+    logWarn`Failed to prepare wikiData-bound find() functions`;
+    logWarn`\`find\` variable will be missing`;
+  }
+
+  const replContext = {
+    dataPath,
+    mediaPath,
+    mediaCachePath,
+
+    languages,
+    defaultLanguage,
+    language: defaultLanguage,
+
+    missingImagePaths,
+    thumbsCache,
+    urls,
+
+    wikiData,
+    ...wikiData,
+    WD: wikiData,
+
+    ...thingConstructors,
+    CacheableObject,
+    debugComposite,
+
+    ...sort,
+    ...sugar,
+    ...wikiDataUtils,
+
+    serialize,
+    S: serialize,
+
+    _find,
+    find,
+    bindFind,
+
+    getSizeOfAdditionalFile,
+    getSizeOfImagePath,
+    showAggregate: niceShowAggregate,
+  };
+
+  replContext.replContext = replContext;
+
+  return replContext;
+}
+
+export async function go(buildOptions) {
+  const {
+    cliOptions,
+    closeLanguageWatchers,
+  } = buildOptions;
+
+  const disableHistory = cliOptions['no-repl-history'] ?? false;
+
+  console.log('HSMusic data REPL');
+
+  const replServer = repl.start();
+
+  Object.assign(replServer.context,
+    await getContextAssignments(buildOptions));
+
+  if (disableHistory) {
+    console.log(`\rInput history disabled (--no-repl-history provided)`);
+  } else {
+    const historyFile = path.join(os.homedir(), '.hsmusic_repl_history');
+    await new Promise(resolve => {
+      replServer.setupHistory(historyFile, (err) => {
+        if (err) {
+          console.error(`\rFailed to begin locally logging input history to ${historyFile} (provide --no-repl-history to disable)`);
+        } else {
+          console.log(`\rLogging input history to ${historyFile} (provide --no-repl-history to disable)`);
+        }
+        resolve();
+      });
+    });
+  }
+
+  replServer.displayPrompt(true);
+
+  let resolveDone;
+
+  replServer.on('exit', () => {
+    closeLanguageWatchers();
+    resolveDone();
+  });
+
+  await new Promise(resolve => {
+    resolveDone = resolve;
+  });
+
+  return true;
+}
diff --git a/src/write/build-modes/static-build.js b/src/write/build-modes/static-build.js
new file mode 100644
index 0000000..a355a00
--- /dev/null
+++ b/src/write/build-modes/static-build.js
@@ -0,0 +1,507 @@
+import * as path from 'node:path';
+
+import {
+  copyFile,
+  mkdir,
+  stat,
+  symlink,
+  writeFile,
+  unlink,
+} from 'node:fs/promises';
+
+import {quickLoadContentDependencies} from '#content-dependencies';
+import {quickEvaluate} from '#content-function';
+import * as html from '#html';
+import * as pageSpecs from '#page-specs';
+import {empty, queue, withEntries} from '#sugar';
+
+import {
+  fileIssue,
+  logError,
+  logInfo,
+  logWarn,
+  progressPromiseAll,
+} from '#cli';
+
+import {
+  getPagePathname,
+  getURLsFrom,
+  getURLsFromRoot,
+} from '#urls';
+
+import {bindUtilities} from '../bind-utilities.js';
+import {generateRedirectHTML, generateRandomLinkDataJSON} from '../common-templates.js';
+
+const pageFlags = Object.keys(pageSpecs);
+
+export const description = `Generates all page content in one build (according to the contents of data files at build time) and writes them to disk, preparing the output folder for upload and serving by any static web host\n\nIntended for any production or public-facing release of a wiki; serviceable for local development, but can be a bit unwieldy and time/CPU-expensive`;
+
+export const config = {
+  fileSizes: {
+    default: true,
+  },
+
+  languageReloading: {
+    applicable: false,
+  },
+
+  mediaValidation: {
+    default: true,
+  },
+
+  thumbs: {
+    default: true,
+  },
+};
+
+export function getCLIOptions() {
+  return {
+    // This is the output directory. It's the one you'll upload online with
+    // rsync or whatever when you're pushing an upd8, and also the one
+    // you'd archive if you wanted to make a 8ackup of the whole dang
+    // site. Just keep in mind that the gener8ted result will contain a
+    // couple symlinked directories, so if you're uploading, you're pro8a8ly
+    // gonna want to resolve those yourself.
+    'out-path': {
+      help: `Specify path to output directory, into which HTML page files and other output are written and other directories are linked\n\nAlways required alongside --static-build mode, but may be provided via the HSMUSIC_OUT environment variable instead`,
+      type: 'value',
+    },
+
+    // Working without a dev server and just using file:// URLs in your we8
+    // 8rowser? This will automatically append index.html to links across
+    // the site. Not recommended for production, since it isn't guaranteed
+    // 100% error-free (and index.html-style links are less pretty anyway).
+    'append-index-html': {
+      help: `Apply "index.html" to the end of page links, instead of just linking to the directory (ex. "/track/ng2yu/"); useful when no local server hosting option is available and browsing build output directly off the disk drive\n\nDefinitely not intended for production: this option isn't extensively tested and may include conspicuous oddities`,
+      type: 'flag',
+    },
+
+    // Only want to 8uild one language during testing? This can chop down
+    // 8uild times a pretty 8ig chunk! Just pass a single language code.
+    'lang': {
+      help: `Skip rest and build only pages for this locale language (specify a language code)`,
+      type: 'value',
+    },
+
+    // NOT for neatly ena8ling or disa8ling specific features of the site!
+    // This is only in charge of what general groups of files to write.
+    // They're here to make development quicker when you're only working
+    // on some particular area(s) of the site rather than making changes
+    // across all of them.
+    ...withEntries(pageSpecs, entries => entries.map(
+      ([key, spec]) => [key, {
+        help: spec.description &&
+          `Skip rest and build only:\n${spec.description}`,
+        type: 'flag',
+      }])),
+  };
+}
+
+export async function go({
+  cliOptions,
+  _dataPath,
+  mediaPath,
+  mediaCachePath,
+  queueSize,
+
+  defaultLanguage,
+  languages,
+  missingImagePaths,
+  srcRootPath,
+  thumbsCache,
+  urls,
+  wikiData,
+
+  cachebust,
+  developersComment: _developersComment,
+  getSizeOfAdditionalFile,
+  getSizeOfImagePath,
+  niceShowAggregate,
+}) {
+  const outputPath = cliOptions['out-path'] || process.env.HSMUSIC_OUT;
+  const appendIndexHTML = cliOptions['append-index-html'] ?? false;
+  const writeOneLanguage = cliOptions['lang'] ?? null;
+
+  if (!outputPath) {
+    logError`Expected ${'--out-path'} option or ${'HSMUSIC_OUT'} to be set`;
+    return false;
+  }
+
+  if (appendIndexHTML) {
+    logWarn`Appending index.html to link hrefs. (Note: not recommended for production release!)`;
+  }
+
+  if (writeOneLanguage && !(writeOneLanguage in languages)) {
+    logError`Specified to write only ${writeOneLanguage}, but there is no strings file with this language code!`;
+    return false;
+  } else if (writeOneLanguage) {
+    logInfo`Writing only language ${writeOneLanguage} this run.`;
+  } else {
+    logInfo`Writing all languages.`;
+  }
+
+  const selectedPageFlags = Object.keys(cliOptions)
+    .filter(key => pageFlags.includes(key));
+
+  const writeAll = empty(selectedPageFlags) || selectedPageFlags.includes('all');
+  logInfo`Writing site pages: ${writeAll ? 'all' : selectedPageFlags.join(', ')}`;
+
+  await mkdir(outputPath, {recursive: true});
+
+  await writeSymlinks({
+    srcRootPath,
+    mediaPath,
+    mediaCachePath,
+    outputPath,
+    urls,
+  });
+
+  if (writeAll) {
+    await writeFavicon({
+      mediaPath,
+      outputPath,
+    });
+
+    await writeSharedFilesAndPages({
+      outputPath,
+      randomLinkDataJSON: generateRandomLinkDataJSON({wikiData}),
+    });
+  } else {
+    logInfo`Skipping favicon and shared files (not writing all site pages).`
+  }
+
+  const buildSteps = writeAll
+    ? Object.entries(pageSpecs)
+    : Object.entries(pageSpecs)
+        .filter(([flag]) => selectedPageFlags.includes(flag));
+
+  let writes;
+  {
+    let error = false;
+
+    // TODO: Port this to aggregate error
+    writes = buildSteps
+      .map(([flag, pageSpec]) => {
+        if (pageSpec.condition && !pageSpec.condition({wikiData})) {
+          return null;
+        }
+
+        const paths = [];
+
+        if (pageSpec.pathsTargetless) {
+          const result = pageSpec.pathsTargetless({wikiData});
+          if (Array.isArray(result)) {
+            paths.push(...result);
+          } else {
+            paths.push(result);
+          }
+        }
+
+        if (pageSpec.targets) {
+          if (!pageSpec.pathsForTarget) {
+            logError`${flag + '.targets'} is specified, but ${flag + '.pathsForTarget'} is missing!`;
+            error = true;
+            return null;
+          }
+
+          const targets = pageSpec.targets({wikiData});
+
+          if (!Array.isArray(targets)) {
+            logError`${flag + '.targets'} was called, but it didn't return an array! (${targets})`;
+            error = true;
+            return null;
+          }
+
+          paths.push(...targets.flatMap(target => pageSpec.pathsForTarget(target)));
+          // TODO: Validate each pathsForTargets entry
+        }
+
+        return paths;
+      })
+      .filter(Boolean)
+      .flat();
+
+    if (error) {
+      return false;
+    }
+  }
+
+  const pageWrites = writes.filter(({type}) => type === 'page');
+  const dataWrites = writes.filter(({type}) => type === 'data');
+  const redirectWrites = writes.filter(({type}) => type === 'redirect');
+
+  if (writes.length) {
+    logInfo`Total of ${writes.length} writes returned. (${pageWrites.length} page, ${dataWrites.length} data [currently skipped], ${redirectWrites.length} redirect)`;
+  } else {
+    logWarn`No writes returned at all, so exiting early. This is probably a bug!`;
+    return false;
+  }
+
+  /*
+  await progressPromiseAll(`Writing data files shared across languages.`, queue(
+    dataWrites.map(({path, data}) => () => {
+      const bound = {};
+
+      bound.serializeLink = bindOpts(serializeLink, {});
+
+      bound.serializeContribs = bindOpts(serializeContribs, {});
+
+      bound.serializeImagePaths = bindOpts(serializeImagePaths, {
+        thumb
+      });
+
+      bound.serializeCover = bindOpts(serializeCover, {
+        [bindOpts.bindIndex]: 2,
+        serializeImagePaths: bound.serializeImagePaths,
+        urls
+      });
+
+      bound.serializeGroupsForAlbum = bindOpts(serializeGroupsForAlbum, {
+        serializeLink
+      });
+
+      bound.serializeGroupsForTrack = bindOpts(serializeGroupsForTrack, {
+        serializeLink
+      });
+
+      // TODO: This only supports one <>-style argument.
+      return writeData(path[0], path[1], data({...bound}));
+    }),
+    queueSize
+  ));
+  */
+
+  let errored = false;
+
+  const contentDependencies = await quickLoadContentDependencies({
+    showAggregate: niceShowAggregate,
+  });
+
+  const perLanguageFn = async (language, i, entries) => {
+    const baseDirectory =
+      language === defaultLanguage ? '' : language.code;
+
+    console.log(`\x1b[34;1m${`[${i + 1}/${entries.length}] ${language.code} (-> /${baseDirectory}) `.padEnd(60, '-')}\x1b[0m`);
+
+    await progressPromiseAll(`Writing ${language.code}`, queue([
+      ...pageWrites.map(page => () => {
+        const pagePath = page.path;
+
+        const pathname = getPagePathname({
+          baseDirectory,
+          pagePath,
+          urls,
+        });
+
+        const to = getURLsFrom({
+          baseDirectory,
+          pagePath,
+          urls,
+        });
+
+        const absoluteTo = getURLsFromRoot({
+          baseDirectory,
+          urls,
+        });
+
+        const bound = bindUtilities({
+          absoluteTo,
+          cachebust,
+          defaultLanguage,
+          getSizeOfAdditionalFile,
+          getSizeOfImagePath,
+          language,
+          languages,
+          missingImagePaths,
+          pagePath,
+          thumbsCache,
+          to,
+          urls,
+          wikiData,
+        });
+
+        let pageHTML, oEmbedJSON;
+        try {
+          const topLevelResult =
+            quickEvaluate({
+              contentDependencies,
+              extraDependencies: {...bound, appendIndexHTML},
+
+              name: page.contentFunction.name,
+              args: page.contentFunction.args ?? [],
+            });
+
+          ({pageHTML, oEmbedJSON} = html.resolve(topLevelResult));
+        } catch (error) {
+          logError`\rError generating page: ${pathname}`;
+          niceShowAggregate(error);
+          errored = true;
+          return;
+        }
+
+        return writePage({
+          pageHTML,
+          oEmbedJSON,
+          outputDirectory: path.join(outputPath, getPagePathname({
+            baseDirectory,
+            device: true,
+            pagePath,
+            urls,
+          })),
+        });
+      }),
+
+      ...redirectWrites.map(({fromPath, toPath, title, getTitle}) => () => {
+        title ??= getTitle?.({language});
+
+        const to = getURLsFrom({
+          baseDirectory,
+          pagePath: fromPath,
+          urls,
+        });
+
+        const target = to('localized.' + toPath[0], ...toPath.slice(1));
+        const pageHTML = generateRedirectHTML(title, target, {language});
+
+        return writePage({
+          pageHTML,
+          outputDirectory: path.join(outputPath, getPagePathname({
+            baseDirectory,
+            device: true,
+            pagePath: fromPath,
+            urls,
+          })),
+        });
+      }),
+    ], queueSize));
+  };
+
+  await wrapLanguages(perLanguageFn, {
+    languages,
+    writeOneLanguage,
+  });
+
+  // The single most important step.
+  logInfo`Written!`;
+
+  if (errored) {
+    logWarn`The code generating content for some pages ended up erroring.`;
+    logWarn`These pages were skipped, so if you ran a build previously and`;
+    logWarn`they didn't error that time, then the old version is still`;
+    logWarn`available - albeit possibly outdated! Please scroll up and send`;
+    logWarn`the HSMusic developers a copy of the errors:`;
+    fileIssue({topMessage: null});
+
+    return false;
+  }
+
+  return true;
+}
+
+// Wrapper function for running a function once for all languages.
+async function wrapLanguages(fn, {
+  languages,
+  writeOneLanguage = null,
+}) {
+  const k = writeOneLanguage;
+  const languagesToRun = k ? {[k]: languages[k]} : languages;
+
+  const entries = Object.entries(languagesToRun).filter(
+    ([key]) => key !== 'default'
+  );
+
+  for (let i = 0; i < entries.length; i++) {
+    const [_key, language] = entries[i];
+
+    await fn(language, i, entries);
+  }
+}
+
+async function writePage({
+  pageHTML,
+  oEmbedJSON = '',
+  outputDirectory,
+}) {
+  await mkdir(outputDirectory, {recursive: true});
+
+  await Promise.all([
+    writeFile(path.join(outputDirectory, 'index.html'), pageHTML),
+
+    oEmbedJSON &&
+      writeFile(path.join(outputDirectory, 'oembed.json'), oEmbedJSON),
+  ].filter(Boolean));
+}
+
+function writeSymlinks({
+  srcRootPath,
+  mediaPath,
+  mediaCachePath,
+  outputPath,
+  urls,
+}) {
+  return progressPromiseAll('Writing site symlinks.', [
+    link(path.join(srcRootPath, 'util'), 'shared.utilityRoot'),
+    link(path.join(srcRootPath, 'static'), 'shared.staticRoot'),
+    link(mediaPath, 'media.root'),
+    link(mediaCachePath, 'thumb.root'),
+  ]);
+
+  async function link(directory, urlKey) {
+    const pathname = urls.from('shared.root').toDevice(urlKey);
+    const file = path.join(outputPath, pathname);
+
+    try {
+      await unlink(file);
+    } catch (error) {
+      if (error.code !== 'ENOENT') {
+        throw error;
+      }
+    }
+
+    try {
+      await symlink(path.resolve(directory), file);
+    } catch (error) {
+      if (error.code === 'EPERM') {
+        await symlink(path.resolve(directory), file, 'junction');
+      } else {
+        throw error;
+      }
+    }
+  }
+}
+
+async function writeFavicon({
+  mediaPath,
+  outputPath,
+}) {
+  const faviconFile = 'favicon.ico';
+
+  try {
+    await stat(path.join(mediaPath, faviconFile));
+  } catch (error) {
+    return;
+  }
+
+  try {
+    await copyFile(
+      path.join(mediaPath, faviconFile),
+      path.join(outputPath, faviconFile));
+  } catch (error) {
+    logWarn`Failed to copy favicon! ${error.message}`;
+    return;
+  }
+
+  logInfo`Copied favicon to site root.`;
+}
+
+async function writeSharedFilesAndPages({
+  outputPath,
+  randomLinkDataJSON,
+}) {
+  return progressPromiseAll(`Writing files & pages shared across languages.`, [
+    randomLinkDataJSON &&
+      writeFile(
+        path.join(outputPath, 'random-link-data.json'),
+        randomLinkDataJSON),
+  ].filter(Boolean));
+}
diff --git a/src/write/common-templates.js b/src/write/common-templates.js
new file mode 100644
index 0000000..c9824a4
--- /dev/null
+++ b/src/write/common-templates.js
@@ -0,0 +1,57 @@
+import * as html from '#html';
+import {getArtistNumContributions} from '#wiki-data';
+
+export function generateRedirectHTML(title, target, {language}) {
+  return `<!DOCTYPE html>\n` + html.tag('html', [
+    html.tag('head', [
+      html.tag('title', language.$('redirectPage.title', {title})),
+      html.tag('meta', {charset: 'utf-8'}),
+
+      html.tag('meta', {
+        'http-equiv': 'refresh',
+        content: `0;url=${target}`,
+      }),
+
+      // TODO: Is this OK for localized pages?
+      html.tag('link', {
+        rel: 'canonical',
+        href: target,
+      }),
+    ]),
+
+    html.tag('body',
+      html.tag('main', [
+        html.tag('h1',
+          language.$('redirectPage.title', {title})),
+        html.tag('p',
+          language.$('redirectPage.infoLine', {
+            target: html.tag('a', {href: target}, target),
+          })),
+      ])),
+  ]);
+}
+
+export function generateRandomLinkDataJSON({wikiData}) {
+  const {albumData, artistData} = wikiData;
+
+  return JSON.stringify({
+    albumDirectories:
+      albumData
+        .map(album => album.directory),
+
+    albumTrackDirectories:
+      albumData
+        .map(album => album.tracks
+          .map(track => track.directory)),
+
+    artistDirectories:
+      artistData
+        .filter(artist => !artist.isAlias)
+        .map(artist => artist.directory),
+
+    artistNumContributions:
+      artistData
+        .filter(artist => !artist.isAlias)
+        .map(artist => getArtistNumContributions(artist)),
+  });
+}