#!/usr/bin/env node // Builds the docs site: every page in docs/ becomes site/docs/.html in the // albedo.sh style, next to docs.css, docs-lake.js, openapi.yaml and the API reference. import { execFileSync } from 'node:child_process'; import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync, } from 'node:fs'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { Marked } from 'marked'; import * as pagefind from 'pagefind'; import { createCssVariablesTheme, createHighlighter } from 'shiki'; const site = dirname(fileURLToPath(import.meta.url)); const root = dirname(site); const source = join(root, 'docs'); const out = join(site, 'docs'); const repo = 'https://tangled.org/okami.mom/albedo/blob/main'; // Where the docs are served. The host answers /docs as well as /docs/, and a relative address // resolves differently under each, so every address the pages carry starts here. const base = '/docs/'; const address = (name) => (name === 'index.html' ? base : base + name); // The sidebar, in order. A page in docs/ missing here fails the build, so none is dropped silently. const pages = [ { file: 'readme.md', out: 'index.html', group: 'guide', label: 'overview' }, { file: 'install.md', group: 'guide', label: 'install' }, { file: 'web.md', group: 'guide', label: 'web client' }, { file: 'discord.md', group: 'guide', label: 'discord' }, { file: 'photon.md', group: 'guide', label: 'photon' }, { file: 'webhooks.md', group: 'guide', label: 'webhooks' }, { file: 'skills.md', group: 'guide', label: 'skills & instructions' }, { file: 'mcp.md', group: 'guide', label: 'mcp servers' }, { file: 'agents-and-worktrees.md', group: 'guide', label: 'agents & worktrees', }, { file: 'artifacts.md', group: 'guide', label: 'artifacts' }, { file: 'remote-kernels.md', group: 'guide', label: 'remote kernels' }, { file: 'tools-and-environments.md', group: 'guide', label: 'remote, colab & ui', }, { file: 'daemon-lifecycle.md', group: 'operate', label: 'daemon lifecycle' }, { file: 'home-manager.md', group: 'operate', label: 'home-manager' }, { file: 'extensions.md', group: 'contribute', label: 'write an extension' }, { file: 'extension-api.md', group: 'contribute', label: 'extension api' }, { file: 'client-api.md', group: 'api', label: 'client api' }, { file: 'http-api-workflows.md', group: 'api', label: 'http workflows' }, { file: 'http-api-design.md', group: 'api', label: 'http api design' }, { file: 'http-sessions.md', group: 'api', label: 'http sessions' }, { file: 'http-streams.md', group: 'api', label: 'http streams' }, { file: 'http-extensions.md', group: 'api', label: 'http extensions' }, { file: 'http-api-architecture.md', group: 'api', label: 'api architecture' }, { file: 'contributing-api.md', group: 'api', label: 'change the api' }, { file: 'api-client.gen.md', group: 'api', label: 'client reference' }, { file: 'api-extension.gen.md', group: 'api', label: 'extension reference', }, { file: 'api-internal-transfer.gen.md', group: 'api', label: 'transfer reference', }, ].map((page) => ({ ...page, out: page.out ?? page.file.replace(/\.md$/, '.html'), })); const reference = { label: 'api reference', out: 'api-reference.html' }; const escape = (text) => text.replace( /[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c], ); const slug = (text) => text .toLowerCase() .trim() .replace(/<[^>]+>/g, '') .replace(/[^\p{L}\p{N}\s_-]/gu, '') .replace(/\s/g, '-'); // Rewrites a link written for the repository into one that works on the site. function siteHref(href) { const [path, hash] = href.split('#'); if (/^[a-z]+:|^#/.test(href) || !path) return href; const page = pages.find((p) => p.file === path); if (page) return address(page.out) + (hash ? `#${hash}` : ''); if (path === 'api-reference.html' || path === 'openapi.yaml') return base + href; return `${repo}/${join('docs', path)}${hash ? `#${hash}` : ''}`; } const highlighter = await createHighlighter({ themes: [ createCssVariablesTheme({ name: 'madoromi', variablePrefix: '--shiki-' }), ], langs: [ 'gleam', 'python', 'json', 'go', 'sh', 'yaml', 'toml', 'nix', 'markdown', ], }); function render(markdown) { const headings = []; const images = []; const seen = new Map(); let title = ''; const marked = new Marked({ gfm: true, renderer: { heading({ tokens, depth, text }) { const html = this.parser.parseInline(tokens); if (depth === 1 && !title) { title = text; return `

