modes #23

Merged
SethTrowbridge merged 7 commits from modes into master 2023-04-29 21:30:28 -04:00
2 changed files with 306 additions and 280 deletions
Showing only changes of commit 8917d179ef - Show all commits

View File

@ -9,6 +9,6 @@
},
"tasks": {
"host": "deno run -A --unstable https://deno.land/std@0.181.0/http/file_server.ts",
"dev": "deno run -A --unstable --reload=http://localhost:4507/ --no-lock --config=deno.jsonc 'http://localhost:4507/server.tsx?reload=1'"
"dev": "deno run -A --unstable --reload=http://localhost:4507/ --no-lock --config=deno.jsonc 'http://localhost:4507/server.tsx'"
}
}

View File

@ -60,307 +60,333 @@ const TranspileURL:Transpiler =async(inPath, inKey, inCheck)=>
const LibPath = "lib";
type ImportMap = {imports?:Record<string, string>, importMap?:string};
let App, TwindInst;
let ImportObject:ImportMap = {};
try
async function Configure(inDevMode:boolean, inLibPath:string)
{
const confDeno = await fetch(`${Path.Active}/deno.jsonc`);
const confText = await confDeno.text();
const confDenoParsed = JSONC(confText) as ImportMap;
if(confDenoParsed.importMap)
{
try
{
const confImports = await Deno.readTextFile(confDenoParsed.importMap);
try
{
ImportObject = JSON.parse(confImports);
}
catch(e)
{
console.log(`"importMap" "${confDenoParsed.importMap}" contains invalid JSON`);
}
}
catch(e)
{
console.log(`"importMap" "${confDenoParsed.importMap}" cannot be found`);
}
}
else if(confDenoParsed.imports)
{
ImportObject = {imports:confDenoParsed.imports};
}
if(ImportObject.imports)
{
const importReact = ImportObject.imports["react"];
if(importReact)
{
ImportObject.imports["react-original"] = importReact;
ImportObject.imports["react"] = `/${LibPath}/react.tsx`;
}
else
{
console.log(`"imports" configuration does not alias "react"`);
}
const importIso = ImportObject.imports["@eno/iso"];
if(importIso)
{
ImportObject.imports["@eno/iso"] = `/${LibPath}/iso.tsx`;
}
else
{
}
const importApp = ImportObject.imports["@eno/app"];
if(importApp)
{
let appImport
try
{
appImport = await import(Path.Active+importApp);
}
catch(e)
{
console.log(`"@eno/app" entry-point (${importApp}) file not found`)
}
if(typeof appImport.default == "function" )
{
App = appImport.default;
}
else
{
console.log(`"@eno/app" entry-point (${importApp}) needs to export a default function to use as the app root.`)
}
let twindConfig = Iso.CSS;
if(typeof appImport.CSS == "object")
{
twindConfig = {...twindConfig, ...appImport.CSS};
}
try
{
// @ts-ignore
TwindInst = Twind.install(twindConfig);
}
catch(e)
{
console.log(`CSS configuration is malformed`);
}
}
else
{
console.log(`"imports" configuration does not alias an entry-point file as "@eno/app"`);
}
Object.entries(ImportObject.imports).forEach(([key, value])=>{
if(value.startsWith("./") && ImportObject.imports)
{
ImportObject.imports[key] = value.substring(1);
}
})
}
else
{
console.log(`No "imports" found in configuration`);
}
}
catch(e)
{
console.log(`error during configuration: ${e}`);
}
Deno.serve({ port: Deno.args[0]||3000 }, async(_req:Request) =>
{
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];
console.log(pathParts, pathLast, pathExt);
console.log(`Request for "${url.pathname}"...`);
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)
{
//
}
}
type ImportMap = {imports?:Record<string, string>, importMap?:string};
const output:{Imports?:ImportMap, App?:React.FunctionComponent, TwindInst?:Twind.Twind, Error?:string} = {};
let ImportObject:ImportMap = {};
try
{
// serve index by default
let type = `text/html`;
let body:BodyInit = ``;
const isLib = url.pathname.startsWith(`/${LibPath}/`);
if(Transpileable(url.pathname))
const confDeno = await fetch(`${Path.Active}/deno.jsonc`);
const confText = await confDeno.text();
const confDenoParsed = JSONC(confText) as ImportMap;
if(confDenoParsed.importMap)
{
type = `application/javascript`;
if(isLib)
try
{
body = await TranspileURL(Path.Hosted+url.pathname, url.pathname, true);
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;
}
}
else if(!url.searchParams.get("reload"))
catch(e)
{
const imp = await import(Path.Active+url.pathname);
const members = [];
for( const key in imp ) { members.push(key); }
body =
`
import {FileListen} from "/${LibPath}/hmr.tsx";
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);`;
output.Error = `"importMap" "${confDenoParsed.importMap}" cannot be found`;
return output;
}
}
else if(confDenoParsed.imports)
{
output.Imports = {imports:confDenoParsed.imports};
}
if(output.Imports?.imports)
{
if(inDevMode)
{
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;
}
}
const importIso = output.Imports.imports["@eno/iso"];
if(importIso)
{
output.Imports.imports["@eno/iso"] = `/${inLibPath}/iso.tsx`;
}
else
{
body = await TranspileURL(Path.Active+url.pathname, url.pathname, true);
output.Error = `"imports" configuration does not alias "@eno/iso"`;
return output;
}
}
// serve static media
else if( pathExt )
{
type = MIME.typeByExtension(pathExt) || "text/html";
const _fetch = await fetch((isLib ? Path.Hosted : Path.Active)+url.pathname);
body = await _fetch.text();
}
else
{
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)
const importApp = output.Imports.imports["@eno/app"];
if(importApp)
{
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);
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;
}
}
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>
<title>${Iso.Meta.title}</title>
<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(ImportObject)}</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";
import {Router, Fetch, CSS} from "@eno/iso";
Twind.install(App.CSS ? {...CSS, ...App.CSS} : CSS);
Fetch.Seed(${JSON.stringify(seed)});
const hmrWrap = H( ()=>H(App.default) );
hydrate( H(Router.Provider, null, hmrWrap), document.querySelector("#app"));
</script>
</body>
</html>`;
}
return new Response(body, {headers:{"content-type":type as string, "Access-Control-Allow-Origin":"*", charset:"utf-8"}});
}
catch(error)
{
console.log(error);
return new Response(error, {status:404});
}
});
const Sockets:Set<WebSocket> = new Set();
const SocketsBroadcast =(inData:string)=>{ for (const socket of Sockets){ socket.send(inData); } }
const FilesChanged:Map<string, string> = new Map();
const ProcessFiles =debounce(async()=>
{
console.log("Processing Files...", FilesChanged);
for await (const [path, action] of FilesChanged)
{
const key = path.substring(Deno.cwd().length).replaceAll("\\", "/");
console.log(key, action);
if(action != "remove")
{
await TranspileURL(Path.Active+key, key, false);
console.log(` ...cached "${key}"`);
SocketsBroadcast(key);
else
{
output.Error = `"imports" configuration does not alias an entry-point file as "@eno/app"`;
return output;
}
Object.entries(output.Imports.imports).forEach(([key, value])=>{
if(value.startsWith("./") && output.Imports?.imports)
{
output.Imports.imports[key] = value.substring(1);
}
})
}
else
{
Transpiled.delete(key);
output.Error = `No "imports" found in configuration`;
return output;
}
}
FilesChanged.clear();
}, 1000);
for await (const event of Deno.watchFs(Deno.cwd()))
{
event.paths.forEach( path =>
catch(e)
{
if(Transpileable(path))
output.Error = `error during configuration: ${e}`;
return output;
}
return output;
}
const {Imports, App, TwindInst, Error} = await Configure(true, LibPath);
if(Error)
{
console.log(Error);
}
if(App && TwindInst)
{
Deno.serve({ port: Deno.args[0]||3000 }, async(_req:Request) =>
{
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];
console.log(pathParts, pathLast, pathExt);
console.log(`Request for "${url.pathname}"...`);
if(_req.headers.get("upgrade") == "websocket")
{
FilesChanged.set(path, event.kind);
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)
{
//
}
}
try
{
// serve index by default
let type = `text/html`;
let body:BodyInit = ``;
const isLib = url.pathname.startsWith(`/${LibPath}/`);
if(Transpileable(url.pathname))
{
type = `application/javascript`;
if(isLib)
{
body = await TranspileURL(Path.Hosted+url.pathname, url.pathname, true);
}
else if(!url.searchParams.get("reload"))
{
const imp = await import(Path.Active+url.pathname);
const members = [];
for( const key in imp ) { members.push(key); }
body =
`
import {FileListen} from "/${LibPath}/hmr.tsx";
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);
}
}
// serve static media
else if( pathExt )
{
type = MIME.typeByExtension(pathExt) || "text/html";
const _fetch = await fetch((isLib ? Path.Hosted : Path.Active)+url.pathname);
body = await _fetch.text();
}
else
{
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>
<title>${Iso.Meta.title}</title>
<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";
import {Router, Fetch, CSS} from "@eno/iso";
Twind.install(App.CSS ? {...CSS, ...App.CSS} : CSS);
Fetch.Seed(${JSON.stringify(seed)});
const hmrWrap = H( ()=>H(App.default) );
hydrate( H(Router.Provider, null, hmrWrap), document.querySelector("#app"));
</script>
</body>
</html>`;
}
return new Response(body, {headers:{"content-type":type as string, "Access-Control-Allow-Origin":"*", charset:"utf-8"}});
}
catch(error)
{
console.log(error);
return new Response(error, {status:404});
}
});
if(FilesChanged.size)
const Sockets:Set<WebSocket> = new Set();
const SocketsBroadcast =(inData:string)=>{ for (const socket of Sockets){ socket.send(inData); } }
const FilesChanged:Map<string, string> = new Map();
const ProcessFiles =debounce(async()=>
{
ProcessFiles();
console.log("Processing Files...", FilesChanged);
for await (const [path, action] of FilesChanged)
{
const key = path.substring(Deno.cwd().length).replaceAll("\\", "/");
console.log(key, action);
if(action != "remove")
{
await TranspileURL(Path.Active+key, key, false);
console.log(` ...cached "${key}"`);
SocketsBroadcast(key);
}
else
{
Transpiled.delete(key);
}
}
FilesChanged.clear();
}, 1000);
for await (const event of Deno.watchFs(Deno.cwd()))
{
event.paths.forEach( path =>
{
if(Transpileable(path))
{
FilesChanged.set(path, event.kind);
}
});
if(FilesChanged.size)
{
ProcessFiles();
}
}
}