diagramming/mod.ts
2024-06-07 12:49:25 -05:00

179 lines
4.5 KiB
TypeScript
Executable file

#!/usr/bin/env -S deno run --allow-read --allow-write --allow-net --allow-env --ext=ts
import { Command } from 'https://deno.land/x/cliffy@v1.0.0-rc.4/command/mod.ts'
import { z } from 'https://deno.land/x/zod@v3.23.8/mod.ts'
const sockets: Set<WebSocket> = new Set([])
const Args = z.object({
input: z.string().default('./src'),
output: z.string().default('./build'),
open: z.boolean().default(false),
server: z.boolean().default(true),
host: z.string().default('localhost'),
port: z.number().default(8080),
})
type Args = z.infer<typeof Args>
const ClientEvent = z.discriminatedUnion('type', [
z.object({ type: z.literal('open'), connectionAttempt: z.number() }),
])
type ClientEvent = z.infer<typeof ClientEvent>
const command = new Command()
.name('diagrammer')
.description('A server to facilitate editing of Mermaid diagrams')
.version('v1.0.0')
.option(
'-i, --input <input_directory:path>',
'The directory containing .mmd files to compile.',
{
default: './src',
},
)
.option(
'-o, --output <output_directory:path>',
'The directory to put compiled .svg files into.',
{
default: './build',
},
)
.option('--open', 'Include this flag to open your browser automatically.', {
default: false,
})
.option(
'--no-server',
'Include this flag if you only want Mermaid compilation.',
)
.option('-H, --host <hostname>', 'The host name for the local server.', {
default: 'localhost',
})
.option('-p, --port <port:number>', 'The port number for the local server.', {
default: 8080,
})
async function openBrowser(args: Args): Promise<void> {
if (args.open) {
const url = `http://${args.host}:${args.port}`
console.log(`opening browser to ${url}`)
const process = new Deno.Command('xdg-open', {
args: [url],
}).spawn()
// const result = true
console.log(`opened browser to ${url}: ${await process.status}`)
}
}
async function runServer(args: Args): Promise<void> {
const opts = { hostname: args.host, port: args.port }
Deno.serve(opts, async (req: Request) => {
if (req.headers.get('upgrade') == 'websocket') {
return handleWebSocket(req)
}
const url = new URL(req.url)
if (url.pathname == '/client.js') {
return new Response(await Deno.readTextFile('./client.js'), {
headers: new Headers({ 'content-type': 'text/javascript' }),
})
} else if (url.pathname == '/') {
return new Response(html.index, {
headers: new Headers({ 'content-type': 'text/html' }),
})
}
return new Response(`Hello, ${url.pathname}!`)
})
return await new Promise((_resolve) => {
// a promise that never resolves
})
}
async function runMermaidFileWatcher(args: Args) {
console.log('Starting Mermaid file watcher...')
for await (
const { kind, paths } of Deno.watchFs(args.input, { recursive: true })
) {
console.log(
`Mermaid file watcher event: ${kind} ${paths.join(', ')}`,
)
for (const p of paths) {
console.log(p)
if (p.endsWith('.mmd') && (kind == 'create' || kind == 'modify')) {
console.log('omg a mermaid')
const contents = await Deno.readTextFile(p)
sockets.forEach((s) =>
s.send(JSON.stringify({ type: 'mermaid', contents }))
)
}
// TODO: handle removals?
}
}
}
function handleWebSocket(req: Request): Response {
const { socket, response } = Deno.upgradeWebSocket(req)
socket.addEventListener('open', (_ev) => {
console.log(`websocket open`)
socket.send('hi')
sockets.add(socket)
})
socket.addEventListener('message', (ev) => {
console.log(`websocket message: ${ev}`)
try {
if (ev.data) {
const data = JSON.parse(ev.data)
const clientEvent = ClientEvent.parse(data)
handleClientEvent(socket, clientEvent)
}
} catch (err) {
console.error(`invalid client message: ${err}`)
}
})
socket.addEventListener('close', (ev) => {
console.log(`websocket close: ${ev}`)
sockets.delete(socket)
})
return response
}
function handleClientEvent(socket: WebSocket, ce: ClientEvent) {
switch (ce.type) {
case 'open':
if (ce.connectionAttempt > 0) socket.send('reload')
break
}
}
const html = {
index: `
<!DOCTYPE html>
<h1>Hello, index!</h1>
<script src="./client.js"></script>
<script src="https://cdn.jsdelivr.net/npm/mermaid@10.9.1/dist/mermaid.min.js"></script>
`,
}
async function run(args: Args) {
// TODO: start mermaid file watcher
await Promise.all([
runMermaidFileWatcher(args),
runServer(args),
openBrowser(args),
])
}
command
.action(async (rawArgs) => {
const args = Args.parse(rawArgs)
console.log({ args })
await run(args)
})
.parse()