Serve es5 bundle if exists
[k0tyk.git] / k0tyk.js
blobe6205924e87405e8e0bec059066aaa5360fd497b
1 #!/usr/bin/qjs -m
2 /** @license 0BSD 2020 k0tyk <k0tyk@pm.me> */
3 import * as std from "std";
4 import { createElement as h } from "./.crank/index.js";
5 import { renderer } from "./.crank/html.js";
6 var m = `${std.in.getline()}`.split(" ") || ["", ""];
7 var [method, URL] = m;
8 /** @type {{ [x: string]: string }} */ var headers = {};
9 for (var x = ""; (x = std.in.getline()) && (x = x.trim()); )
10   if ((m = /(.+?): (.*)/.exec(x) || ["", "", ""])[0]) headers[m[1]] = m[2];
11 try {
12   var f = std.open(std.getenv("PWD") + URL, "r");
13 } catch (_) {}
14 if (f) for (var x = "", y = ""; (y = f.getline()) != null; x += y + "\n");
15 if (x) {
16   console.log("HTTP/1.1 200 OK");
17   console.log(`Content-Type: application/javascript; charset=utf-8\n\n${x}`);
18   std.exit();
20 var [pathname, search] = URL.split("?");
21 if (pathname == "/") pathname = "/index";
22 if (search) search = `?${search}`;
23 (async () => {
24   var { c, v } = await import(std.getenv("PWD") + pathname + "v.js");
25   var props = await c({ headers, location: { pathname, search }, method });
26   if (!/html/.test(headers["Accept"] || "")) {
27     x = JSON.stringify(props);
28     console.log("HTTP/1.1 200 OK");
29     console.log(`Content-Type: application/json; charset=utf-8\n\n${x}`);
30     return;
31   }
32   x = `<title>${props.title}</title>${renderer.render(h(v, props))}`;
33   var bundle = std.loadFile(
34     `${std.getenv("PWD")}${pathname.replace("/", "/.")}v.js`
35   );
36   x += bundle
37     ? `<script>${bundle}</script>`
38     : `<script type=module>import { createElement } from "/.crank/index.js";
39 import { renderer } from "/.crank/dom.js";
40 import { v } from "${pathname}v.js";
41 renderer.render(createElement(v, ${JSON.stringify(props)}), document.body);
42 </script>`;
43   console.log("HTTP/1.1 200 OK");
44   console.log(`Content-Type: text/html; charset=utf-8\n\n${x}`);
45 })().catch((e) => {
46   x = `${e.message}\n${e.stack}`;
47   console.log("HTTP/1.1 500 Internal Server Error");
48   console.log(`Content-Type: text/plain; charset=utf-8\n\n${x}`);
49 });