import * as ESBuild from 'https://deno.land/x/esbuild@v0.14.45/mod.js'; import * as MIME from "https://deno.land/std@0.180.0/media_types/mod.ts"; import { debounce } from "https://deno.land/std@0.151.0/async/debounce.ts"; const Transpiled = new Map(); /** * checks for (.tsx | .jsx | .ts | .js) extensions */ export const Transpileable =(inFilePath:string):boolean=> { let dotIndex = inFilePath.length-4; if(inFilePath[dotIndex] !== ".") { if(inFilePath[++dotIndex] !== ".") { return false; } } if(inFilePath[dotIndex+2] == "s") { const first = inFilePath[dotIndex+1]; return (first == "t" || first == "j"); } return false; }; export const Transpile =async(inCode:string, inKey:string):Promise=> { const transpile = await ESBuild.transform(inCode, { loader: "tsx", sourcemap: "inline", minify:true }); Transpiled.set(inKey, transpile.code); return transpile.code; }; type Transpiler = (inPath:string, inKey:string, inCheck?:boolean)=>Promise; export const TranspileFS:Transpiler =async(inPath, inKey, inCheck)=> { if(inCheck) { const cached = Transpiled.get(inKey); if(cached) { return cached; } } const body = await Deno.readTextFile(inPath); return Transpile(body, inKey); }; export const TranspileURL:Transpiler =async(inPath, inKey, inCheck)=> { if(inCheck) { const cached = Transpiled.get(inKey); if(cached) { return cached; } } const path = import.meta.resolve(`.${inPath}`); let body = await fetch(path); let text = await body.text(); return Transpile(text, inKey); }; type ImportMap = {imports?:Record, importMap?:string}; let ImportString = ``; let ImportObject:ImportMap = {}; try { const confDeno = await Deno.readTextFile(Deno.cwd()+"/deno.json"); const confDenoParsed:ImportMap = JSON.parse(confDeno); if(confDenoParsed.importMap) { try { const confImports = await Deno.readTextFile(confDenoParsed.importMap); try { ImportObject = JSON.parse(confImports); ImportString = confImports; } catch(e) { console.log(`"importMap" "${confDenoParsed.importMap}" contains invalid JSON`); } } catch(e) { console.log(`"importMap" "${confDenoParsed.importMap}" cannot be found`); } } else if(confDenoParsed.imports) { ImportObject = {imports:confDenoParsed.imports}; ImportString = JSON.stringify(ImportObject); } if(ImportObject.imports) { const importReact = ImportObject.imports?.["react"]; if(importReact) { ImportObject.imports["react-original"] = importReact; ImportObject.imports["react"] = "/hmr/react.tsx"; ImportString = JSON.stringify(ImportObject); } else { console.log(`"imports" configuration does not alias "react"`); } } else { console.log(`No "imports" found in configuration`); } } catch(e) { console.log(`deno.json not found`); } const Index = `
Loading
`; Deno.serve({ port: 3000 }, async(_req:Request) => { const url:URL = new URL(_req.url); const fsPath = Deno.cwd()+url.pathname; console.log(`Request for "${url.pathname}"...`); if(_req.headers.get("upgrade") == "websocket") { try { const { response, socket } = Deno.upgradeWebSocket(_req); socket.onopen = () => { Sockets.add(socket); console.log("Overwatch: Socket created"); }; socket.onclose = () => { Sockets.delete(socket); console.log("Overwatch: Socket deleted"); }; socket.onmessage = (e) => {}; socket.onerror = (e) => console.log("Overwatch: Socket errored:", e); return response; } catch(e) { // } } try { // serve index by default let type = `text/html`; let body:BodyInit = Index; const isLib = url.pathname.startsWith("/lib/") // serve .tsx .jsx .ts .js if(Transpileable(url.pathname)) { type = `application/javascript`; if(isLib) { body = await TranspileURL(url.pathname, url.pathname, true); } else if(!url.searchParams.get("reload")) { const path = `file://${Deno.cwd().replaceAll("\\", "/")+url.pathname}`; console.log(path); const imp = await import(path); const members = []; for( const key in imp ) { members.push(key); } body = `import * as Import from "${url.pathname}?reload=0"; ${ members.map(m=>`let proxy_${m} = Import.${m}; export { proxy_${m} as ${m} };`).join(" ") } const reloadHandler = (updatedModule)=> { ${ members.map(m=>`proxy_${m} = updatedModule.${m};`).join("\n") } }; window.HMR("${url.pathname}", reloadHandler);`; } else { body = await TranspileFS(fsPath, url.pathname, true); } } // serve static media else if( url.pathname.endsWith("/") === false) { type = MIME.typeByExtension(url.pathname.substring(url.pathname.lastIndexOf("."))) || "text/html"; if(isLib) { const _fetch = await fetch(import.meta.resolve(`.${url.pathname}`)); body = await _fetch.text(); } else { body = await Deno.readFile(fsPath); } } return new Response(body, {headers:{"content-type":type as string}}); } catch(error) { console.log(` ...404`); return new Response(error, {status:404}); } }); const Sockets:Set = new Set(); const SocketsBroadcast =(inData:string)=>{ for (const socket of Sockets){ socket.send(inData); } } const FilesChanged:Map = new Map(); const ProcessFiles =debounce(async()=> { console.log("Files changed...") for await (const [file, action] of FilesChanged) { const pathname = file.substring(Deno.cwd().length).replaceAll("\\", "/"); console.log(pathname, action); if(Transpileable(pathname)) { if(action !== "remove") { await TranspileFS(file, pathname, false); console.log(` ...cached "${pathname}"`); SocketsBroadcast(pathname); } } } FilesChanged.clear(); }, 1000); for await (const event of Deno.watchFs(Deno.cwd())) { event.paths.forEach( path => FilesChanged.set(path, event.kind) ); ProcessFiles(); }