eno/server.tsx

307 lines
8.7 KiB
TypeScript
Raw Normal View History

2023-03-16 08:25:44 -04:00
import * as ESBuild from 'https://deno.land/x/esbuild@v0.14.45/mod.js';
2023-03-17 11:54:36 -04:00
import * as MIME from "https://deno.land/std@0.180.0/media_types/mod.ts";
2022-12-01 17:10:59 -05:00
import { debounce } from "https://deno.land/std@0.151.0/async/debounce.ts";
2023-03-17 11:54:36 -04:00
const Transpiled = new Map();
/**
* checks for (.tsx | .jsx | .ts | .js) extensions
*/
export const Transpileable =(inFilePath:string):boolean=>
2022-12-01 17:10:59 -05:00
{
2023-03-17 11:54:36 -04:00
let dotIndex = inFilePath.length-4;
if(inFilePath[dotIndex] !== ".")
{
if(inFilePath[++dotIndex] !== ".")
{
return false;
}
}
2022-12-01 17:10:59 -05:00
2023-03-17 11:54:36 -04:00
if(inFilePath[dotIndex+2] == "s")
{
const first = inFilePath[dotIndex+1];
return (first == "t" || first == "j");
}
return false;
};
2023-03-27 23:05:20 -04:00
export const Transpile =async(inCode:string, inKey:string):Promise<string>=>
2022-12-01 17:10:59 -05:00
{
2023-03-27 23:05:20 -04:00
const transpile = await ESBuild.transform(inCode, { loader: "tsx", sourcemap: "inline", minify:true });
2022-12-01 17:10:59 -05:00
Transpiled.set(inKey, transpile.code);
return transpile.code;
};
2023-03-27 23:05:20 -04:00
type Transpiler = (inPath:string, inKey:string, inCheck?:boolean)=>Promise<string>;
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);
};
2022-12-01 17:10:59 -05:00
2023-03-22 17:45:25 -04:00
type ImportMap = {imports?:Record<string, string>, importMap?:string};
2023-03-17 11:54:36 -04:00
let ImportString = ``;
2023-03-22 17:45:25 -04:00
let ImportObject:ImportMap = {};
2023-03-17 11:54:36 -04:00
try
{
const confDeno = await Deno.readTextFile(Deno.cwd()+"/deno.json");
2023-03-22 17:45:25 -04:00
const confDenoParsed:ImportMap = JSON.parse(confDeno);
2023-03-17 11:54:36 -04:00
if(confDenoParsed.importMap)
{
try
{
const confImports = await Deno.readTextFile(confDenoParsed.importMap);
try
{
ImportObject = JSON.parse(confImports);
ImportString = confImports;
}
catch(e)
{
2023-03-22 17:45:25 -04:00
console.log(`"importMap" "${confDenoParsed.importMap}" contains invalid JSON`);
2023-03-17 11:54:36 -04:00
}
}
catch(e)
{
2023-03-22 17:45:25 -04:00
console.log(`"importMap" "${confDenoParsed.importMap}" cannot be found`);
2023-03-17 11:54:36 -04:00
}
}
else if(confDenoParsed.imports)
{
ImportObject = {imports:confDenoParsed.imports};
ImportString = JSON.stringify(ImportObject);
}
2023-03-22 17:45:25 -04:00
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`);
}
2023-03-17 11:54:36 -04:00
}
catch(e)
{
console.log(`deno.json not found`);
}
2023-03-22 17:45:25 -04:00
2022-12-01 17:10:59 -05:00
const Index = `
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
2023-03-20 17:41:57 -04:00
<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>
2022-12-01 17:10:59 -05:00
</head>
<body>
<div id="app">Loading</div>
2023-03-17 11:54:36 -04:00
<script type="importmap">${ImportString}</script>
2022-12-01 17:10:59 -05:00
<script async src="https://ga.jspm.io/npm:es-module-shims@1.5.1/dist/es-module-shims.js" crossorigin="anonymous"></script>
<script type="module">
import * as TW from "https://esm.sh/@twind/core@1.0.1";
import TWPreTail from "https://esm.sh/@twind/preset-tailwind@1.0.1";
import TWPreAuto from "https://esm.sh/@twind/preset-autoprefix@1.0.1";
const Configure = {presets: [TWPreTail(), TWPreAuto()]};
const ShadowDOM = document.querySelector("#app").attachShadow({mode: "open"});
const ShadowDiv = document.createElement("div");
const ShadowCSS = document.createElement("style");
ShadowDOM.append(ShadowCSS);
ShadowDOM.append(ShadowDiv);
import App from "./app.tsx";
App(ShadowDiv, Configure);
TW.observe(TW.twind(Configure, TW.cssom(ShadowCSS)), ShadowDiv);
</script>
</body>
</html>
`;
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}"...`);
2023-03-20 17:41:57 -04:00
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)
{
//
}
}
2022-12-01 17:10:59 -05:00
try
{
2023-03-17 11:54:36 -04:00
// serve index by default
let type = `text/html`;
let body:BodyInit = Index;
2023-03-27 23:05:20 -04:00
const isLib = url.pathname.startsWith("/lib/")
// serve .tsx .jsx .ts .js
if(Transpileable(url.pathname))
2022-12-01 17:10:59 -05:00
{
2023-03-27 23:05:20 -04:00
type = `application/javascript`;
if(isLib)
2022-12-01 17:10:59 -05:00
{
2023-03-27 23:05:20 -04:00
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);
2023-03-22 17:45:25 -04:00
2023-03-27 23:05:20 -04:00
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);`;
2023-03-22 17:45:25 -04:00
2023-03-20 17:41:57 -04:00
}
2023-03-27 23:05:20 -04:00
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
2023-03-20 17:41:57 -04:00
{
2023-03-22 17:45:25 -04:00
body = await Deno.readFile(fsPath);
2022-12-01 17:10:59 -05:00
}
}
return new Response(body, {headers:{"content-type":type as string}});
}
catch(error)
{
console.log(` ...404`);
return new Response(error, {status:404});
}
});
2023-03-17 11:54:36 -04:00
const Sockets:Set<WebSocket> = new Set();
const SocketsBroadcast =(inData:string)=>{ for (const socket of Sockets){ socket.send(inData); } }
2023-03-20 17:41:57 -04:00
2023-03-17 11:54:36 -04:00
const FilesChanged:Map<string, string> = new Map();
2022-12-01 17:10:59 -05:00
const ProcessFiles =debounce(async()=>
{
console.log("Files changed...")
2023-03-17 11:54:36 -04:00
for await (const [file, action] of FilesChanged)
2022-12-01 17:10:59 -05:00
{
const pathname = file.substring(Deno.cwd().length).replaceAll("\\", "/");
2023-03-17 11:54:36 -04:00
console.log(pathname, action);
if(Transpileable(pathname))
2022-12-01 17:10:59 -05:00
{
if(action !== "remove")
{
2023-03-27 23:05:20 -04:00
await TranspileFS(file, pathname, false);
2022-12-01 17:10:59 -05:00
console.log(` ...cached "${pathname}"`);
2023-03-17 11:54:36 -04:00
SocketsBroadcast(pathname);
2022-12-01 17:10:59 -05:00
}
}
}
2023-03-17 11:54:36 -04:00
FilesChanged.clear();
2022-12-01 17:10:59 -05:00
}, 1000);
2023-03-17 11:54:36 -04:00
for await (const event of Deno.watchFs(Deno.cwd()))
2022-12-01 17:10:59 -05:00
{
2023-03-17 11:54:36 -04:00
event.paths.forEach( path => FilesChanged.set(path, event.kind) );
2022-12-01 17:10:59 -05:00
ProcessFiles();
}