Compare commits

...

8 Commits

Author SHA1 Message Date
506fce9d7d Merge pull request 'api' (#3) from api into master
Reviewed-on: #3
2023-07-29 20:30:02 -04:00
19097e1e68 tweak deploy script 2023-07-29 20:25:41 -04:00
06981cc067 fix path (no ext) 2023-07-29 18:49:44 -04:00
6cee7ac065 custom api handler started 2023-07-29 18:21:59 -04:00
b118ba02f9 setup debug 2023-07-29 17:13:49 -04:00
254cd45a2c fix hmr, modify example 2023-07-29 16:45:41 -04:00
2b59bd33aa add proxy imports!
remove file.deno.tsx falback
2023-07-29 13:57:44 -04:00
d2938ce6fe obscure double-undescore routes 2023-07-22 10:08:53 -04:00
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.enable": true,
"deno.unstable": true, "deno.unstable": true
"deno.config": "./deno.json"
} }

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":"https://esm.sh/preact@10.15.1/compat",
"react-original":"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": "tasks":
{ {
"local": "deno run -A --no-lock ./run-local.tsx --port=1234", "local": "deno run -A --reload=http://localhost --no-lock ./run-local.tsx --port=1234",
"serve": "deno run -A --no-lock ./run-serve.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"; import React from "react";
@ -39,7 +39,7 @@ export default ()=>
return <CTXString.Provider value="intradestink"> return <CTXString.Provider value="intradestink">
<Router.Provider> <Router.Provider>
<div class="my-4 font-sans"> <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> <h2 class="font-black text-blue-500 p-4">subtitle</h2>
<p> <p>
<button onClick={e=>Dispatch(1)}>{Store.name}|{Store.age}?</button> <button onClick={e=>Dispatch(1)}>{Store.name}|{Store.age}?</button>

View File

@ -3,12 +3,15 @@
"imports": "imports":
{ {
"react": "https://esm.sh/preact@10.15.1/compat", "react": "https://esm.sh/preact@10.15.1/compat",
"able/": "http://localhost:1234/", ">able/": "http://localhost:4507/",
"entry": "./app.tsx" ">able/app": "./app.tsx",
">able/api": "./api.tsx"
}, },
"tasks": "tasks":
{ {
"local": "deno run -A --no-lock --reload=http://localhost:1234 http://localhost:1234/run-local.tsx", "local": "deno run --config=deno.json -A --no-lock --reload=http://localhost:4507 http://localhost:4507/run-local.tsx",
"serve": "deno run -A --no-lock --reload=http://localhost:1234 http://localhost:1234/run-serve.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"; import { parse } from "https://deno.land/std@0.194.0/flags/mod.ts";
@ -47,18 +47,12 @@ try
{ {
console.log("Runing deploy!"); console.log("Runing deploy!");
const serveScript = import.meta.resolve("./run-serve.tsx"); const serveScript = import.meta.resolve("./run-serve.tsx");
console.log("Serve script:", serveScript);
let arg = parse(Deno.args); let arg = parse(Deno.args);
let env = await load(); let env = await Env.load();
let useToken = await collect("DENO_DEPLOY_TOKEN", arg, env); let useToken = await collect("DENO_DEPLOY_TOKEN", arg, env);
let useProject = await collect("DENO_DEPLOY_PROJECT", 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( const command = new Deno.Command(
`deno`, `deno`,
@ -70,6 +64,8 @@ try
"https://deno.land/x/deploy/deployctl.ts", "https://deno.land/x/deploy/deployctl.ts",
"deploy", "deploy",
`--project=${useProject}`, `--project=${useProject}`,
`--config=deno.json`,
`--token=${useToken}`,
serveScript serveScript
], ],
stdin: "piped", 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"; import * as Collect from "./hmr-static.tsx";
const SocketsLive:Set<WebSocket> = new Set(); const SocketsLive:Set<WebSocket> = new Set();
@ -22,57 +22,48 @@ Configure({
Remap: (inImports, inConfig)=> Remap: (inImports, inConfig)=>
{ {
inImports["react-original"] = inImports["react"]; inImports["react-original"] = inImports["react"];
inImports["react"] = import.meta.resolve(`./hmr-react.tsx`); inImports["react"] = `/>able/hmr-react.tsx`;
return inImports; return inImports;
}, },
async Serve(inReq, inURL, inExt, inMap, inConfig) async Serve(inReq, inURL, inExt, inMap, inConfig)
{ {
if(Transpile.Check(inExt) && !inURL.searchParams.get("reload")) 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 code =`
import {FileListen} from "${import.meta.resolve(`./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)=>
{
${ local.map(m=>`proxy_${m} = updatedModule.${m};`).join("\n") }
});
${ foreign.join(";\n") }
`
return new Response(code, {headers:{"content-type":"application/javascript"}});
}
if(inReq.headers.get("upgrade") == "websocket")
{
try
{ {
const { response, socket } = Deno.upgradeWebSocket(inReq);
socket.onopen = () => SocketsLive.add(socket); // we dont need to add ?reload= because this fetch is by way the file system not the hosted url
socket.onclose = () => SocketsLive.delete(socket); const [local, foreign] = await Collect.FileExports(Root+inURL.pathname);
socket.onmessage = (e) => {}; const code =`
socket.onerror = (e) => console.log("Socket errored:", e); import {FileListen} from ">able/hmr-listen.tsx";
return response; 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)=>
{
${ local.map(m=>`proxy_${m} = updatedModule.${m};`).join("\n") }
});
${ foreign.join(";\n") }
`
return new Response(code, {headers:{"content-type":"application/javascript"}});
} }
catch(e){ /**/ }
if(inReq.headers.get("upgrade") == "websocket")
{
try
{
const { response, socket } = Deno.upgradeWebSocket(inReq);
socket.onopen = () => SocketsLive.add(socket);
socket.onclose = () => SocketsLive.delete(socket);
socket.onmessage = (e) => {};
socket.onerror = (e) => console.log("Socket errored:", e);
return response;
}
catch(e){ /**/ }
}
} }
} }
}); });
@ -95,7 +86,7 @@ const Watcher =async()=>
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(`file://${Deno.cwd().replaceAll("\\", "/")}`+key, key, true); const tsx = await Transpile.Fetch(Root+key, key, true);
tsx && SocketsSend(key); tsx && SocketsSend(key);
} }
else else

View File

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