// Dev server: builds, serves dist/index.html at the Kody mount, rebuilds on changes
// to src/ and data/, and live-reloads open tabs (Reveal keeps your slide via the URL hash).
import { createServer } from 'node:http'
import { watch, readFileSync } from 'node:fs'
import { spawn } from 'node:child_process'
import { join } from 'node:path'
const root = new URL('..', import.meta.url).pathname
const port = Number(process.env.PORT ?? 4320)
const mount = '/packages/closing-the-agentic-loop'
const clients = new Set()
let building = false
let queued = false
function build() {
if (building) return void (queued = true)
building = true
const started = Date.now()
const child = spawn(process.execPath, [join(root, 'scripts/build.mjs')], { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] })
let out = ''
child.stdout.on('data', (d) => (out += d))
child.stderr.on('data', (d) => (out += d))
child.on('exit', (code) => {
building = false
const time = new Date().toLocaleTimeString()
if (code === 0) {
console.log(`[${time}] built in ${Date.now() - started}ms, reloading ${clients.size} tab(s)`)
for (const res of clients) res.write('data: reload\n\n')
} else {
console.error(`[${time}] build failed:\n${out}`)
}
if (queued) {
queued = false
build()
}
})
}
let timer
for (const dir of ['src', 'data']) {
watch(join(root, dir), { recursive: true }, (_event, file) => {
if (file && /(^|\/)\.|~$/.test(file)) return
clearTimeout(timer)
timer = setTimeout(build, 100)
})
}
const reloadScript = ``
createServer((req, res) => {
const { pathname } = new URL(req.url, `http://localhost:${port}`)
if (pathname === '/' || pathname === mount) {
res.writeHead(302, { location: mount + '/' })
return res.end()
}
if (pathname === `${mount}/__dev/events`) {
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' })
res.write(': connected\n\n')
clients.add(res)
return req.on('close', () => clients.delete(res))
}
if (pathname === `${mount}/favicon.ico`) {
res.writeHead(200, { 'content-type': 'image/x-icon' })
return res.end(readFileSync(join(root, 'src/c/icons/favicon.ico')))
}
if (pathname === `${mount}/` || pathname === `${mount}/index.html`) {
try {
const raw = readFileSync(join(root, 'dist/index.html'), 'utf8')
const at = raw.lastIndexOf('