able-baker/serve.tsx

194 lines
5.8 KiB
TypeScript
Raw Normal View History

2023-06-06 12:50:50 -04:00
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";
2023-06-06 22:24:43 -04:00
import * as SWCW from "https://esm.sh/@swc/wasm-web@1.3.62";
2023-06-06 12:50:50 -04:00
2023-06-07 14:15:57 -04:00
const ImportMap = {imports:{}};
const ImportMapReload =async()=>
{
let confText;
try
{
confText = await Deno.readTextFile(Deno.cwd()+"\\deno.json");
}
catch(e)
{
console.log(`No "deno.json" file found at "${Deno.cwd()}"`);
}
2023-06-07 17:09:40 -04:00
confText && (ImportMap.imports = Configuration.Remap(JSON.parse(confText)?.imports || {}));
2023-06-07 14:15:57 -04:00
};
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>;
2023-06-07 17:09:40 -04:00
type Configuration = {Proxy:string, Allow:string, Reset:string, SWCOp:SWCW.Options, Serve:CustomHTTPHandler, Shell:CustomHTTPHandler, Remap:CustomRemapper};
type ConfigurationArgs = {Proxy?:string, Allow?:string, Reset?:string, SWCOp?:SWCW.Options, Serve?:CustomHTTPHandler, Shell?:CustomHTTPHandler, Remap?:CustomRemapper};
let Configuration:Configuration =
2023-06-06 12:50:50 -04:00
{
2023-06-07 17:09:40 -04:00
Proxy: `file://${Deno.cwd().replaceAll("\\", "/")}`,
2023-06-06 12:50:50 -04:00
Allow: "*",
2023-06-06 17:22:14 -04:00
Reset: "/clear-cache",
2023-06-07 17:09:40 -04:00
Serve(inReq, inURL, inExt, inMap)
{
return false;
},
2023-06-07 14:15:57 -04:00
Remap: (inImports)=>
{
Object.entries(inImports).forEach(([key, value])=>
{
if(value.startsWith("./"))
{
inImports[key] = value.substring(1);
}
});
2023-06-07 17:09:40 -04:00
Configuration.SWCOp.jsc.transform.react.importSource = inImports["react"];
2023-06-07 14:15:57 -04:00
return inImports;
},
2023-06-07 17:09:40 -04:00
Shell(inReq, inURL, inExt, inMap)
{
return new Response(
`<!doctype html>
<html>
<head>
</head>
<body>
<div id="app"></div>
<script type="importmap">${JSON.stringify(inMap)}</script>
<script type="module">
import App from "app";
import React from "react";
React.render(React.createElement(App), document.querySelector("#app"))
</script>
</body>
</html>`, {status:200, headers:{"content-type":"text/html"}});
},
2023-06-07 11:22:49 -04:00
SWCOp:
2023-06-06 22:24:43 -04:00
{
sourceMaps: false,
minify: true,
jsc:
{
target:"es2017",
minify:
{
compress: { unused: true },
mangle: true
},
parser:
{
syntax: "typescript",
tsx: true,
},
transform:
{
react: { runtime: "automatic" }
}
2023-06-07 11:22:49 -04:00
}
}
};
export const Transpile =
{
2023-06-06 22:24:43 -04:00
Cache: new Map() as Map<string, string>,
2023-06-07 11:22:49 -04:00
Files: ["tsx", "jsx", "ts", "js", "mjs"],
Check(inExtension:string|false)
{
return inExtension ? this.Files.includes(inExtension) : false;
},
2023-06-06 22:24:43 -04:00
Clear()
{
const size = this.Cache.size;
this.Cache.clear();
2023-06-07 14:15:57 -04:00
ImportMapReload();
2023-06-06 22:24:43 -04:00
return size;
},
Fetch: async function(inPath:string, inKey:string, inCheckCache=true)
{
2023-06-07 11:22:49 -04:00
const check = this.Cache.get(inPath);
if(check && inCheckCache)
2023-06-06 22:24:43 -04:00
{
2023-06-07 11:22:49 -04:00
return check;
}
else
{
try
2023-06-06 22:24:43 -04:00
{
2023-06-07 11:22:49 -04:00
const resp = await fetch(inPath);
const text = await resp.text();
2023-06-07 17:09:40 -04:00
const {code} = await SWCW.transform(text, { ...Configuration.SWCOp, filename:inKey});
2023-06-07 11:22:49 -04:00
this.Cache.set(inKey, code);
return code;
2023-06-06 22:24:43 -04:00
}
2023-06-07 11:22:49 -04:00
catch(e)
2023-06-06 22:24:43 -04:00
{
2023-06-07 11:22:49 -04:00
//console.log(`Transpile.Fetch error. Key:"${inKey}" Path:"${inPath}" Error:"${e}"`);
return null;
2023-06-06 22:24:43 -04:00
}
}
}
};
2023-06-06 12:50:50 -04:00
2023-06-07 11:22:49 -04:00
export const Extension =(inPath:string)=>
{
const posSlash = inPath.lastIndexOf("/");
const posDot = inPath.lastIndexOf(".");
return posDot > posSlash ? inPath.substring(posDot+1).toLowerCase() : false;
};
2023-06-07 17:09:40 -04:00
export const Configure =(config:ConfigurationArgs)=> Configuration = {...Configuration, ...config};
2023-06-07 14:15:57 -04:00
await ImportMapReload();
await SWCW.default();
2023-06-06 12:50:50 -04:00
HTTP.serve(async(req: Request)=>
{
const url:URL = new URL(req.url);
2023-06-07 11:22:49 -04:00
const ext = Extension(url.pathname);
2023-06-07 17:09:40 -04:00
const headers = {"content-type":"application/json", "Access-Control-Allow-Origin": Configuration.Allow, "charset":"UTF-8"};
2023-06-07 11:22:49 -04:00
// cache-reset route
2023-06-07 17:09:40 -04:00
if(url.pathname === Configuration.Reset)
2023-06-06 12:50:50 -04:00
{
2023-06-07 11:22:49 -04:00
return new Response(`{"cleared":${Transpile.Clear()}}`, {headers});
2023-06-06 12:50:50 -04:00
}
2023-06-07 14:15:57 -04:00
// allow for custom handler
2023-06-07 17:09:40 -04:00
const custom = await Configuration.Serve(req, url, ext, ImportMap);
2023-06-07 14:15:57 -04:00
if(custom)
{
return custom;
}
2023-06-07 17:09:40 -04:00
// custom page html
if(!ext)
{
const shell = await Configuration.Shell(req, url, ext, ImportMap);
if(shell)
{
return shell;
}
}
2023-06-07 11:22:49 -04:00
// transpileable files
if(Transpile.Check(ext))
2023-06-06 12:50:50 -04:00
{
2023-06-07 17:09:40 -04:00
const lookup = await Transpile.Fetch(Configuration.Proxy + url.pathname, url.pathname);
2023-06-07 11:22:49 -04:00
return new Response(lookup, {status:lookup?200:404, headers:{...headers, "content-type":"application/javascript"}} );
2023-06-06 12:50:50 -04:00
}
2023-06-07 11:22:49 -04:00
// all other static files
2023-06-07 14:15:57 -04:00
if(ext)
2023-06-06 12:50:50 -04:00
{
2023-06-07 14:15:57 -04:00
try
{
const type = MIME.typeByExtension(ext);
2023-06-07 17:09:40 -04:00
const file = await fetch(Configuration.Proxy + url.pathname);
2023-06-07 14:15:57 -04:00
const text = await file.text();
return new Response(text, {headers:{...headers, "content-type":type||""}});
}
catch(e)
{
return new Response(`{"error":"${e}", "path":"${url.pathname}"}`, {status:404, headers});
}
2023-06-06 12:50:50 -04:00
}
2023-06-07 11:22:49 -04:00
2023-06-07 14:15:57 -04:00
return new Response(`{"error":"unmatched route", "path":"${url.pathname}"}`, {status:404, headers});
2023-06-06 12:50:50 -04:00
});