hmr #1

Merged
SethTrowbridge merged 9 commits from hmr into master 2023-04-01 11:13:22 -04:00
2 changed files with 84 additions and 40 deletions
Showing only changes of commit 9e2b7a5759 - Show all commits

View File

@ -2,8 +2,6 @@ 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 * 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"; import { debounce } from "https://deno.land/std@0.151.0/async/debounce.ts";
console.log(`Serving files from "${Deno.cwd()}"`);
const Transpiled = new Map(); const Transpiled = new Map();
/** /**
* checks for (.tsx | .jsx | .ts | .js) extensions * checks for (.tsx | .jsx | .ts | .js) extensions
@ -40,6 +38,7 @@ let ImportString = ``;
let ImportObject = {}; let ImportObject = {};
try try
{ {
const confDeno = await Deno.readTextFile(Deno.cwd()+"/deno.json"); const confDeno = await Deno.readTextFile(Deno.cwd()+"/deno.json");
const confDenoParsed:{importMap?:string, imports?:string} = JSON.parse(confDeno); const confDenoParsed:{importMap?:string, imports?:string} = JSON.parse(confDeno);
if(confDenoParsed.importMap) if(confDenoParsed.importMap)
@ -77,6 +76,35 @@ const Index = `
<html> <html>
<head> <head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
let reloads = 0;
const listeners = new Map();
const socket = new WebSocket("ws://"+document.location.host);
socket.addEventListener('message', (event) =>
{
let handlers = listeners.get(event.data)??[];
reloads++;
Promise.all(
handlers.map(handler=>
{
return import(event.data+"?reload="+reloads)
.then(updatedModule=>handler(updatedModule));
})
).then(()=>
{
handlers = listeners.get("reload-complete")??[];
handlers.forEach(handler=>handler());
});
});
window.HMR = (path, handler)=>
{
const members = listeners.get(path)??[];
members.push(handler);
listeners.set(path, members);
};
</script>
</head> </head>
<body> <body>
<div id="app">Loading</div> <div id="app">Loading</div>
@ -109,43 +137,6 @@ Deno.serve({ port: 3000 }, async(_req:Request) =>
console.log(`Request for "${url.pathname}"...`); console.log(`Request for "${url.pathname}"...`);
try
{
// serve index by default
let type = `text/html`;
let body:BodyInit = Index;
// serve .tsx .jsx .ts .js
if(Transpileable(url.pathname))
{
body = Transpiled.get(url.pathname);
type = `application/javascript`;
if(!body)
{
body = await Transpile(fsPath, url.pathname);
}
}
// serve static media
else if( url.pathname.endsWith("/") === false)
{
body = await Deno.readFile(fsPath);
type = MIME.typeByExtension(url.pathname.substring(url.pathname.lastIndexOf("."))) || "text/html";
}
return new Response(body, {headers:{"content-type":type as string}});
}
catch(error)
{
console.log(` ...404`);
return new Response(error, {status:404});
}
});
const Sockets:Set<WebSocket> = new Set();
const SocketsBroadcast =(inData:string)=>{ for (const socket of Sockets){ socket.send(inData); } }
Deno.serve({ port: 3001 }, (_req:Request) =>
{
if(_req.headers.get("upgrade") == "websocket") if(_req.headers.get("upgrade") == "websocket")
{ {
try try
@ -170,8 +161,60 @@ Deno.serve({ port: 3001 }, (_req:Request) =>
// //
} }
} }
return new Response("Overwatch: Not a websocket request.");
try
{
// serve index by default
let type = `text/html`;
let body:BodyInit = Index;
// serve .tsx .jsx .ts .js
if(Transpileable(url.pathname))
{
type = `application/javascript`;
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 = Transpiled.get(url.pathname) || await Transpile(fsPath, url.pathname);
}
}
// serve static media
else if( url.pathname.endsWith("/") === false)
{
body = await Deno.readFile(fsPath);
type = MIME.typeByExtension(url.pathname.substring(url.pathname.lastIndexOf("."))) || "text/html";
}
return new Response(body, {headers:{"content-type":type as string}});
}
catch(error)
{
console.log(` ...404`);
return new Response(error, {status:404});
}
}); });
const Sockets:Set<WebSocket> = new Set();
const SocketsBroadcast =(inData:string)=>{ for (const socket of Sockets){ socket.send(inData); } }
const FilesChanged:Map<string, string> = new Map(); const FilesChanged:Map<string, string> = new Map();
const ProcessFiles =debounce(async()=> const ProcessFiles =debounce(async()=>
{ {

1
test.tsx Normal file
View File

@ -0,0 +1 @@
export const test = "true";