feat(server): Add basePath config to host from a directory (#2092)

Co-authored-by: Marvin Hagemeister <marvin@deno.com>
This commit is contained in:
Reed von Redwitz
2023-11-29 16:44:25 +00:00
committed by GitHub
co-authored by Marvin Hagemeister
parent fe792455ab
commit 9ab8651018
40 changed files with 810 additions and 28 deletions
+170
View File
@@ -0,0 +1,170 @@
import {
assert,
assertEquals,
assertMatch,
delay,
puppeteer,
STATUS_CODE,
} from "./deps.ts";
import {
clickWhenListenerReady,
getErrorOverlay,
waitForText,
withFakeServe,
withFresh,
withPageName,
} from "./test_utils.ts";
Deno.test("redirects on incomplete base path in url", async () => {
await withFresh("./tests/fixture_base_path/main.ts", async (address) => {
await delay(100);
const url = new URL(address);
const res = await fetch(url.origin);
assert(
res.url.endsWith("/foo/bar"),
`didn't redirect to base path: "${res.url}"`,
);
assert(res.redirected, "did not redirect");
assertEquals(res.status, STATUS_CODE.OK);
await res.body?.cancel();
});
});
Deno.test("shows full address with base path in cli", async () => {
// deno-lint-ignore require-await
await withFresh("./tests/fixture_base_path/main.ts", async (address) => {
assertMatch(address, /^http:\/\/localhost:\d+\/foo\/bar$/);
});
});
Deno.test("rewrites middleware request", async () => {
await withFresh("./tests/fixture_base_path/main.ts", async (address) => {
const res = await fetch(`${address}/api`);
const body = await res.text();
assertEquals(body, "it works");
});
});
Deno.test("rewrites root relative middleware redirects", async () => {
await withFresh("./tests/fixture_base_path/main.ts", async (address) => {
const res = await fetch(`${address}/api/rewrite`);
assertEquals(res.status, STATUS_CODE.OK);
assertEquals(res.url, address);
await res.body?.cancel();
});
});
Deno.test("passes basePath to route handlers", async () => {
await withFresh("./tests/fixture_base_path/main.ts", async (address) => {
const res = await fetch(`${address}/api/base-handler`);
assertEquals(res.status, STATUS_CODE.OK);
assertEquals(await res.text(), "/foo/bar");
});
});
Deno.test("works with relative urls", async () => {
await withFresh("./tests/fixture_base_path/main.ts", async (address) => {
const browser = await puppeteer.launch({ args: ["--no-sandbox"] });
const page = await browser.newPage();
await page.goto(`${address}/a/b/relative`);
await Promise.all([
page.waitForNavigation(),
page.click("a"),
]);
const html = await page.content();
assertMatch(html, /it works/);
await browser.close();
});
});
Deno.test("rewrites root relative URLs in HTML", async () => {
await withFresh("./tests/fixture_base_path/main.ts", async (address) => {
const browser = await puppeteer.launch({ args: ["--no-sandbox"] });
const page = await browser.newPage();
await page.goto(`${address}/html`);
const script = await page.$eval("#script-output", (el) => el.textContent);
assertEquals(script, "it works");
const img = await page.$eval("img", (el) => ({
src: el.src,
}));
assertMatch(img.src, /\/foo\/bar\/img\.png/);
const img2 = await page.$eval(".img-srcset", (el) => ({
src: el.src,
srcset: el.srcset,
}));
assertMatch(img2.src, /\/foo\/bar\/img\.png/);
assertMatch(
img2.srcset,
/\/foo\/bar\/img\.png.* 480w,.*\/foo\/bar\/img\.png.* 800w/,
);
const source = await page.$eval("picture source", (el) => ({
srcset: el.srcset,
}));
assertMatch(
source.srcset,
/\/foo\/bar\/img\.png/,
);
const style = await page.$eval(
".foo",
(el) => window.getComputedStyle(el).color,
);
assertMatch(
style,
/rgb\(255,\s+0,\s+0\)/,
);
await browser.close();
});
});
Deno.test("island tests", async (t) => {
await withPageName(
"./tests/fixture_base_path/main.ts",
async (page, address) => {
async function counterTest(counterId: string, originalValue: number) {
const pElem = await page.waitForSelector(`#${counterId} > p`);
const value = await pElem?.evaluate((el) => el.textContent);
assert(value === `${originalValue}`, `${counterId} first value`);
await clickWhenListenerReady(page, `#b-${counterId}`);
await waitForText(page, `#${counterId} > p`, String(originalValue + 1));
}
await page.goto(`${address}/islands`);
await t.step("Ensure 1 islands on 1 page are revived", async () => {
await counterTest("counter1", 3);
});
},
);
});
Deno.test("renders error boundary", async () => {
await withPageName(
"./tests/fixture_base_path/main.ts",
async (page, address) => {
await page.goto(`${address}/error_boundary`);
const text = await page.$eval("p", (el) => el.textContent);
assertEquals(text, "it works");
},
);
});
Deno.test("dev_command config: shows codeframe", async () => {
await withFakeServe(
"./tests/fixture_base_path/dev.ts",
async (server) => {
const { codeFrame } = await getErrorOverlay(server, "/codeframe");
assert(codeFrame);
},
);
});
+2
View File
@@ -44,3 +44,5 @@ export {
} from "https://deno.land/std@0.208.0/path/mod.ts";
export * as JSONC from "https://deno.land/std@0.208.0/jsonc/mod.ts";
export * as colors from "https://deno.land/std@0.208.0/fmt/colors.ts";
export { STATUS_CODE } from "https://deno.land/std@0.208.0/http/status.ts";
export { stripAnsiCode } from "https://deno.land/std@0.208.0/fmt/colors.ts";
+18
View File
@@ -0,0 +1,18 @@
{
"lock": false,
"tasks": {
"start": "deno run -A --watch=static/,routes/ dev.ts"
},
"imports": {
"$fresh/": "../../",
"preact": "https://esm.sh/preact@10.15.1",
"preact/": "https://esm.sh/preact@10.15.1/",
"@preact/signals": "https://esm.sh/*@preact/signals@1.2.2",
"@preact/signals-core": "https://esm.sh/@preact/signals-core@1.5.0",
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.1.0"
},
"compilerOptions": {
"jsx": "react-jsx",
"jsxImportSource": "preact"
}
}
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env -S deno run -A --watch=static/,routes/
import dev from "$fresh/dev.ts";
await dev(import.meta.url, "./main.ts");
+41
View File
@@ -0,0 +1,41 @@
// DO NOT EDIT. This file is generated by Fresh.
// This file SHOULD be checked into source version control.
// This file is automatically updated during development when running `dev.ts`.
import * as $_middleware from "./routes/_middleware.ts";
import * as $a_b_b from "./routes/a/b/b.tsx";
import * as $a_b_relative_index from "./routes/a/b/relative/index.tsx";
import * as $api_base_handler from "./routes/api/base-handler.ts";
import * as $api_index from "./routes/api/index.ts";
import * as $api_rewrite from "./routes/api/rewrite.ts";
import * as $baz_slug_ from "./routes/baz/[...slug].tsx";
import * as $codeframe from "./routes/codeframe.tsx";
import * as $error_boundary from "./routes/error_boundary.tsx";
import * as $html from "./routes/html.tsx";
import * as $index from "./routes/index.tsx";
import * as $islands from "./routes/islands.tsx";
import * as $$Counter from "./islands/Counter.tsx";
import { Manifest } from "$fresh/server.ts";
const manifest = {
routes: {
"./routes/_middleware.ts": $_middleware,
"./routes/a/b/b.tsx": $a_b_b,
"./routes/a/b/relative/index.tsx": $a_b_relative_index,
"./routes/api/base-handler.ts": $api_base_handler,
"./routes/api/index.ts": $api_index,
"./routes/api/rewrite.ts": $api_rewrite,
"./routes/baz/[...slug].tsx": $baz_slug_,
"./routes/codeframe.tsx": $codeframe,
"./routes/error_boundary.tsx": $error_boundary,
"./routes/html.tsx": $html,
"./routes/index.tsx": $index,
"./routes/islands.tsx": $islands,
},
islands: {
"./islands/Counter.tsx": $$Counter,
},
baseUrl: import.meta.url,
} satisfies Manifest;
export default manifest;
@@ -0,0 +1,22 @@
import type { Signal } from "@preact/signals";
import { IS_BROWSER } from "$fresh/runtime.ts";
interface CounterProps {
count: Signal<number>;
id: string;
}
export default function Counter(props: CounterProps) {
return (
<div id={props.id}>
<p>{props.count}</p>
<button
id={`b-${props.id}`}
onClick={() => props.count.value += 1}
disabled={!IS_BROWSER}
>
+1
</button>
</div>
);
}
+10
View File
@@ -0,0 +1,10 @@
/// <reference no-default-lib="true" />
/// <reference lib="dom" />
/// <reference lib="dom.iterable" />
/// <reference lib="dom.asynciterable" />
/// <reference lib="deno.ns" />
import { start } from "$fresh/server.ts";
import manifest from "./fresh.gen.ts";
await start(manifest, { router: { basePath: "/foo/bar" } });
@@ -0,0 +1,11 @@
import { MiddlewareHandlerContext } from "$fresh/server.ts";
export async function handler(
_req: Request,
ctx: MiddlewareHandlerContext<{ data: string }>,
) {
ctx.state.data = "it works";
const resp = await ctx.next();
resp.headers.set("server", "fresh server");
return resp;
}
+3
View File
@@ -0,0 +1,3 @@
export default function B() {
return <h1>it works</h1>;
}
@@ -0,0 +1,7 @@
export default function Relative() {
return (
<div>
<a href="b">baz/foo</a>
</div>
);
}
@@ -0,0 +1,9 @@
import { Handlers } from "$fresh/server.ts";
export const handler: Handlers<unknown, { data: string }> = {
GET(_req, ctx) {
return new Response(ctx.basePath, {
status: 200,
});
},
};
@@ -0,0 +1,7 @@
import { Handlers } from "$fresh/server.ts";
export const handler: Handlers<unknown, { data: string }> = {
GET(_req, ctx) {
return new Response(ctx.state.data);
},
};
@@ -0,0 +1,13 @@
import { Handlers } from "$fresh/server.ts";
export const handler: Handlers<unknown, { data: string }> = {
GET(req) {
const url = new URL(req.url);
return new Response(null, {
status: 302,
headers: {
"Location": url.origin,
},
});
},
};
@@ -0,0 +1,3 @@
export default function Other() {
return <h1>it works</h1>;
}
@@ -0,0 +1,4 @@
// deno-lint-ignore no-explicit-any
export default function Page(): any {
throw new Error("fail!!!");
}
@@ -0,0 +1,27 @@
import { Component } from "preact";
class ErrorBoundary extends Component {
state = { error: null } as { error: Error | null };
static getDerivedStateFromError(error: Error) {
return { error };
}
render() {
return this.state.error
? <p>{this.state.error.message}</p>
: <>{this.props.children}</>;
}
}
function Thrower(): preact.JSX.Element {
throw new Error("it works");
}
export default function ErrorBoundaryPage() {
return (
<ErrorBoundary>
<Thrower />
</ErrorBoundary>
);
}
+27
View File
@@ -0,0 +1,27 @@
import { Head } from "$fresh/runtime.ts";
export default function Page() {
return (
<>
<Head>
<link rel="stylesheet" href="/style.css" />
</Head>
<div>
<div id="script-output" />
<script src="/script.js"></script>
<img class="img" src="/img.png" alt="" />
<img
class="img-srcset"
src="/img.png"
srcset="/img.png 480w, /img.png 800w"
alt=""
/>
<picture>
<source srcset="/img.png" media="(min-width: 600px)" />
<img src="/img.png" alt="MDN" />
</picture>
<p class="foo">css style</p>
</div>
</>
);
}
+3
View File
@@ -0,0 +1,3 @@
export default function Home() {
return <h1>it works</h1>;
}
@@ -0,0 +1,10 @@
import { useSignal } from "@preact/signals";
import Counter from "../islands/Counter.tsx";
export default function Home() {
return (
<div>
<Counter id="counter1" count={useSignal(3)} />
</div>
);
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

+1
View File
@@ -0,0 +1 @@
document.querySelector("#script-output").textContent = "it works";
+3
View File
@@ -0,0 +1,3 @@
.foo {
color: red;
}
+3 -2
View File
@@ -235,7 +235,6 @@ export async function withPageName(
}
} finally {
serverProcess.kill("SIGTERM");
// Wait until the process exits
await serverProcess.status;
@@ -483,7 +482,9 @@ async function spawnServer(
// @ts-ignore yes it does
for await (const line of lines.values({ preventCancel: true })) {
output.push(line);
const match = line.match(/https?:\/\/localhost:\d+/g);
const match = line.match(
/https?:\/\/localhost:\d+(\/\w+[-\w]*)*/g,
);
if (match) {
address = match[0];
break;