more configuration

This commit is contained in:
Seth Trowbridge 2023-06-07 11:22:49 -04:00
parent 083e37a173
commit c758f66b27
2 changed files with 148 additions and 86 deletions

View File

@ -1,32 +1,71 @@
import * as HTTP from "https://deno.land/std@0.177.0/http/server.ts"; import Setup, {Transpile, Extension} from "./serve.tsx";
import Setup, {Transpile} from "./serve.tsx";
const Directory = `file://${Deno.cwd().replaceAll("\\", "/")}`;
Transpile.Config.sourceMaps = "inline";
Setup({Proxy:Directory});
const SocketsLive:Set<WebSocket> = new Set(); const SocketsLive:Set<WebSocket> = new Set();
const SocketsSend =(inData:string)=>{ console.log(inData); for (const socket of SocketsLive){ socket.send(inData); } } const SocketsSend =(inData:string)=>{ console.log(inData); for (const socket of SocketsLive){ socket.send(inData); } }
HTTP.serve((_req:Request)=> const Directory = `file://${Deno.cwd().replaceAll("\\", "/")}`;
{
if(_req.headers.get("upgrade") == "websocket") Setup({
Proxy:Directory,
SWCOp:
{ {
try sourceMaps: "inline",
minify: false,
jsc:
{ {
const { response, socket } = Deno.upgradeWebSocket(_req); target:"es2022",
socket.onopen = () => SocketsLive.add(socket); parser:
socket.onclose = () => SocketsLive.delete(socket); {
socket.onmessage = (e) => {}; syntax: "typescript",
socket.onerror = (e) => console.log("Socket errored:", e); tsx: true,
return response; }
} }
catch(e) },
async Serve(inReq, inURL, inExt)
{
if(inReq.headers.get("upgrade") == "websocket")
{ {
return new Response(e); try
{
const { response, socket } = Deno.upgradeWebSocket(inReq);
socket.onopen = () => SocketsLive.add(socket);
socket.onclose = () => SocketsLive.delete(socket);
socket.onmessage = (e) => {};
socket.onerror = (e) => console.log("Socket errored:", e);
return response;
}
catch(e)
{
return new Response(e);
}
} }
if(!inExt)
{
await fetch(Directory+"/deno.json");
return new Response(
`<!doctype html>
<html>
<head>
</head>
<body>
<div id="app"></div>
<script type="importmap">
{
"imports":
{
"react":"https://esm.sh/preact/compat"
}
}
</script>
<script type="module"></script>
</body>
</html>`, {headers:{"content-type":"text/html"}});
}
return false;
} }
return new Response(`websockets only`); });
}, { port: 4444 });
let blocking = false; let blocking = false;
const filesChanged:Map<string, string> = new Map(); const filesChanged:Map<string, string> = new Map();
@ -40,15 +79,18 @@ for await (const event of Deno.watchFs(Deno.cwd()))
{ {
for await (const [path, action] of filesChanged) for await (const [path, action] of filesChanged)
{ {
const key = path.substring(Deno.cwd().length).replaceAll("\\", "/"); if(Transpile.Check(Extension(path)))
if(action != "remove")
{ {
const tsx = await Transpile.Fetch(Directory+key, key, true); const key = path.substring(Deno.cwd().length).replaceAll("\\", "/");
tsx && SocketsSend(key); if(action != "remove")
} {
else const tsx = await Transpile.Fetch(Directory+key, key, true, true);
{ tsx && SocketsSend(key);
Transpile.Cache.delete(key); }
else
{
Transpile.Cache.delete(key);
}
} }
} }
filesChanged.clear(); filesChanged.clear();

136
serve.tsx
View File

@ -2,19 +2,16 @@ import * as MIME from "https://deno.land/std@0.180.0/media_types/mod.ts";
import * as HTTP from "https://deno.land/std@0.177.0/http/server.ts"; import * as HTTP from "https://deno.land/std@0.177.0/http/server.ts";
import * as SWCW from "https://esm.sh/@swc/wasm-web@1.3.62"; import * as SWCW from "https://esm.sh/@swc/wasm-web@1.3.62";
export type Configuration = {Proxy:string, Allow:string, Reset:string, Local:boolean}; type CustomHTTPHandler = (inReq:Request, inURL:URL, inExtension:string|false)=>false|Response|Promise<Response|false>
export type ConfigurationArgs = {Proxy?:string, Allow?:string, Reset?:string, Local?:boolean}; type Configuration = {Proxy:string, Allow:string, Reset:string, SWCOp:SWCW.Options, Serve:CustomHTTPHandler};
export let Configure:Configuration = type ConfigurationArgs = {Proxy?:string, Allow?:string, Reset?:string, SWCOp?:SWCW.Options, Serve?:CustomHTTPHandler};
let Configure:Configuration =
{ {
Proxy: "", Proxy: "",
Allow: "*", Allow: "*",
Reset: "/clear-cache", Reset: "/clear-cache",
Local: false Serve: ()=>false,
}; SWCOp:
export default (config:ConfigurationArgs)=> Configure = {...Configure, ...config};
export const Transpile = {
Config:
{ {
sourceMaps: false, sourceMaps: false,
minify: true, minify: true,
@ -35,9 +32,19 @@ export const Transpile = {
{ {
react: { runtime: "automatic" } react: { runtime: "automatic" }
} }
}, }
} as SWCW.Options, }
};
export default (config:ConfigurationArgs)=> Configure = {...Configure, ...config};
export const Transpile =
{
Cache: new Map() as Map<string, string>, Cache: new Map() as Map<string, string>,
Files: ["tsx", "jsx", "ts", "js", "mjs"],
Check(inExtension:string|false)
{
return inExtension ? this.Files.includes(inExtension) : false;
},
Clear() Clear()
{ {
const size = this.Cache.size; const size = this.Cache.size;
@ -46,76 +53,89 @@ export const Transpile = {
}, },
Fetch: async function(inPath:string, inKey:string, inCheckCache=true) Fetch: async function(inPath:string, inKey:string, inCheckCache=true)
{ {
console.log("transpile", inPath) const check = this.Cache.get(inPath);
if(inPath.endsWith(".tsx") || inPath.endsWith(".jsx") || inPath.endsWith(".js") || inPath.endsWith(".mjs")) if(check && inCheckCache)
{ {
const check = this.Cache.get(inPath); return check;
if(check && inCheckCache)
{
return check;
}
else
{
try
{
const resp = await fetch(inPath);
const text = await resp.text();
const {code} = await SWCW.transform(text, {...this.Config, filename:inKey});
this.Cache.set(inKey, code);
return code;
}
catch(e)
{
console.log(`xpile.tsx error. Key:${inKey} Path:${inPath} Error:"${e}"`);
return null;
}
}
} }
else else
{ {
return false; try
{
const resp = await fetch(inPath);
const text = await resp.text();
const {code} = await SWCW.transform(text, { ...Configure.SWCOp, filename:inKey});
this.Cache.set(inKey, code);
return code;
}
catch(e)
{
//console.log(`Transpile.Fetch error. Key:"${inKey}" Path:"${inPath}" Error:"${e}"`);
return null;
}
} }
} }
}; };
export const Extension =(inPath:string)=>
{
const posSlash = inPath.lastIndexOf("/");
const posDot = inPath.lastIndexOf(".");
return posDot > posSlash ? inPath.substring(posDot+1).toLowerCase() : false;
};
SWCW.default(); SWCW.default();
console.log("starting server");
HTTP.serve(async(req: Request)=> HTTP.serve(async(req: Request)=>
{ {
const url:URL = new URL(req.url); const url:URL = new URL(req.url);
const ext = Extension(url.pathname);
const headers = {"content-type":"application/json", "Access-Control-Allow-Origin": Configure.Allow, "charset":"UTF-8"};
if(url.pathname.endsWith("/")) // allow for custom handler
const custom = await Configure.Serve(req, url, ext);
if(custom)
{ {
return custom;
} }
// implied index.html files
if(!ext)
{
return new Response(`<!doctype html>
<html>
<head>
</head>
<body>
<script type="importmap"></script>
<script type="module"></script>
</body>
</html>`, {headers:{...headers, "content-type":"text/html"}});
}
// cache-reset route
if(url.pathname === Configure.Reset) if(url.pathname === Configure.Reset)
{ {
return new Response(`cache cleared (${Transpile.Clear()} items)`); return new Response(`{"cleared":${Transpile.Clear()}}`, {headers});
} }
const lookup = await Transpile.Fetch(Configure.Proxy + url.pathname, url.pathname); // transpileable files
if(lookup === null) if(Transpile.Check(ext))
{ {
// error const lookup = await Transpile.Fetch(Configure.Proxy + url.pathname, url.pathname);
return new Response(`transpile error (see console)`, {status:404, headers:{"content-type":"application/javascript", "Access-Control-Allow-Origin": Configure.Allow, charset:"utf-8"}}); return new Response(lookup, {status:lookup?200:404, headers:{...headers, "content-type":"application/javascript"}} );
} }
else if(lookup === false)
// all other static files
try
{ {
// not a javascript file const type = MIME.typeByExtension(ext);
try const file = await fetch(Configure.Proxy + url.pathname);
{ const text = await file.text();
const type = MIME.typeByExtension(url.pathname.substring(url.pathname.lastIndexOf("."))) || "text/html"; return new Response(text, {headers:{...headers, "content-type":type||""}});
const file = await fetch(Configure.Proxy + url.pathname);
const text = await file.text();
return new Response(text, {headers:{"content-type":type, "Access-Control-Allow-Origin":Configure.Allow, charset:"utf-8"}});
}
catch(e)
{
return new Response(`404 ${Configure.Proxy + url.pathname}`, {status:404});
}
} }
else catch(e)
{ {
return new Response(lookup, {headers:{"content-type":"application/javascript", "Access-Control-Allow-Origin": Configure.Allow, charset:"utf-8"}}); return new Response(`{"error":"${e}", "path":"${url.pathname}"}`, {status:404, headers});
} }
}); });