boot-function #1

Merged
SethTrowbridge merged 25 commits from boot-function into master 2023-06-21 07:53:14 -04:00
4 changed files with 78 additions and 55 deletions
Showing only changes of commit 0aa0bb2955 - Show all commits

5
example/app.tsx Normal file
View File

@ -0,0 +1,5 @@
import React from "react";
export default ()=>
{
return <div><h1>hey!</h1></div>
}

View File

@ -1,6 +1,7 @@
{ {
"imports": "imports":
{ {
"react":"https://esm.sh/preact/compat" "react":"https://esm.sh/preact/compat",
"app": "./app.tsx"
} }
} }

View File

@ -1,10 +1,10 @@
import Setup, {Transpile, Extension} from "./serve.tsx"; import Configure, {Transpile, Extension} from "./serve.tsx";
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); } }
const Directory = `file://${Deno.cwd().replaceAll("\\", "/")}`; const Directory = `file://${Deno.cwd().replaceAll("\\", "/")}`;
Setup({ Configure({
Proxy:Directory, Proxy:Directory,
SWCOp: SWCOp:
{ {
@ -20,7 +20,7 @@ Setup({
} }
} }
}, },
async Serve(inReq, inURL, inExt) Serve(inReq, inURL, inExt, inMap)
{ {
if(inReq.headers.get("upgrade") == "websocket") if(inReq.headers.get("upgrade") == "websocket")
{ {
@ -41,26 +41,22 @@ Setup({
if(!inExt) if(!inExt)
{ {
await fetch(Directory+"/deno.json"); return new Response
(`<!doctype html>
return new Response(
`<!doctype html>
<html> <html>
<head> <head>
</head> </head>
<body> <body>
<div id="app"></div> <div id="app"></div>
<script type="importmap"> <script type="importmap">${JSON.stringify(inMap)}</script>
{ <script type="module">
"imports": import App from "app";
{ import React from "react";
"react":"https://esm.sh/preact/compat" React.render(React.createElement(App), document.querySelector("#app"))
}
}
</script> </script>
<script type="module"></script>
</body> </body>
</html>`, {headers:{"content-type":"text/html"}}); </html>
`, {status:200, headers:{"content-type":"text/html"}});
} }
return false; return false;
@ -84,7 +80,7 @@ for await (const event of Deno.watchFs(Deno.cwd()))
const key = path.substring(Deno.cwd().length).replaceAll("\\", "/"); const key = path.substring(Deno.cwd().length).replaceAll("\\", "/");
if(action != "remove") if(action != "remove")
{ {
const tsx = await Transpile.Fetch(Directory+key, key, true, true); const tsx = await Transpile.Fetch(Directory+key, key, true);
tsx && SocketsSend(key); tsx && SocketsSend(key);
} }
else else

View File

@ -2,15 +2,42 @@ 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";
type CustomHTTPHandler = (inReq:Request, inURL:URL, inExtension:string|false)=>false|Response|Promise<Response|false> const ImportMap = {imports:{}};
type Configuration = {Proxy:string, Allow:string, Reset:string, SWCOp:SWCW.Options, Serve:CustomHTTPHandler}; const ImportMapReload =async()=>
type ConfigurationArgs = {Proxy?:string, Allow?:string, Reset?:string, SWCOp?:SWCW.Options, Serve?:CustomHTTPHandler}; {
let confText;
try
{
confText = await Deno.readTextFile(Deno.cwd()+"\\deno.json");
}
catch(e)
{
console.log(`No "deno.json" file found at "${Deno.cwd()}"`);
}
confText && (ImportMap.imports = Configure.Remap(JSON.parse(confText)?.imports || {}));
};
type CustomHTTPHandler = (inReq:Request, inURL:URL, inExt:string|false, inMap:{imports:Record<string, string>})=>false|Response|Promise<Response|false>;
type CustomRemapper = (inImports:Record<string, string>)=>Record<string, string>;
type Configuration = {Proxy:string, Allow:string, Reset:string, SWCOp:SWCW.Options, Serve:CustomHTTPHandler, Remap:CustomRemapper};
type ConfigurationArgs = {Proxy?:string, Allow?:string, Reset?:string, SWCOp?:SWCW.Options, Serve?:CustomHTTPHandler, Remap?:CustomRemapper};
let Configure:Configuration = let Configure:Configuration =
{ {
Proxy: "", Proxy: "",
Allow: "*", Allow: "*",
Reset: "/clear-cache", Reset: "/clear-cache",
Serve: ()=>false, Serve: ()=>false,
Remap: (inImports)=>
{
Object.entries(inImports).forEach(([key, value])=>
{
if(value.startsWith("./"))
{
inImports[key] = value.substring(1);
}
});
return inImports;
},
SWCOp: SWCOp:
{ {
sourceMaps: false, sourceMaps: false,
@ -35,7 +62,6 @@ let Configure:Configuration =
} }
} }
}; };
export default (config:ConfigurationArgs)=> Configure = {...Configure, ...config};
export const Transpile = export const Transpile =
{ {
@ -49,6 +75,7 @@ export const Transpile =
{ {
const size = this.Cache.size; const size = this.Cache.size;
this.Cache.clear(); this.Cache.clear();
ImportMapReload();
return size; return size;
}, },
Fetch: async function(inPath:string, inKey:string, inCheckCache=true) Fetch: async function(inPath:string, inKey:string, inCheckCache=true)
@ -84,40 +111,29 @@ export const Extension =(inPath:string)=>
return posDot > posSlash ? inPath.substring(posDot+1).toLowerCase() : false; return posDot > posSlash ? inPath.substring(posDot+1).toLowerCase() : false;
}; };
SWCW.default(); export default (config:ConfigurationArgs)=> Configure = {...Configure, ...config};
await ImportMapReload();
await SWCW.default();
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 ext = Extension(url.pathname);
const headers = {"content-type":"application/json", "Access-Control-Allow-Origin": Configure.Allow, "charset":"UTF-8"}; const headers = {"content-type":"application/json", "Access-Control-Allow-Origin": Configure.Allow, "charset":"UTF-8"};
// 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 // cache-reset route
if(url.pathname === Configure.Reset) if(url.pathname === Configure.Reset)
{ {
return new Response(`{"cleared":${Transpile.Clear()}}`, {headers}); return new Response(`{"cleared":${Transpile.Clear()}}`, {headers});
} }
// allow for custom handler
const custom = await Configure.Serve(req, url, ext, ImportMap);
if(custom)
{
return custom;
}
// transpileable files // transpileable files
if(Transpile.Check(ext)) if(Transpile.Check(ext))
{ {
@ -126,6 +142,8 @@ HTTP.serve(async(req: Request)=>
} }
// all other static files // all other static files
if(ext)
{
try try
{ {
const type = MIME.typeByExtension(ext); const type = MIME.typeByExtension(ext);
@ -137,5 +155,8 @@ HTTP.serve(async(req: Request)=>
{ {
return new Response(`{"error":"${e}", "path":"${url.pathname}"}`, {status:404, headers}); return new Response(`{"error":"${e}", "path":"${url.pathname}"}`, {status:404, headers});
} }
}
return new Response(`{"error":"unmatched route", "path":"${url.pathname}"}`, {status:404, headers});
}); });