Merge pull request 'api' (#3) from api into master

Reviewed-on: #3
This commit is contained in:
SethTrowbridge 2023-07-29 20:30:02 -04:00
commit 506fce9d7d
13 changed files with 160 additions and 128 deletions

17
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,17 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"request": "launch",
"name": "Debug Serve Mode",
"type": "node",
"cwd": "${workspaceFolder}/example",
"runtimeExecutable": "deno",
"runtimeArgs": ["task", "debug"],
"attachSimplePort": 9229
}
]
}

View File

@ -1,5 +1,4 @@
{
"deno.enable": true,
"deno.unstable": true,
"deno.config": "./deno.json"
"deno.unstable": true
}

4
api Normal file
View File

@ -0,0 +1,4 @@
export default (req:Request):Response|false=>
{
return false;
}

1
app Normal file
View File

@ -0,0 +1 @@
export default ()=>{};

View File

@ -7,11 +7,13 @@
{
"react":"https://esm.sh/preact@10.15.1/compat",
"react-original":"https://esm.sh/preact@10.15.1/compat",
"able/": "http://localhost:1234/"
">able/": "http://localhost:4507/"
},
"tasks":
{
"local": "deno run -A --no-lock ./run-local.tsx --port=1234",
"serve": "deno run -A --no-lock ./run-serve.tsx --port=1234"
"local": "deno run -A --reload=http://localhost --no-lock ./run-local.tsx --port=1234",
"serve": "deno run -A --reload=http://localhost --no-lock ./run-serve.tsx --port=1234",
"debug": "deno run -A --reload=http://localhost --inspect-wait --no-lock ./run-serve.tsx --port=1234",
"deploy":"deno run -A --no-lock --reload=http://localhost http://localhost:4507/run-deploy.tsx"
}
}

1
example/.env Normal file
View File

@ -0,0 +1 @@
DENO_DEPLOY_TOKEN=1

4
example/api.tsx Normal file
View File

@ -0,0 +1,4 @@
export default (inReq:Request)=>
{
return false;
}

View File

@ -1,4 +1,4 @@
import { Router, Switch, Case } from "able/iso-elements.tsx";
import { Router, Switch, Case } from ">able/iso-elements.tsx";
import React from "react";
@ -39,7 +39,7 @@ export default ()=>
return <CTXString.Provider value="intradestink">
<Router.Provider>
<div class="my-4 font-sans">
<h1 class="font-black text-xl text-red-500">Title</h1>
<h1 class="font-black text-xl text-red-500">Title?????</h1>
<h2 class="font-black text-blue-500 p-4">subtitle</h2>
<p>
<button onClick={e=>Dispatch(1)}>{Store.name}|{Store.age}?</button>

View File

@ -3,12 +3,15 @@
"imports":
{
"react": "https://esm.sh/preact@10.15.1/compat",
"able/": "http://localhost:1234/",
"entry": "./app.tsx"
">able/": "http://localhost:4507/",
">able/app": "./app.tsx",
">able/api": "./api.tsx"
},
"tasks":
{
"local": "deno run -A --no-lock --reload=http://localhost:1234 http://localhost:1234/run-local.tsx",
"serve": "deno run -A --no-lock --reload=http://localhost:1234 http://localhost:1234/run-serve.tsx"
"local": "deno run --config=deno.json -A --no-lock --reload=http://localhost:4507 http://localhost:4507/run-local.tsx",
"serve": "deno run --config=deno.json -A --no-lock --reload=http://localhost:4507 http://localhost:4507/run-serve.tsx",
"deploy":"deno run -A --no-lock --reload=http://localhost:4507 http://localhost:4507/run-deploy.tsx",
"debug": "deno run --config=deno.json -A --inspect-wait --no-lock --reload=http://localhost:4507 http://localhost:4507/run-serve.tsx"
}
}

View File

@ -1,15 +0,0 @@
import * as Util from "@able/";
import * as React from "react";
import {createElement} from "react/client";
import('react').then((module) => {
console.log(module);
});
function unimport(n:number)
{
return n;
}
unimport(123)

View File

