Skip to content
โ† Public packages

@kentcdodds/closing-the-agentic-loop

Closing the Agentic Loop: Kent C. Dodds's talk and workshop deck. Default short talk; ?event=aie-2026 is the AIE hour cut with a Podium QR; ?format=full adds labs.

FollowForkOpen app

Files

build.mjs

152 lines ยท 8.7 KB ยท JavaScript
// Builds one fully self-contained Reveal.js page from src/deck.html + src/slides/*.html
// (file-name order) + data/*.json. Reveal.js and its notes plugin come from the pinned
// npm package (node_modules/reveal.js) and are inlined with the fonts, images, CSS and JS.
// Writes dist/index.html (the offline build) and app/assets.generated.ts (served by the app).
import { readdirSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'
import { join, extname } from 'node:path'
import QRCode from 'qrcode'

const root = new URL('..', import.meta.url).pathname
const src = join(root, 'src')
const types = { '.png': 'image/png', '.svg': 'image/svg+xml', '.woff2': 'font/woff2', '.ico': 'image/x-icon', '.webp': 'image/webp', '.jpg': 'image/jpeg' }
const esc = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
const code = (t) => esc(t).replace(/`([^`]+)`/g, '<code>$1</code>')

// c/<path> โ†’ data: URI, so the page never requests anything.
const dataUri = (rel) => {
	const file = join(src, 'c', rel)
	const type = types[extname(file)]
	if (!type) throw new Error(`No content type for ${rel}`)
	return `data:${type};base64,${readFileSync(file).toString('base64')}`
}

// Rewrites `@scope { a, b { ... } }` into rules prefixed with the slide's selector,
// so slide CSS stays isolated in browsers without @scope support.
function scopeCss(css, sel) {
	return css.replace(/@scope\s*\{([\s\S]*)\}\s*$/m, (_, body) =>
		body.replace(/([^{}]+)\{([^{}]*)\}/g, (_, selectors, decls) => {
			const out = selectors.split(',').map((s) => s.trim()).filter(Boolean).map((s) =>
				s.startsWith(':scope') ? sel + s.slice(6) : `${sel} ${s}`,
			)
			return `\n${out.join(', ')} {${decls}}`
		}),
	)
}

// House style for everything we write (slides, notes, data, docs): no em or en dashes, ASCII quotes only, and
// never the word "moat". Vendored code is not checked.
{
	const files = [
		...readdirSync(join(src, 'slides')).filter((f) => f.endsWith('.html')).map((f) => join(src, 'slides', f)),
		...readdirSync(join(root, 'data')).filter((f) => f.endsWith('.json')).map((f) => join(root, 'data', f)),
		...['README.md', 'AGENTS.md', 'LAB-GUIDE.md'].map((f) => join(root, f)),
	]
	const bad = []
	for (const file of files) {
		let text
		try { text = readFileSync(file, 'utf8') } catch { continue }
		text.split('\n').forEach((line, i) => {
			const m = line.match(/[\u2013\u2014\u2018\u2019\u201C\u201D]|\bmoats?\b/i)
			if (m) bad.push(`${file.slice(root.length)}:${i + 1}: ${JSON.stringify(m[0])}`)
		})
	}
	if (bad.length) throw new Error(`house style (no em/en dashes, ASCII quotes, no "moat"):\n${bad.join('\n')}`)
}

const rungs = JSON.parse(readFileSync(join(root, 'data/rungs.json'), 'utf8'))
const factory = JSON.parse(readFileSync(join(root, 'data/factory.json'), 'utf8'))
// Hour slide-set and event overrides, read by deck.js. Inlined as JSON, so nothing
// renders unless deck.js applies them. Each event with a podiumUrl gets a QR data URI
// generated here (no external QR service).
const hour = JSON.parse(readFileSync(join(root, 'data/hour.json'), 'utf8'))
const events = JSON.parse(readFileSync(join(root, 'data/events.json'), 'utf8')).events
for (const [slug, ev] of Object.entries(events)) {
	if (!ev.podiumUrl) throw new Error(`event ${slug}: missing podiumUrl`)
	if (!ev.title || !ev.format || !ev.displayUrl || !ev.pageTitle) throw new Error(`event ${slug}: missing title, format, displayUrl or pageTitle`)
	const svg = await QRCode.toString(ev.podiumUrl, {
		type: 'svg',
		errorCorrectionLevel: 'H',
		margin: 1,
		width: 256,
		color: { dark: '#111417', light: '#FFFFFF' },
	})
	ev.qrDataUri = `data:image/svg+xml;base64,${Buffer.from(svg).toString('base64')}`
}
const SCORES = ['done', 'partial', 'missing', 'unknown', 'n/a']
const all = rungs.groups.flatMap((g) => g.rungs)
for (const r of all) if (r.score !== null && !SCORES.includes(r.score)) throw new Error(`rung ${r.n}: bad score ${r.score}`)
const counts = SCORES.map((s) => [s, all.filter((r) => r.score === s).length])

// Ladder slide: rung names only, grouped by pillar. The "done when" wording and the
// scores go into the speaker notes ({{RUNGS_NOTES}}).
const group = (g) => `<div class="group${g.id === 'KI' ? ' ki' : ''}"><div class="gh">${esc(g.id)} ยท ${esc(g.label)}</div>${g.rungs
	.map((r) => `<div class="rung"><span class="n">${r.n}</span><span class="t">${esc(r.title)}</span></div>`)
	.join('')}</div>`
const byId = Object.fromEntries(rungs.groups.map((g) => [g.id, g]))
const rungsHtml = `<div class="cols">
	<div class="col">${group(byId.P1)}</div>
	<div class="col">${group(byId.P2)}${group(byId.P3)}</div>
	<div class="col">${group(byId.KI)}</div>
