eno/server.tsx

438 lines
14 KiB
TypeScript
Raw Permalink Normal View History

import * as ESBuild from 'https://deno.land/x/esbuild@v0.17.4/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-04-29 11:15:54 -04:00
import { parse as JSONC} from "https://deno.land/std@0.185.0/jsonc/mod.ts";
2023-04-02 14:16:46 -04:00
import SSR from "https://esm.sh/v113/preact-render-to-string@6.0.2";
2023-04-22 12:08:58 -04:00
import Prepass from "https://esm.sh/preact-ssr-prepass@1.2.0";
2023-04-05 20:05:21 -04:00
import * as Twind from "https://esm.sh/@twind/core@1.1.3";
2023-04-13 22:23:04 -04:00
import React from "react";
2023-04-06 23:44:27 -04:00
import * as Iso from "@eno/iso";
2023-03-17 11:54:36 -04:00
2023-04-29 20:16:28 -04:00
Deno.env.set("initialized", "true");
2023-04-29 13:55:37 -04:00
/**
* Setup a transpiler.
* @param inDevMode When true, starts a file-watcher
* @returns
*/
function Transpiler(inDevMode:boolean)
2022-12-01 17:10:59 -05:00
{
2023-04-29 13:55:37 -04:00
const Transpiled = new Map();
const Transpileable =(inFilePath:string):boolean=>
2023-03-17 11:54:36 -04:00
{
2023-04-29 13:55:37 -04:00
let dotIndex = inFilePath.length-4;
if(inFilePath[dotIndex] !== ".")
2023-03-17 11:54:36 -04:00
{
2023-04-29 13:55:37 -04:00
if(inFilePath[++dotIndex] !== ".")
{
return false;
}
2023-03-17 11:54:36 -04:00
}
2023-04-29 13:55:37 -04:00
if(inFilePath[dotIndex+2] == "s")
{
const first = inFilePath[dotIndex+1];
return (first == "t" || first == "j");
}
return false;
};
const Transpile =async(inCode:string, inKey:string):Promise<string>=>
{
const transpile = await ESBuild.transform(inCode, inDevMode ? { loader: "tsx", sourcemap:"inline", minify: false, sourcefile:inKey} :
{ loader: "tsx",
minify:true,
jsx:"automatic",
jsxImportSource:"https://esm.sh/preact@10.13.2"});
2023-04-29 13:55:37 -04:00
Transpiled.set(inKey, transpile.code);
return transpile.code;
};
type Transpiler = (inPath:string, inKey:string, inCheck?:boolean)=>Promise<string>;
const TranspileURL:Transpiler =async(inPath, inKey, inCheck)=>
{
if(inCheck)
{
const cached = Transpiled.get(inKey);
if(cached)
{
return cached;
}
}
let body = await fetch(inPath);
let text = await body.text();
return Transpile(text, inKey);
};
const Sockets:Set<WebSocket> = new Set();
const SocketsBroadcast =(inData:string)=>{ for (const socket of Sockets){ socket.send(inData); } }
const SocketsHandler = inDevMode ? (_req:Request)=>
2023-03-17 11:54:36 -04:00
{
2023-04-29 13:55:37 -04:00
if(_req.headers.get("upgrade") == "websocket")
{
try
{
const { response, socket } = Deno.upgradeWebSocket(_req);
socket.onopen = () => Sockets.add(socket);
socket.onclose = () => Sockets.delete(socket);
socket.onmessage = (e) => {};
socket.onerror = (e) => console.log("Socket errored:", e);
return response;
}
catch(e)
{
//
}
}
return false;
2023-03-17 11:54:36 -04:00
}
2023-04-29 13:55:37 -04:00
:
()=>false;
2023-03-17 11:54:36 -04:00
let reloads = 0;
2023-04-29 13:55:37 -04:00
const watcher =async()=>
2023-03-27 23:05:20 -04:00
{
2023-04-29 13:55:37 -04:00
const FilesChanged:Map<string, string> = new Map();
const ProcessFiles =debounce(async()=>
{
for await (const [path, action] of FilesChanged)
{
const key = path.substring(Deno.cwd().length).replaceAll("\\", "/");
if(action != "remove")
{
if(Imports?.imports)
{
reloads++;
const importApp = Imports.imports["@eno/app"];
const imp = await import(Path.Active+importApp+"?reloads="+reloads);
App = imp.default;
}
2023-04-29 13:55:37 -04:00
await TranspileURL(Path.Active+key, key, false);
SocketsBroadcast(key);
}
else
{
Transpiled.delete(key);
}
}
FilesChanged.clear();
}, 1000);
for await (const event of Deno.watchFs(Deno.cwd()))
2023-03-27 23:05:20 -04:00
{
2023-04-29 13:55:37 -04:00
event.paths.forEach( path =>
{
if(Transpileable(path))
{
FilesChanged.set(path, event.kind);
}
});
if(FilesChanged.size)
{
ProcessFiles();
}
2023-03-27 23:05:20 -04:00
}
}
2023-04-29 13:55:37 -04:00
if(inDevMode)
{
watcher().then(()=>{console.log("done watching");});
}
2022-12-01 17:10:59 -05:00
2023-04-29 13:55:37 -04:00
return {TranspileURL, Transpileable, SocketsHandler};
2023-04-29 11:49:52 -04:00
2023-04-29 13:55:37 -04:00
}
2023-04-29 11:49:52 -04:00
2023-04-29 13:55:37 -04:00
/**
* Extract all configuration info form a project's deno.jsonc file
* @param inDevMode When true, proxies react to an HMR-enabled version
* @param inLibPath
* @returns
*/
2023-04-29 11:49:52 -04:00
async function Configure(inDevMode:boolean, inLibPath:string)
2023-03-17 11:54:36 -04:00
{
2023-04-29 11:49:52 -04:00
type ImportMap = {imports?:Record<string, string>, importMap?:string};
const output:{Imports?:ImportMap, App?:React.FunctionComponent, TwindInst?:Twind.Twind, Error?:string} = {};
let ImportObject:ImportMap = {};
try
2023-03-17 11:54:36 -04:00
{
2023-04-29 11:49:52 -04:00
const confDeno = await fetch(`${Path.Active}/deno.jsonc`);
const confText = await confDeno.text();
const confDenoParsed = JSONC(confText) as ImportMap;
if(confDenoParsed.importMap)
2023-03-17 11:54:36 -04:00
{
try
{
2023-04-29 11:49:52 -04:00
const confImports = await Deno.readTextFile(confDenoParsed.importMap);
try
{
output.Imports = JSON.parse(confImports);
}
catch(e)
{
output.Error = `"importMap" "${confDenoParsed.importMap}" contains invalid JSON`;
return output;
}
2023-03-17 11:54:36 -04:00
}
catch(e)
{
2023-04-29 11:49:52 -04:00
output.Error = `"importMap" "${confDenoParsed.importMap}" cannot be found`;
return output;
2023-03-17 11:54:36 -04:00
}
}
2023-04-29 11:49:52 -04:00
else if(confDenoParsed.imports)
2023-03-17 11:54:36 -04:00
{
2023-04-29 11:49:52 -04:00
output.Imports = {imports:confDenoParsed.imports};
2023-03-17 11:54:36 -04:00
}
2023-04-29 11:49:52 -04:00
if(output.Imports?.imports)
2023-03-22 17:45:25 -04:00
{
2023-04-29 11:49:52 -04:00
if(inDevMode)
2023-04-29 11:15:54 -04:00
{
2023-04-29 11:49:52 -04:00
const importReact = output.Imports.imports["react"];
if(importReact)
{
output.Imports.imports["react-original"] = importReact;
output.Imports.imports["react"] = `/${inLibPath}/react.tsx`;
}
else
{
output.Error = `"imports" configuration does not alias "react"`;
return output;
}
2023-04-29 11:15:54 -04:00
}
2023-04-29 11:49:52 -04:00
const importIso = output.Imports.imports["@eno/iso"];
if(importIso)
2023-04-29 11:15:54 -04:00
{
2023-04-29 11:49:52 -04:00
output.Imports.imports["@eno/iso"] = `/${inLibPath}/iso.tsx`;
2023-04-29 11:15:54 -04:00
}
else
{
2023-04-29 11:49:52 -04:00
output.Error = `"imports" configuration does not alias "@eno/iso"`;
return output;
2023-04-29 11:15:54 -04:00
}
2023-04-29 11:49:52 -04:00
const importApp = output.Imports.imports["@eno/app"];
if(importApp)
2023-04-29 11:15:54 -04:00
{
2023-04-29 11:49:52 -04:00
let appImport
try
{
appImport = await import(Path.Active+importApp);
}
catch(e)
{
output.Error = `"@eno/app" entry-point (${importApp}) file not found`;
return output;
}
if(typeof appImport.default == "function" )
{
output.App = appImport.default;
}
else
{
output.Error = `"@eno/app" entry-point (${importApp}) needs to export a default function to use as the app root.`;
return output;
}
let twindConfig = Iso.CSS;
if(typeof appImport.CSS == "object")
{
twindConfig = {...twindConfig, ...appImport.CSS};
}
try
{
// @ts-ignore
output.TwindInst = Twind.install(twindConfig);
}
catch(e)
{
output.Error = `CSS configuration is malformed`;
return output;
}
2023-04-29 11:15:54 -04:00
}
2023-04-29 11:49:52 -04:00
else
2023-04-29 11:15:54 -04:00
{
2023-04-29 11:49:52 -04:00
output.Error = `"imports" configuration does not alias an entry-point file as "@eno/app"`;
return output;
2023-04-29 11:15:54 -04:00
}
2023-04-29 11:49:52 -04:00
Object.entries(output.Imports.imports).forEach(([key, value])=>{
if(value.startsWith("./") && output.Imports?.imports)
{
output.Imports.imports[key] = value.substring(1);
}
})
}
else
{
2023-04-29 11:49:52 -04:00
output.Error = `No "imports" found in configuration`;
return output;
}
2023-03-22 17:45:25 -04:00
}
2023-04-29 11:49:52 -04:00
catch(e)
2023-03-22 17:45:25 -04:00
{
2023-04-29 11:49:52 -04:00
output.Error = `error during configuration: ${e}`;
return output;
2023-03-22 17:45:25 -04:00
}
2023-04-29 11:49:52 -04:00
return output;
2023-03-17 11:54:36 -04:00
}
2023-03-31 06:55:54 -04:00
const Flags:Record<string, string|boolean> = {};
Deno.args.forEach(arg=>
{
if(arg.startsWith("--"))
{
const kvp = arg.substring(2).split("=");
Flags[kvp[0]] = kvp[1] ? kvp[1] : true;
}
});
let DevMode = Flags.dev ? true : false;
2023-04-29 13:55:37 -04:00
let hosted = import.meta.resolve("./");
const Path = {
Hosted: hosted.substring(0, hosted.length-1),
Active: `file://${Deno.cwd().replaceAll("\\", "/")}`,
LibDir: "lib"
};
console.log(Path);
console.log(`Dev Mode: ${DevMode}`);
console.log(`Args seen: `, Flags);
2023-04-02 14:16:46 -04:00
2023-04-29 13:55:37 -04:00
const {Transpileable, TranspileURL, SocketsHandler} = Transpiler(DevMode);
let {Imports, App, TwindInst, Error} = await Configure(DevMode, Path.LibDir);
2023-04-29 11:49:52 -04:00
if(Error)
2022-12-01 17:10:59 -05:00
{
2023-04-29 11:49:52 -04:00
console.log(Error);
}
2023-04-29 13:55:37 -04:00
else if(App && TwindInst)
2023-04-29 11:49:52 -04:00
{
Deno.serve({ port: Flags?.port||3000 }, async(_req:Request) =>
2023-03-20 17:41:57 -04:00
{
2023-04-29 11:49:52 -04:00
const url:URL = new URL(_req.url);
const pathParts = url.pathname.substring(1, url.pathname.endsWith("/") ? url.pathname.length-1 : url.pathname.length).split("/");
const pathLast = pathParts.at(-1);
const pathExt:string|undefined = pathLast?.split(".")[1];
2023-04-29 13:55:37 -04:00
const resp = SocketsHandler(_req);
if(resp){ return resp; }
2023-04-29 11:49:52 -04:00
try
2022-12-01 17:10:59 -05:00
{
2023-04-29 11:49:52 -04:00
// serve index by default
let type = `text/html`;
let body:BodyInit = ``;
2023-04-29 13:55:37 -04:00
const isLib = url.pathname.startsWith(`/${Path.LibDir}/`);
2023-04-29 11:49:52 -04:00
if(Transpileable(url.pathname))
2022-12-01 17:10:59 -05:00
{
2023-04-29 11:49:52 -04:00
type = `application/javascript`;
if(isLib)
{
body = await TranspileURL(Path.Hosted+url.pathname, url.pathname, true);
}
else if(DevMode && !url.searchParams.get("reload"))
2023-04-29 11:49:52 -04:00
{
const imp = await import(Path.Active+url.pathname);
const members = [];
for( const key in imp ) { members.push(key); }
body =
`
2023-04-29 13:55:37 -04:00
import {FileListen} from "/${Path.LibDir}/hmr.tsx";
2023-04-29 11:49:52 -04:00
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") }
};
FileListen("${url.pathname}", reloadHandler);`;
}
else
{
body = await TranspileURL(Path.Active+url.pathname, url.pathname, true);
}
2023-03-27 23:05:20 -04:00
}
2023-04-29 11:49:52 -04:00
// serve static media
else if( pathExt )
2023-03-27 23:05:20 -04:00
{
2023-04-29 11:49:52 -04:00
type = MIME.typeByExtension(pathExt) || "text/html";
2023-04-29 13:55:37 -04:00
const _fetch = await fetch((Path.Active)+url.pathname);
2023-04-29 11:49:52 -04:00
body = await _fetch.text();
2023-03-20 17:41:57 -04:00
}
2023-03-27 23:05:20 -04:00
else
{
2023-04-29 11:49:52 -04:00
Iso.Fetch.ServerBlocking = [];
Iso.Fetch.ServerTouched = new Set();
Iso.Fetch.ServerRemove = new Set();
let app = <Iso.Router.Provider url={url}><App/></Iso.Router.Provider>;
await Prepass(app)
let bake = SSR(app);
while(Iso.Fetch.ServerBlocking.length)
{
await Promise.all(Iso.Fetch.ServerBlocking);
Iso.Fetch.ServerBlocking = [];
// at this point, anything that was requested that was not cached, has now been loaded and cached
// this next render will use cached resources. using a cached resource (if its "Seed" is true) adds it to the "touched" set.
app = <Iso.Router.Provider url={url}><App/></Iso.Router.Provider>;
await Prepass(app)
bake = SSR(app);
}
const seed:Iso.FetchRecord[] = [];
Iso.Fetch.ServerTouched.forEach((record)=>{
const r:Iso.FetchRecord = {...record};
delete r.Promise;
seed.push(r);
});
Iso.Fetch.ServerTouched = false;
const results = Twind.extract(bake, TwindInst);
type = `text/html`;
body =
`<!doctype html>
<html lang="en">
<head>
2023-04-29 21:15:14 -04:00
<title>${Iso.Meta.Meta.title}</title>
2023-04-29 11:49:52 -04:00
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8"/>
<style data-twind>${results.css}</style>
<script type="importmap">${JSON.stringify(Imports)}</script>
</head>
<body>
<div id="app">${results.html}</div>
<script type="module">
import {hydrate, createElement as H} from "react";
import * as Twind from "https://esm.sh/v115/@twind/core@1.1.3/es2022/core.mjs";
import * as App from "@eno/app";
2023-04-29 21:15:14 -04:00
import {Router, Fetch, CSS, Meta} from "@eno/iso";
2023-04-29 11:49:52 -04:00
Twind.install(App.CSS ? {...CSS, ...App.CSS} : CSS);
Fetch.Seed(${JSON.stringify(seed)});
const hmrWrap = H( ()=>H(App.default) );
2023-04-29 21:15:14 -04:00
hydrate(
H(Router.Provider, null,
H(Meta.Provider, null, hmrWrap)
),
document.querySelector("#app")
);
2023-04-29 11:49:52 -04:00
</script>
</body>
</html>`;
2023-03-27 23:05:20 -04:00
}
2023-04-29 11:49:52 -04:00
return new Response(body, {headers:{"content-type":type as string, "Access-Control-Allow-Origin":"*", charset:"utf-8"}});
2023-03-27 23:05:20 -04:00
}
2023-04-29 11:49:52 -04:00
catch(error)
2023-03-27 23:05:20 -04:00
{
2023-04-29 11:49:52 -04:00
console.log(error);
return new Response(error, {status:404});
2022-12-01 17:10:59 -05:00
}
2023-04-29 11:49:52 -04:00
});
2022-12-01 17:10:59 -05:00
}