@ -1,4 +1,4 @@
import { load } from "https://deno.land/std@0.194.0/dotenv/mod.ts";
import * as Env from "https://deno.land/std@0.194.0/dotenv/mod.ts";
import { parse } from "https://deno.land/std@0.194.0/flags/mod.ts";
@ -47,18 +47,12 @@ try
{
console.log("Runing deploy!");
const serveScript = import.meta.resolve("./run-serve.tsx");
console.log("Serve script:", serveScript);
let arg = parse(Deno.args);
let env = await load();
let env = await Env.load();
let useToken = await collect("DENO_DEPLOY_TOKEN", arg, env);
let useProject = await collect("DENO_DEPLOY_PROJECT", arg, env);
let useEntry = await collect("DENO_DEPLOY_ENTRY", arg, env);
Deno.env.set("DENO_DEPLOY_TOKEN", useToken || "");
Deno.env.set("DENO_DEPLOY_ENTRY", useEntry || "");
const command = new Deno.Command(
`deno`,
@ -70,6 +64,8 @@ try
"https://deno.land/x/deploy/deployctl.ts",
"deploy",
`--project=${useProject}`,
`--config=deno.json`,
`--token=${useToken}`,
serveScript
],
stdin: "piped",

View File

@ -1,4 +1,4 @@
import {Configure, Transpile, Extension} from "./run-serve.tsx";
import {Configure, Transpile, Extension, Root} from "./run-serve.tsx";
import * as Collect from "./hmr-static.tsx";
const SocketsLive:Set<WebSocket> = new Set();
@ -22,31 +22,20 @@ Configure({
Remap: (inImports, inConfig)=>
{
inImports["react-original"] = inImports["react"];
inImports["react"] = import.meta.resolve(`./hmr-react.tsx`);
inImports["react"] = `/>able/hmr-react.tsx`;
return inImports;
},
async Serve(inReq, inURL, inExt, inMap, inConfig)
{
if(!inURL.pathname.startsWith(encodeURI("/>")))
{
if(Transpile.Check(inExt) && !inURL.searchParams.get("reload"))
{
// const imp = await import(inConfig.Proxy+inURL.pathname);
// const members = [];
// for( const key in imp ) { members.push(key); }
//
// const code =`
//import {FileListen} from "${import.meta.resolve(`./hmr-listen.tsx`)}";
//import * as Import from "${inURL.pathname}?reload=0";
//${ members.map(m=>`let proxy_${m} = Import.${m}; export { proxy_${m} as ${m} };`).join("\n") }
//FileListen("${inURL.pathname}", (updatedModule)=>
//{
// ${ members.map(m=>`proxy_${m} = updatedModule.${m};`).join("\n") }
//});`
// we dont need to add ?reload= because this fetch is by way the file system not the hosted url
const [local, foreign] = await Collect.FileExports(inConfig.Proxy+inURL.pathname);
const [local, foreign] = await Collect.FileExports(Root+inURL.pathname);
const code =`
import {FileListen} from "${import.meta.resolve(`./hmr-listen.tsx`)}";
import {FileListen} from ">able/hmr-listen.tsx";
import * as Import from "${inURL.pathname}?reload=0";
${ local.map(m=>`let proxy_${m} = Import.${m}; export { proxy_${m} as ${m} };`).join("\n") }
FileListen("${inURL.pathname}", (updatedModule)=>
@ -74,6 +63,8 @@ ${ foreign.join(";\n") }
catch(e){ /**/ }
}
}
}
});
const Watcher =async()=>
@ -95,7 +86,7 @@ const Watcher =async()=>
const key = path.substring(Deno.cwd().length).replaceAll("\\", "/");
if(action != "remove")
{
const tsx = await Transpile.Fetch(`file://${Deno.cwd().replaceAll("\\", "/")}`+key, key, true);
const tsx = await Transpile.Fetch(Root+key, key, true);
tsx && SocketsSend(key);
}
else

View File

@ -1,6 +1,10 @@
import * as MIME from "https://deno.land/std@0.180.0/media_types/mod.ts";
import * as SWCW from "https://esm.sh/@swc/wasm-web@1.3.62";
import Api from ">able/api";
export const Root = new URL(`file://${Deno.cwd().replaceAll("\\", "/")}`).toString();
Deno.args.forEach(arg=>
{
@ -14,10 +18,11 @@ Deno.args.forEach(arg=>
type DenoConfig = {imports:Record<string, string>};
const ImportMap:DenoConfig = {imports:{}};
let ImportMapOriginal = {};
let ImportMapProxies:Record<string, string> = {};
const ImportMapReload =async()=>
{
let json:DenoConfig;
const path = Configuration.Proxy+"/deno.json";
const path = Root+"/deno.json";
try
{
const resp = await fetch(path);
@ -41,17 +46,32 @@ const ImportMapReload =async()=>
json.imports["react/"] = json.imports["react"]+"/";
}
if(!json.imports["entry"])
if(!json.imports["able:app"])
{
console.log(`"entry" specifier not defined in import map.`);
console.log(`"able:app" specifier not defined in import map.`);
}
ImportMapProxies = {};
Object.entries(json.imports).forEach(([key, value])=>
{
if(value.startsWith("./"))
{
json.imports[key] = value.substring(1);
}
if(key.startsWith(">"))
{
if(value.startsWith("./"))
{
ImportMapProxies[encodeURI(key)] = value.substring(1);
json.imports[key] = value.substring(1);
}
else
{
ImportMapProxies["/"+encodeURI(key)] = value;
json.imports[key] = "/"+key;
}
}
});
ImportMap.imports = Configuration.Remap(json.imports, Configuration);
@ -59,11 +79,10 @@ const ImportMapReload =async()=>
type CustomHTTPHandler = (inReq:Request, inURL:URL, inExt:string|false, inMap:{imports:Record<string, string>}, inConfig:Configuration)=>void|false|Response|Promise<Response|void|false>;
type CustomRemapper = (inImports:Record<string, string>, inConfig:Configuration)=>Record<string, string>;
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};
type Configuration = {Allow:string, Reset:string, SWCOp:SWCW.Options, Serve:CustomHTTPHandler, Shell:CustomHTTPHandler, Remap:CustomRemapper};
type ConfigurationArgs = {Allow?:string, Reset?:string, SWCOp?:SWCW.Options, Serve?:CustomHTTPHandler, Shell?:CustomHTTPHandler, Remap?:CustomRemapper};
let Configuration:Configuration =
{
Proxy: new URL(`file://${Deno.cwd().replaceAll("\\", "/")}`).toString(),
Allow: "*",
Reset: "/clear-cache",
async Serve(inReq, inURL, inExt, inMap, inConfig){},
@ -73,8 +92,6 @@ let Configuration:Configuration =
},
Shell(inReq, inURL, inExt, inMap, inConfig)
{
const parts = Deno.mainModule.split(inConfig.Proxy);
return new Response(
`<!doctype html>
<html>
@ -86,8 +103,8 @@ let Configuration:Configuration =
<div id="app"></div>
<script type="importmap">${JSON.stringify(inMap)}</script>
<script type="module">
import Mount from "${import.meta.resolve("./run-browser.tsx")}";
Mount("#app", "entry");
import Mount from ">able/run-browser.tsx";
Mount("#app", ">able/app");
</script>
</body>
</html>`, {status:200, headers:{"content-type":"text/html"}});
@ -133,6 +150,7 @@ export const Transpile =
return size;
},
/**
* DONT USE
* Converts dynamic module imports in to static, also can resolve paths with an import map
*/
async Patch(inPath:string, inKey:string, inMap?:DenoConfig)
@ -263,17 +281,46 @@ export const Configure =(config:ConfigurationArgs)=>
}
await ImportMapReload();
try
{
await SWCW.default();
}
catch(e)
{
console.log("swc init error:", e);
}
const server = Deno.serve({port:parseInt(Deno.env.get("port")||"8000")}, async(req: Request)=>
{
const url:URL = new URL(req.url);
const ext = Extension(url.pathname);
const headers = {"content-type":"application/json", "Access-Control-Allow-Origin": Configuration.Allow, "charset":"UTF-8"};
let proxy = Root + url.pathname;
// cache-reset route
if(url.pathname === Configuration.Reset)
if(url.pathname.includes("/__"))
{
return new Response(`{"cleared":${Transpile.Clear()}}`, {headers});
return new Response(`{"error":"unmatched route", "path":"${url.pathname}"}`, {status:404, headers});
}
// proxy imports
if(url.pathname.startsWith(encodeURI("/>")))
{
let bestMatch="";
for(let key in ImportMapProxies)
{
if(url.pathname.startsWith(key) && key.length > bestMatch.length)
{
bestMatch = key;
}
}
if(bestMatch.length)
{
const match = ImportMapProxies[bestMatch];
const path = url.pathname.substring(bestMatch.length);
proxy = path ? match + path : Root + match;
}
}
// allow for custom handler
@ -283,42 +330,17 @@ const server = Deno.serve({port:parseInt(Deno.env.get("port")||"8000")}, async(r
return custom;
}
const api = Api(req);
if(api)
{
return api;
}
// transpileable files
if(Transpile.Check(ext))
{
let code;
let path;
let file;
if( req.headers.get("user-agent")?.startsWith("Deno") || url.searchParams.has("deno") )
{
try
{
path = Configuration.Proxy + ExtensionPrefix(url.pathname, "deno");
console.log("looking for", path);
file = await fetch(path) as Response;
if(file.ok)
{
code = await file.text();
}
else
{
throw new Error("404");
}
}
catch(e)
{
path = Configuration.Proxy + url.pathname;
console.log("falling back to", path);
file = await fetch(path);
code = await file.text();
}
}
else
{
path = Configuration.Proxy + url.pathname;
code = await Transpile.Fetch(path, url.pathname);
}
console.log("transpiling:", proxy);
const code = await Transpile.Fetch(proxy, url.pathname);
if(code)
{
return new Response(code, {headers:{...headers, "content-type":"application/javascript"}} );
@ -335,13 +357,19 @@ const server = Deno.serve({port:parseInt(Deno.env.get("port")||"8000")}, async(r
}
}
// cache-reset route
if(url.pathname === Configuration.Reset)
{
return new Response(`{"cleared":${Transpile.Clear()}}`, {headers});
}
// all other static files
if(ext)
{
try
{
const type = MIME.typeByExtension(ext);
const file = await fetch(Configuration.Proxy + url.pathname);
const file = await fetch(proxy);
return new Response(file.body, {headers:{...headers, "content-type":type||""}});
}
catch(e)
@ -353,3 +381,4 @@ const server = Deno.serve({port:parseInt(Deno.env.get("port")||"8000")}, async(r
return new Response(`{"error":"unmatched route", "path":"${url.pathname}"}`, {status:404, headers});
});