Skip to content
Python
3.5 KB
Raw Blame
// Package the static review site. Never deploy the marketing site or build server.
import {readdir, readFile, mkdir, writeFile} from 'node:fs/promises';
import {resolve, join} from 'node:path';
import {createHash} from 'node:crypto';

const [input, output, revision] = process.argv.slice(2);
if (!input || !output || !/^[a-f0-9]{40}$/.test(revision ?? '')) throw new Error('Usage: node prepare-hosting.mjs <dist> <new-release-dir> <git-sha>');
if (resolve(input) === resolve(output)) throw new Error('Use a separate release directory');
await mkdir(output); // Refuse to reuse an old release.
const files = [];
async function visit(dir = '') {
  for (const entry of await readdir(join(input, dir), {withFileTypes: true})) {
    const relative = dir ? `${dir}/${entry.name}` : entry.name;
    if (relative === 'previews' || /^sitemap.*\.xml$/.test(relative)) continue;
    if (entry.isSymbolicLink()) throw new Error(`Symlink: ${relative}`);
    if (entry.isDirectory()) { await visit(relative); continue; }
    if (!entry.isFile() || /(^|\/)\./.test(relative) || relative.endsWith('.map')) throw new Error(`Unexpected build artifact: ${relative}`);
    let content = await readFile(join(input, relative));
    if (relative.endsWith('.html')) {
      let html = content.toString();
      if (!html.includes('</head>')) throw new Error(`Missing head: ${relative}`);
      html = html.replace(/<meta\b[^>]*name=["']robots["'][^>]*>/gi, '');
      content = Buffer.from(html.replace('</head>', '<meta name="robots" content="noindex, nofollow"/></head>'));
    }
    await mkdir(join(output, 'files', dir), {recursive: true});
    await writeFile(join(output, 'files', relative), content);
    files.push({path: relative, sha256: createHash('sha256').update(content).digest('hex'), size: content.length});
  }
}
await visit();
files.sort((a, b) => a.path.localeCompare(b.path));
if (!files.some(f => f.path === 'index.html') || !files.some(f => f.path === 'desktop/index.html')) throw new Error('Not an SDK site');
const allowed = Object.fromEntries(files.map(f => [f.path, 1]));
const router = `// Generated by docs-site/scripts/prepare-hosting.mjs. Source: ${revision}\nvar files = ${JSON.stringify(allowed)};\nfunction handler(event) {\n  var request = event.request;\n  var base = '/docs/sdk';\n  if (request.uri !== base && request.uri.indexOf(base + '/') !== 0) return request;\n  var path = request.uri.slice(base.length).replace(/^\\//, '');\n  if (!path || path.charAt(path.length - 1) === '/') path += 'index.html';\n  if (!files[path] && files[path + '/index.html']) path += '/index.html';\n  if (Object.prototype.hasOwnProperty.call(files, path)) {\n    request.uri = base + '/' + path;\n    return request;\n  }\n  return {statusCode: 404, statusDescription: 'Not Found', headers: {\n    'content-type': {value: 'text/html; charset=utf-8'},\n    'cache-control': {value: 'no-store'},\n    'x-robots-tag': {value: 'noindex, nofollow'}\n  }, body: '<!doctype html><html lang="en"><meta charset="utf-8"><meta name="robots" content="noindex"><title>Page not found</title><h1>Page not found</h1><p><a href="/docs/sdk/">OpenWorker SDK documentation</a></p></html>'};\n}\n`;
if (Buffer.byteLength(router) > 10000) throw new Error('CloudFront function exceeds 10KB; revise routing before deploying');
await writeFile(join(output, 'router.js'), router);
await writeFile(join(output, 'manifest.json'), JSON.stringify({revision, prefix: 'docs/sdk/', files}, null, 2) + '\n');
console.log(`Prepared ${files.length} files; router ${Buffer.byteLength(router)} bytes. No upload performed.`);