${html}

\n`; } const level = Math.max(depth, 2); let id = slug(text); const count = seen.get(id) ?? 0; seen.set(id, count + 1); if (count) id += `-${count}`; if (level === 2) headings.push({ id, html }); return `${html}\n`; }, code({ text, lang }) { const language = highlighter.getLoadedLanguages().includes(lang) ? lang : 'text'; return ( highlighter.codeToHtml(text, { lang: language, theme: 'madoromi' }) + '\n' ); }, // A picture beside docs/.png called -light.png is shown on the light page. image({ href, text }) { const light = href.replace(/\.png$/, '-light.png'); const themed = light !== href && existsSync(join(source, light)); images.push(href, ...(themed ? [light] : [])); const png = readFileSync(join(source, href)); const size = `width="${png.readUInt32BE(16)}" height="${png.readUInt32BE(20)}"`; const lit = themed ? `` : ''; // The picture is a link to itself, so a wide screenshot can be read at full size. return `${lit}${escape(text)}`; }, link({ href, title: linkTitle, tokens }) { const target = siteHref(href); const external = /^https?:/.test(target) ? ' rel="noopener"' : ''; const titled = linkTitle ? ` title="${escape(linkTitle)}"` : ''; return `${this.parser.parseInline(tokens)}`; }, table({ header, rows }) { const labels = header.map((cell) => escape(cell.text)); const head = header .map((cell) => `${this.parser.parseInline(cell.tokens)}`) .join(''); // Long paths in a cell may wrap after a slash, never inside a word. const cell = (tokens) => this.parser .parseInline(tokens) .replace( /([^<]*)<\/code>/g, (_, text) => `${text.replaceAll('/', '/')}`, ); const body = rows .map( (row) => `${row.map((item, i) => `${cell(item.tokens)}`).join('')}`, ) .join('\n'); return `
${head}${body}
\n`; }, }, }); return { html: marked.parse(markdown), headings, title, images }; } function nav(current) { const groups = [...new Set(pages.map((page) => page.group))]; const link = (page) => `${page.label}`; const site = groups .map( (group) => `

${group}

\n` + pages .filter((page) => page.group === group) .map(link) .join(''), ) .join('\n'); return { site: `${site}${reference.label} ↗`, line: pages.map(link).join('') + `${reference.label}`, }; } function toc(headings) { if (headings.length < 2) return { aside: '', line: '' }; const links = headings.map( (h) => `${h.html.replace(/<\/?a[^>]*>/g, '')}`, ); const sentence = links.length === 2 ? links.join(' and ') : `${links.slice(0, -1).join(', ')}, and ${links.at(-1)}`; return { aside: ``, line: `

On this page: ${sentence}.

`, }; } function pager(index) { const [previous, next] = [pages[index - 1], pages[index + 1]]; if (!previous && !next) return ''; const part = (word, page) => page ? `${word} ${page.label} ` : ''; return `

${part('Previous', previous)}${part('Next', next)}

