import { createServer, type Server } from 'node:http' import { readFileSync } from 'node:fs' import type { AddressInfo } from 'node:net' import path from 'node:path' async function closeServer(server: Server): Promise { await new Promise((resolve, reject) => server.close((error) => { if (error) { reject(error) return } resolve() }) ) } export async function startBrowserLinkServer(): Promise<{ sourceUrl: string imageSourceUrl: string close: () => Promise }> { const image = readFileSync( path.join(process.cwd(), 'resources', 'app-icons', 'orca-watercolor.png') ) const server = createServer((request, response) => { const origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}` const pathname = new URL(request.url ?? '/', origin).pathname if (pathname === '/image.png') { response.writeHead(200, { 'Content-Type': 'image/png' }) response.end(image) return } response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }) if (pathname === '/image-source') { response.end(`Image gallery

Image gallery

Click the image to open the PNG in a new tab.

Orca illustration `) return } if (pathname === '/destination') { response.end( `Linked destinationDestination Return` ) return } if (pathname === '/blank-destination') { response.end( 'Blank target destinationBlank target destination' ) return } if (pathname === '/frame-destination') { response.end( `Frame destinationFrame destination Return` ) return } if (pathname === '/frame-modifier-destination') { response.end( 'Frame modifier destinationFrame modifier destination' ) return } if (pathname === '/frame-middle-destination') { response.end( 'Frame middle destinationFrame middle destination' ) return } if (pathname === '/frame') { response.end( `${request.url?.includes('shift-middle') ? 'Frame shift middle destination' : ''}Open frame destinationOpen frame modifier destinationOpen frame middle destinationOpen foreground frame tab` ) return } if (pathname === '/modifier-destination') { response.end( 'Modifier destinationModifier destination' ) return } if (pathname === '/middle-destination') { response.end( 'Middle-click destinationMiddle-click destination' ) return } response.end(` ${request.url?.includes('shift-middle') ? 'Shift middle destination' : 'Source page'} Open destination Open blank target destination Open with modifier Open with middle click Open foreground tab Handle in page `) }) await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) const port = (server.address() as AddressInfo).port return { sourceUrl: `http://127.0.0.1:${port}/source`, imageSourceUrl: `http://127.0.0.1:${port}/image-source`, close: () => closeServer(server) } }