</div>`
const rungsNotes = `<p>Done when (autopilot skill ${esc(rungs.skillVersion)}):</p><ul>${all
	.map((r) => `<li>${r.n}. ${esc(r.title)}: ${code(r.doneWhen)}${rungs.showScores ? ` (mediarss: ${r.score === null ? 'not scored; the dry run predates this rung' : esc(r.score)})` : ''}</li>`)
	.join('')}</ul>`

// Factory slide: the numbers on screen, their GitHub queries in the speaker notes.
const factoryHtml = `<div class="stats">${factory.stats
	.map((s) => `<div class="stat"><div class="v">${esc(s.value)}</div><div class="l">${esc(s.label)}</div></div>`)
	.join('')}</div>`
const factoryNotes = `<p>Sources (${esc(factory.asOf)}), GitHub search:</p><ol>${factory.stats
	.map((s) => `<li>${esc(s.value)} ${esc(s.label)}: <code>${esc(s.query)}</code></li>`)
	.join('')}</ol>`

const slideFiles = readdirSync(join(src, 'slides')).filter((f) => f.endsWith('.html')).sort()
const labels = new Set()
const slidesHtml = slideFiles.map((f) => {
	let html = readFileSync(join(src, 'slides', f), 'utf8').trim()
	const label = html.match(/^<section id="([\w-]+)"/)?.[1]
	if (!label) throw new Error(`${f}: must start with <section id="...">`)
	if (labels.has(label)) throw new Error(`${f}: duplicate label ${label}`)
	labels.add(label)
	html = html.replace(/<style>([\s\S]*?)<\/style>/g, (_, css) => `<style>${scopeCss(css, `.reveal .slides section#${label}`)}</style>`)
	return html
		.replace('{{RUNGS}}', () => rungsHtml)
		.replace('{{RUNGS_NOTES}}', () => rungsNotes)
		.replace('{{FACTORY}}', () => factoryHtml)
		.replace('{{FACTORY_NOTES}}', () => factoryNotes)
}).join('\n')

// `vendor:<path>` reads from node_modules (pinned in package.json); other names from src/c/.
const readAsset = (f) => (f.startsWith('vendor:') ? readFileSync(join(root, 'node_modules', f.slice(7)), 'utf8') : readFileSync(join(src, 'c', f), 'utf8'))
// Inlined JS must not close the <script> element early (the notes plugin carries HTML).
const inlineJs = (t) => t.replace(/<\/script/gi, '<\\/script').replace(/^\/\/# sourceMappingURL=.*$/gm, '')
const inlineCss = (t) => t.replace(/^\/\*# sourceMappingURL=.*$/gm, '')
let page = readFileSync(join(src, 'deck.html'), 'utf8')
	.replace(/<link rel="stylesheet" href="([\w.:/-]+)">/g, (_, f) => `<style>\n${inlineCss(readAsset(f))}\n</style>`)
	.replace(/<script src="([\w.:/-]+)"><\/script>/g, (_, f) => `<script>\n${inlineJs(readAsset(f))}\n</script>`)
	.replace('<!-- slides -->', () => slidesHtml)
	.replace('<!-- hour -->', () => `<script type="application/json" id="hour-data">${JSON.stringify(hour).replace(/</g, '\\u003c')}</script>`)
	.replace('<!-- events -->', () => `<script type="application/json" id="events-data">${JSON.stringify(events).replace(/</g, '\\u003c')}</script>`)
page = page
	.replace(/url\('fonts\/([\w.-]+)'\)/g, (_, f) => `url('${dataUri('fonts/' + f)}')`)
	.replace(/(src|href)="c\/([\w./-]+)"/g, (_, attr, p) => `${attr}="${dataUri(p)}"`)
// Check the markup and CSS (inline scripts are vendored code; the verify step blocks network anyway).
// Plain https links on <a> are navigation the presenter clicks, not resources the page loads.
const markup = page.replace(/<script>[\s\S]*?<\/script>/g, '').replace(/<a ([^>]*?)href="https:\/\/[^"]+"/g, '<a $1')
const bad = markup.match(/(?:src|href)="(?!data:|#)[^"]*"|url\((?!['"]?data:)[^)]*\)/)
if (bad) throw new Error(`page still references an external or relative resource: ${bad[0].slice(0, 120)}`)

mkdirSync(join(root, 'dist'), { recursive: true })
writeFileSync(join(root, 'dist/index.html'), page)
const assets = {
	'index.html': { type: 'text/html; charset=utf-8', text: page },
	'favicon.ico': { type: 'image/x-icon', base64: readFileSync(join(src, 'c/icons/favicon.ico')).toString('base64') },
}
writeFileSync(join(root, 'app/assets.generated.ts'), `// Generated by scripts/build.mjs. Do not edit by hand.
export type Asset = { type: string; text?: string; base64?: string }

export const slideCount = ${slideFiles.length}

export const assets: Record<string, Asset> = ${JSON.stringify(assets, null, '\t')}
`)
console.log(`Composed ${slideFiles.length} slides (${[...labels].join(', ')}). dist/index.html is ${(page.length / 1024).toFixed(0)} KiB.`)