`; } // Search over the pagefind index, shown as text in place of the page while there is a query. const search = `(()=>{const field=document.querySelector('.search input'),article=document.querySelector('article'),found=document.querySelector('.results');let engine,shown='',timer; const words=(n,one,many)=>n+' '+(n===1?one:many); async function show(query){query=query.trim();if(query===shown)return;shown=query;history.replaceState(null,'',query?'?q='+encodeURIComponent(query):location.pathname); if(!query){article.classList.remove('searching');return} engine??=await import('${base}pagefind/pagefind.js');const result=await engine.debouncedSearch(query,{},120);if(!result||query!==shown)return; const pages=await Promise.all(result.results.slice(0,8).map((r)=>r.data())); found.innerHTML='

'+(pages.length?words(result.results.length,'page','pages')+' mention '+query.replace(/[&<>]/g,''):'Nothing mentions '+query.replace(/[&<>]/g,'')+'.')+'

'+pages.map((page)=>'
'+page.meta.title+''+(page.sub_results.length?page.sub_results.slice(0,3).map((s)=>''+(s.title===page.meta.title?'':''+s.title+'')+s.excerpt+'').join(''):'

'+page.excerpt+'

')+'
').join(''); article.classList.add('searching')} field.addEventListener('input',()=>show(field.value)); field.addEventListener('keydown',(e)=>{if(e.key==='Escape'){field.value='';show('');field.blur()}}); addEventListener('keydown',(e)=>{if(e.key==='/'&&document.activeElement!==field){e.preventDefault();field.focus()}}); const q=new URLSearchParams(location.search).get('q');if(q){field.value=q;show(q)}})()`; // Marks the section being read in the right-hand list; the page works the same without it. const spy = `const links=[...document.querySelectorAll('.toc a')];if(links.length){const mark=(id)=>links.forEach((a)=>a.classList.toggle('on',a.hash==='#'+id));mark(links[0].hash.slice(1));const watch=new IntersectionObserver((seen)=>seen.forEach((e)=>e.isIntersecting&&mark(e.target.id)),{rootMargin:'0px 0px -70% 0px'});document.querySelectorAll('h2[id]').forEach((h)=>watch.observe(h))}`; function page(entry, index) { const { html, headings, title, images } = render( readFileSync(join(source, entry.file), 'utf8'), ); for (const image of images) copyFileSync(join(source, image), join(out, image)); const links = nav(entry); const contents = toc(headings); const body = html.replace( /(<\/h1>\n(?:

[\s\S]*?<\/p>\n)?)/, `$1${contents.line}\n`, ); return ` ${escape(title)} · albedo docs

albedo docs

${body}${pager(index)}
${contents.aside}
`; } /** Writes every page, the search index, docs.css, docs-lake.js, openapi.yaml and the API reference into site/docs. */ export async function build() { const unlisted = readdirSync(source).filter( (name) => name.endsWith('.md') && !pages.some((page) => page.file === name), ); if (unlisted.length) throw new Error( `docs/ pages missing from the sidebar in build-docs.mjs: ${unlisted.join(', ')}`, ); rmSync(out, { recursive: true, force: true }); mkdirSync(out, { recursive: true }); const { index, errors } = await pagefind.createIndex({ forceLanguage: 'en', includeCharacters: '_', }); if (!index) throw new Error(`pagefind: ${errors.join('; ')}`); for (const [position, entry] of pages.entries()) { const html = page(entry, position); writeFileSync(join(out, entry.out), html); await index.addHTMLFile({ url: `/${entry.out}`, content: html }); } await index.writeFiles({ outputPath: join(out, 'pagefind') }); await pagefind.close(); copyFileSync(join(site, 'docs.css'), join(out, 'docs.css')); copyFileSync(join(site, 'docs-lake.js'), join(out, 'docs-lake.js')); copyFileSync(join(source, 'openapi.yaml'), join(out, 'openapi.yaml')); execFileSync( 'python3', [ join(root, 'scripts', 'api-reference.py'), '--output', join(out, reference.out), ], { stdio: 'inherit' }, ); console.log( `built ${pages.length} pages, their search index and the API reference into ${out}`, ); } if (process.argv[1] === fileURLToPath(import.meta.url)) await build();