major: import Fresh 2.0 code (#2449)

🎉
This commit is contained in:
Marvin Hagemeister
2024-05-24 09:40:08 +02:00
committed by GitHub
parent 990357629e
commit 287929e4d2
958 changed files with 15794 additions and 28287 deletions
@@ -0,0 +1,134 @@
import * as path from "@std/path";
import * as colors from "@std/fmt/colors";
function tabs2Spaces(str: string) {
return str.replace(/^\t+/, (tabs) => " ".repeat(tabs.length));
}
/**
* Generate an excerpt of the location in the source around the
* specified position.
*/
export function createCodeFrame(
text: string,
lineNum: number,
columnNum: number,
): string | undefined {
// Default settings
const before = 2;
const after = 3;
const lines = text.split("\n");
// Check if specified range is valid
if (lines.length <= lineNum || lines[lineNum].length < columnNum) {
return;
}
const start = Math.max(0, lineNum - before);
const end = Math.min(lines.length, lineNum + after + 1);
// Maximum space needed for line numbering in the current range.
// Necessary when the amount of digits of the line numbering grows:
// 999 | asdf
// 1000 | asdjadfjsa
const maxLineNum = String(end).length;
const padding = " ".repeat(maxLineNum);
// Normalize all indentation (=tabs) to use 2 spaces. We need to
// apply the difference to the marker position to move it back in
// place.
const spaceLines: string[] = [];
let maxLineLen = 0;
for (let i = start; i < end; i++) {
const line = tabs2Spaces(lines[i]);
spaceLines.push(line);
if (line.length > maxLineLen) maxLineLen = line.length;
}
const activeLine = spaceLines[lineNum - start];
// Move marker into correct place by taking the amount of
// normalized tabs into account
const count = Math.max(
0,
activeLine.length - lines[lineNum].length + columnNum,
);
const sep = colors.dim("|");
let out = "";
for (let i = 0; i < spaceLines.length; i++) {
const line = spaceLines[i];
const currentLine = colors.dim(
(padding + (i + start + 1)).slice(-maxLineNum),
);
// Line where the error occurred
if (i === lineNum - start) {
out += colors.red(">") +
` ${currentLine} ${sep} ${line}\n`;
const columnMarker = colors.bold(colors.red("^"));
out += ` ${padding} ${sep} ${" ".repeat(count)}${columnMarker}\n`;
} else {
out += ` ${currentLine} ${sep} ${line}\n`;
}
}
return out;
}
const STACK_FRAME = /^\s*at\s+(?:(.*)\s+)?\((.*):(\d+):(\d+)\)$/;
export interface StackFrame {
fnName: string;
file: string;
line: number;
column: number;
}
function getFirstUserFile(
stack: string,
rootDir: string,
): StackFrame | undefined {
const lines = stack.split("\n");
for (let i = 0; i < lines.length; i++) {
const match = lines[i].match(STACK_FRAME);
if (match && match) {
const fnName = match[1] ?? "";
const file = match[2];
const line = +match[3];
const column = +match[4];
if (file.startsWith("file://")) {
const filePath = path.fromFileUrl(file);
if (path.relative(rootDir, filePath).startsWith(".")) {
continue;
}
return {
fnName,
file,
line,
column,
};
}
}
}
}
export function getCodeFrame(stack: string, rootDir: string) {
const file = getFirstUserFile(stack, rootDir);
if (file) {
try {
const filePath = path.fromFileUrl(file.file);
const text = Deno.readTextFileSync(filePath);
return createCodeFrame(
text,
file.line - 1,
file.column - 1,
);
} catch (err) {
// Ignore
}
}
}
@@ -0,0 +1,32 @@
import { DEV_ERROR_OVERLAY_URL } from "../../../constants.ts";
import { HttpError } from "../../../error.ts";
import type { MiddlewareFn } from "../../../middlewares/mod.ts";
import { FreshScripts } from "../../../runtime/server/preact_hooks.tsx";
import { ErrorOverlay } from "./overlay.tsx";
export function devErrorOverlay<T>(): MiddlewareFn<T> {
return async (ctx) => {
const { config, url } = ctx;
if (url.pathname === config.basePath + DEV_ERROR_OVERLAY_URL) {
return ctx.render(<ErrorOverlay url={url} />);
}
try {
return await ctx.next();
} catch (err) {
if (ctx.req.headers.get("accept")?.includes("text/html")) {
let init: ResponseInit | undefined;
if (err instanceof HttpError) {
if (err.status < 500) throw err;
init = { status: err.status };
}
// At this point we're pretty sure to have a server error
console.error(err);
return ctx.render(<FreshScripts />, init);
}
throw err;
}
};
}
@@ -0,0 +1,57 @@
import { expect } from "@std/expect";
import { App } from "../../../app.ts";
import { FakeServer } from "../../../test_utils.ts";
import { devErrorOverlay } from "./middleware.tsx";
import { HttpError } from "../../../error.ts";
Deno.test("error overlay - show when error is thrown", async () => {
const app = new App();
app.use(devErrorOverlay());
app.config.mode = "development";
app.get("/", () => {
throw new Error("fail");
});
const server = new FakeServer(await app.handler());
const res = await server.get("/", {
headers: {
accept: "text/html",
},
});
const content = await res.text();
expect(content).toContain("fresh-error-overlay");
});
Deno.test("error overlay - should not be visible for HttpError <500", async () => {
const app = new App();
app.use(devErrorOverlay());
app.config.mode = "development";
app
.get("/", () => {
throw new HttpError(404);
})
.get("/500", () => {
throw new HttpError(500);
});
const server = new FakeServer(await app.handler());
let res = await server.get("/", {
headers: {
accept: "text/html",
},
});
let content = await res.text();
expect(content).not.toContain("fresh-error-overlay");
expect(res.status).toEqual(404);
res = await server.get("/500", {
headers: {
accept: "text/html",
},
});
content = await res.text();
expect(content).toContain("fresh-error-overlay");
expect(res.status).toEqual(500);
});
@@ -0,0 +1,168 @@
import type { ComponentChildren } from "preact";
// Just to get some syntax highlighting
const css = (arr: TemplateStringsArray, ...exts: never[]) => {
if (exts.length) throw new Error("Not allowed");
return arr[0];
};
export const errorCss = css`
:root {
--bg: #fff;
--bg-code-frame: rgb(255, 0, 32, 0.1);
--bg-active-line: #fbcecc;
--text: #222;
--text2: #444;
--title: #e84644;
--code: #333;
font-family: sans-serif;
line-height: 1.4;
color: var(--text);
background: var(--bg);
}
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
@media (prefers-color-scheme: dark) {
:root {
--bg-code-frame: rgba(251, 93, 113, 0.2);
--bg-active-line: #4f1919;
--bg: #353535;
--text: #f7f7f7;
--text2: #ddd;
--code: #fdd1d1;
}
}
.inner {
max-width: 48rem;
padding: 4rem 1rem;
margin: 0 auto;
}
.title {
color: var(--title);
font-weight: normal;
font-size: 1.5rem;
margin-bottom: 1rem;
}
.code-frame {
overflow: auto;
padding: 0.5rem;
margin-bottom: 0.5rem;
background: var(--bg-code-frame);
color: var(--code);
}
.line {
padding: 0.25rem 0.5rem;
}
.active-line {
display: inline-block;
width: 100%;
background: var(--bg-active-line);
}
.stack {
overflow-x: auto;
}
.close-btn {
position: absolute;
top: 1rem;
right: 1rem;
color: var(--title);
display: block;
width: 3rem;
height: 3rem;
background: none;
border: none;
transform: translate3d(0, 0, 0);
}
.close-btn:active {
transform: translate3d(0, 2px, 0);
}
.close-btn:hover {
cursor: pointer;
filter: drop-shadow(0 0 0.75rem crimson);
}
`;
function CodeFrame(props: { codeFrame: string }) {
const lines: ComponentChildren[] = [];
props.codeFrame.trimEnd().split("\n").forEach(
(line, i, arr) => {
const vnode = (
<span
class={"line" + (line.startsWith(">") ? " active-line" : "")}
>
{line}
</span>
);
lines.push(vnode);
if (i < arr.length - 1) lines.push("\n");
},
);
return (
<pre class="code-frame">
<code>{lines}</code>
</pre>
);
}
const DEFAULT_MESSAGE = "Internal Server Error";
export function ErrorOverlay(props: { url: URL }) {
const url = props.url;
const title = url.searchParams.get("message") || DEFAULT_MESSAGE;
const stack = url.searchParams.get("stack");
const codeFrame = url.searchParams.get("code-frame");
if (title === DEFAULT_MESSAGE && !stack && !codeFrame) {
return null;
}
return (
<>
<div class="frsh-error-page">
<style dangerouslySetInnerHTML={{ __html: errorCss }} />
<div class="inner">
<div class="header">
<button class="close-btn" aria-label="close" id="close-btn">
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
strokeWidth={1.5}
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M9.75 9.75l4.5 4.5m0-4.5l-4.5 4.5M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg>
</button>
</div>
<div>
<h1 class="title">{title}</h1>
{codeFrame ? <CodeFrame codeFrame={codeFrame} /> : null}
{stack ? <pre class="stack">{stack}</pre> : null}
</div>
</div>
</div>
<script
dangerouslySetInnerHTML={{
__html:
`document.querySelector("#close-btn").addEventListener("click", () => parent.postMessage("close-error-overlay"));`,
}}
/>
</>
);
}
+39
View File
@@ -0,0 +1,39 @@
import type { MiddlewareFn } from "../../middlewares/mod.ts";
import { ALIVE_URL } from "../../constants.ts";
// Live reload: Send updates to browser
export function liveReload<T>(): MiddlewareFn<T> {
const revision = Date.now();
return (ctx) => {
const { config, req, url } = ctx;
const aliveUrl = config.basePath + ALIVE_URL;
if (url.pathname === aliveUrl) {
if (req.headers.get("upgrade") !== "websocket") {
return new Response(null, { status: 501 });
}
// TODO: When a change is made the Deno server restarts,
// so for now the WebSocket connection is only used for
// the client to know when the server is back up. Once we
// have HMR we'll actively start sending messages back
// and forth.
const { response, socket } = Deno.upgradeWebSocket(req);
socket.addEventListener("open", () => {
socket.send(
JSON.stringify({
type: "initial-state",
revision,
}),
);
});
return response;
}
return ctx.next();
};
}