chore: restructure repository into packages/ folder (#3197)

We're having a growing number of packages in this repository. This PR
moves them into a `packages/` directory like it's commonly done in other
projects.
This commit is contained in:
Marvin Hagemeister
2025-08-06 15:52:45 +02:00
committed by GitHub
parent 27e407a1e3
commit 815b1940e3
184 changed files with 94 additions and 82 deletions
+166
View File
@@ -0,0 +1,166 @@
import { App, staticFiles } from "fresh";
import {
ALL_ISLAND_DIR,
assertNotSelector,
assertSelector,
buildProd,
Doc,
parseHtml,
withBrowserApp,
} from "./test_utils.tsx";
import { FakeServer } from "../src/test_utils.ts";
import { Partial } from "fresh/runtime";
const allIslandCache = await buildProd({ islandDir: ALL_ISLAND_DIR });
function testApp<T>(): App<T> {
const app = new App<T>()
.use(staticFiles());
allIslandCache(app);
return app;
}
Deno.test({
name: "active links - without client nav",
fn: async () => {
function View() {
return (
<Doc>
<div>
<h1>nav</h1>
<p>
<a href="/active_nav/foo/bar">/active_nav/foo/bar</a>
</p>
<p>
<a href="/active_nav/foo">/active_nav/foo</a>
</p>
<p>
<a href="/active_nav">/active_nav</a>
</p>
<p>
<a href="/">/</a>
</p>
</div>
</Doc>
);
}
const app = testApp()
.get("/active_nav/foo", (ctx) => {
return ctx.render(<View />);
})
.get("/active_nav", (ctx) => {
return ctx.render(<View />);
});
const server = new FakeServer(app.handler());
let res = await server.get("/active_nav");
let doc = parseHtml(await res.text());
assertSelector(doc, "a[href='/'][data-ancestor]");
// Current
assertNotSelector(doc, "a[href='/active_nav'][data-ancestor]");
assertSelector(doc, "a[href='/active_nav'][data-current]");
assertSelector(doc, `a[href='/active_nav'][aria-current="page"]`);
// Unrelated links
assertNotSelector(doc, "a[href='/active_nav/foo'][data-ancestor]");
assertNotSelector(doc, "a[href='/active_nav/foo'][aria-current]");
assertNotSelector(doc, "a[href='/active_nav/foo/bar'][data-ancestor]");
assertNotSelector(doc, "a[href='/active_nav/foo/bar'][aria-current]");
res = await server.get(`/active_nav/foo`);
doc = parseHtml(await res.text());
assertSelector(doc, "a[href='/active_nav/foo'][data-current]");
assertSelector(doc, `a[href='/active_nav/foo'][aria-current="page"]`);
assertSelector(doc, "a[href='/active_nav'][data-ancestor]");
assertSelector(doc, `a[href='/active_nav'][aria-current="true"]`);
assertSelector(doc, "a[href='/'][data-ancestor]");
assertSelector(doc, `a[href='/'][aria-current="true"]`);
},
});
Deno.test({
name: "active links - updates outside of vdom",
fn: async () => {
function PartialPage() {
return (
<div>
<Partial name="content">
<h1>/active_nav_partial</h1>
</Partial>
<p>
<a href="/active_nav_partial/foo/bar">
/active_nav_partial/foo/bar
</a>
</p>
<p>
<a href="/active_nav_partial/foo">/active_nav_partial/foo</a>
</p>
<p>
<a href="/active_nav_partial">/active_nav_partial</a>
</p>
<p>
<a href="/">/</a>
</p>
</div>
);
}
const app = testApp()
.get("/active_nav_partial/foo", (ctx) => {
return ctx.render(<PartialPage />);
})
.get("/active_nav_partial", (ctx) => {
return ctx.render(<PartialPage />);
});
await withBrowserApp(app, async (page, address) => {
await page.goto(`${address}/active_nav_partial`);
let doc = parseHtml(await page.content());
assertSelector(doc, "a[href='/'][data-ancestor]");
// Current
assertNotSelector(doc, "a[href='/active_nav_partial'][data-ancestor]");
assertSelector(doc, "a[href='/active_nav_partial'][data-current]");
assertSelector(doc, `a[href='/active_nav_partial'][aria-current="page"]`);
// Unrelated links
assertNotSelector(
doc,
"a[href='/active_nav_partial/foo'][data-ancestor]",
);
assertNotSelector(
doc,
"a[href='/active_nav_partial/foo'][aria-current]",
);
assertNotSelector(
doc,
"a[href='/active_nav_partial/foo/bar'][data-ancestor]",
);
assertNotSelector(
doc,
"a[href='/active_nav_partial/foo/bar'][aria-current]",
);
await page.goto(`${address}/active_nav_partial/foo`);
doc = parseHtml(await page.content());
assertSelector(doc, "a[href='/active_nav_partial/foo'][data-current]");
assertSelector(
doc,
`a[href='/active_nav_partial/foo'][aria-current="page"]`,
);
assertSelector(doc, "a[href='/active_nav_partial'][data-ancestor]");
assertSelector(
doc,
`a[href='/active_nav_partial'][data-ancestor][aria-current="true"]`,
);
assertSelector(doc, "a[href='/'][data-ancestor]");
assertSelector(doc, `a[href='/'][aria-current="true"]`);
});
},
});
+118
View File
@@ -0,0 +1,118 @@
import twDenoJson from "../../plugin-tailwindcss/deno.json" with {
type: "json",
};
import * as Marked from "marked";
import { ensureDir, walk } from "@std/fs";
import { dirname, join, relative } from "@std/path";
// import { expect } from "@std/expect/expect";
import { withTmpDir } from "../src/test_utils.ts";
import { FRESH_VERSION, PREACT_VERSION } from "../../update/src/update.ts";
Deno.test("Docs Code example checks", async () => {
await using tmp = await withTmpDir();
for await (const { path, code } of docsMarkdownFiles()) {
const codePath = join(tmp.dir, path);
await ensureDir(dirname(codePath));
await Deno.writeTextFile(codePath, code);
}
const denoJson = {
lock: false,
imports: {
fresh: `jsr:@fresh/core@${FRESH_VERSION}`,
"@fresh/plugin-tailwind-v3":
`jsr:@fresh/plugin-tailwind@^${twDenoJson.version}`,
"@fresh/plugin-tailwind":
`jsr:@fresh/plugin-tailwind@^${twDenoJson.version}`,
preact: `npm:preact@^${PREACT_VERSION}`,
"@deno/gfm": "jsr:@deno/gfm@^0.11.0",
"@std/expect": "jsr:@std/expect@^1.0.16",
},
compilerOptions: {
lib: ["dom", "dom.asynciterable", "deno.ns", "deno.unstable"],
jsx: "precompile",
jsxImportSource: "preact",
jsxPrecompileSkipElements: ["a", "img", "source", "body", "html", "head"],
},
};
await Deno.writeTextFile(
join(tmp.dir, "deno.json"),
JSON.stringify(denoJson, undefined, 2),
);
// Download and cache all dependencies (reduces `stdout` noise)
await new Deno.Command(Deno.execPath(), {
args: ["cache", "**/*"],
cwd: tmp.dir,
}).output();
const { stdout, stderr } = await new Deno.Command(Deno.execPath(), {
args: ["check", "**/*"],
cwd: tmp.dir,
}).output();
const decoder = new TextDecoder();
const output = `${decoder.decode(stdout)}\n${decoder.decode(stderr)}`;
// Log `deno check` output (can be removed if expects below are enabled)
// deno-lint-ignore no-console
console.log(output);
// TODO: Enable after fixing docs check issues
// expect(code).toBe(0);
// expect(output).toBe("");
});
async function* docsMarkdownFiles() {
// Limit to checking Fresh v2 (canary) docs for now
const docsDir = join(
import.meta.dirname!,
"..",
"..",
"..",
"docs",
"canary",
);
const docsIter = walk(docsDir, { exts: [".md"], includeDirs: false });
for await (const entry of docsIter) {
for (const { file, code } of await extractTsCode(entry.path)) {
const path = join(relative(docsDir, entry.path), file);
yield { path, code };
}
}
}
async function extractTsCode(path: string) {
const code: { file: string; code: string }[] = [];
const input = await Deno.readTextFile(path);
let index = 0;
const tokens = await Marked.lexer(input, { gfm: true, async: true });
Marked.walkTokens(tokens, (token) => {
// Get rid of `Marked.Tokens.Generic`
const t = token as Marked.MarkedToken;
if (t.type !== "code") return;
const result = /^([tj]sx?)\s*/.exec(t.lang ?? "");
if (!result) return;
// Codeblock must be TS/JS
index += 1;
// Probably a filename, but perhaps a title,
// so get rid of non-file safe characters
const [match, ext] = result;
let file = t.lang!.slice(match.length)
.toLocaleLowerCase()
.replaceAll(/[^a-z0-9._\-\/\\]/g, "_")
.replaceAll(/_{2,}/g, "_") || String(index);
if (!file.endsWith(ext)) file += `.${ext}`;
code.push({ file, code: t.text });
});
return code;
}
@@ -0,0 +1,15 @@
import { useSignal } from "@preact/signals";
import { useEffect } from "preact/hooks";
export function Foo() {
const active = useSignal(false);
useEffect(() => {
active.value = true;
}, []);
return (
<div id="foo-both" class={active.value ? "ready" : ""}>
{active.value ? "it works" : "it doesn't work"}
</div>
);
}
@@ -0,0 +1,11 @@
import { Foo } from "./(_islands)/Foo.tsx";
import { Foo as Foo2 } from "../foo/(_islands)/Foo.tsx";
export default function Home() {
return (
<div>
<Foo />
<Foo2 />
</div>
);
}
@@ -0,0 +1,15 @@
import { useSignal } from "@preact/signals";
import { useEffect } from "preact/hooks";
export function Foo() {
const active = useSignal(false);
useEffect(() => {
active.value = true;
}, []);
return (
<div id="foo" class={active.value ? "ready" : ""}>
{active.value ? "it works" : "it doesn't work"}
</div>
);
}
@@ -0,0 +1,9 @@
import { Foo } from "./(_islands)/Foo.tsx";
export default function Home() {
return (
<div>
<Foo />
</div>
);
}
@@ -0,0 +1,3 @@
export default function Home() {
return <h1>hello world</h1>;
}
@@ -0,0 +1,9 @@
{
"workspace": [],
"lock": false,
"links": ["../../.."],
"compilerOptions": {
"jsx": "precompile",
"jsxImportSource": "preact"
}
}
@@ -0,0 +1,7 @@
import { Builder } from "../../../src/dev/mod.ts";
const builder = new Builder();
await builder.listen(() => import("./main.tsx"), {
port: 4001,
});
@@ -0,0 +1,6 @@
import { App } from "../../../src/app.ts";
export const app = new App().get(
"/",
() => new Response("hello"),
);
@@ -0,0 +1,10 @@
{
"workspace": [],
"lock": false,
"links": ["../../.."],
"compilerOptions": {
"jsx": "precompile",
"jsxImportSource": "preact",
"jsxPrecompileSkipElements": ["a", "img", "source", "body", "html", "head"]
}
}
@@ -0,0 +1,31 @@
import { App } from "../../../src/app.ts";
const app = new App().get(
"/",
(ctx) =>
ctx.render(
<html>
<head>
<meta charset="utf-8" />
<title>foo</title>
</head>
<body>
<div f-client-nav>
<span f-client-nav={false}>
<p>false</p>
</span>
<a href="/">Home</a>
<img src="/foo.jpg" alt="" />
<picture>
<source src="/bar.jpg" />
</picture>
</div>
</body>
</html>,
),
);
const handler = app.handler();
const res = await handler(new Request("http://localhost/"));
// deno-lint-ignore no-console
console.log(await res.text());
@@ -0,0 +1,21 @@
import { DAY } from "../../src/constants.ts";
import { updateCheck } from "../../src/dev/update_check.ts";
// deno-lint-ignore require-await
async function getLatestVersion() {
// deno-lint-ignore no-console
console.log("fetching latest version");
return Deno.env.get("LATEST_VERSION") ?? "99.99.999";
}
function getCurrentVersion() {
return Deno.env.get("CURRENT_VERSION")!;
}
const interval = +(Deno.env.get("UPDATE_INTERVAL") ?? DAY);
await updateCheck(
interval,
() => Deno.env.get("TEST_HOME")!,
getLatestVersion,
Deno.env.has("CURRENT_VERSION") ? getCurrentVersion : undefined,
);
@@ -0,0 +1,34 @@
import { useComputed, useSignal } from "@preact/signals";
import { useEffect } from "preact/hooks";
export function ComputedSignal(props: { id?: string }) {
const status = useSignal("it doesn't work");
const c = useComputed(() => 1);
const active = useSignal(false);
useEffect(() => {
active.value = true;
}, []);
return (
<div id={props.id} class={active.value ? "ready" : ""}>
<button
type="button"
class="trigger"
onClick={() => {
try {
// This should throw
// deno-lint-ignore no-explicit-any
(c as any).value = 10;
status.value = "it doesn't work";
} catch {
status.value = "it works";
}
}}
>
trigger
</button>
<p class="output">{status}</p>
</div>
);
}
@@ -0,0 +1,34 @@
import { type Signal, useSignal } from "@preact/signals";
import { useEffect } from "preact/hooks";
export interface CounterProps {
id?: string;
count: Signal<number>;
}
export function Counter(props: CounterProps) {
const active = useSignal(false);
useEffect(() => {
active.value = true;
}, []);
return (
<div id={props.id} class={active.value ? "ready" : ""}>
<button
type="button"
class="decrement"
onClick={() => props.count.value -= 1}
>
-1
</button>
<p class="output">{props.count}</p>
<button
type="button"
class="increment"
onClick={() => props.count.value += 1}
>
+1
</button>
</div>
);
}
@@ -0,0 +1,31 @@
import { useSignal } from "@preact/signals";
import { useEffect } from "preact/hooks";
import type { ComponentChildren } from "preact";
export function CounterWithSlots(
props: { children?: ComponentChildren; jsx?: ComponentChildren },
) {
const sig = useSignal(0);
const active = useSignal(false);
useEffect(() => {
active.value = true;
}, []);
return (
<div class={active.value ? "ready" : ""}>
<div class="counter-with-children">
<p class="output">{sig}</p>
<button type="button" onClick={() => sig.value = sig.peek() + 1}>
update
</button>
</div>
<div class="children">
{props.children}
</div>
<div class="jsx">
{props.jsx}
</div>
</div>
);
}
@@ -0,0 +1,17 @@
import { useEffect } from "preact/hooks";
import { useSignal } from "@preact/signals";
export function EscapeIsland(props: { str: string }) {
const active = useSignal(false);
useEffect(() => {
active.value = true;
}, []);
return (
<div class={active.value ? "ready" : ""}>
<p>it works</p>
<div>{props.str}</div>
</div>
);
}
@@ -0,0 +1,25 @@
import type { VNode } from "preact";
import { FragmentIsland } from "./FragmentIsland.tsx";
import { useEffect } from "preact/hooks";
import { useSignal } from "@preact/signals";
function Foo(props: { children: () => VNode }) {
return props.children();
}
export function FnIsland() {
const active = useSignal(false);
useEffect(() => {
active.value = true;
}, []);
return (
<div class={active.value ? "ready" : ""}>
<Foo>
{() => <FragmentIsland />}
</Foo>
</div>
);
}
@@ -0,0 +1,9 @@
// deno-lint-ignore-file jsx-curly-braces
export function FragmentIsland() {
return (
<>
<p>it{" "}</p>
<p>works</p>
</>
);
}
@@ -0,0 +1,23 @@
import { useSignal } from "@preact/signals";
import { useEffect } from "preact/hooks";
export interface FreshAttrs {
id?: string;
}
export function FreshAttrs(props: FreshAttrs) {
const active = useSignal(false);
useEffect(() => {
active.value = true;
}, []);
return (
<div id={props.id} class={active.value ? "ready" : ""}>
<h1>Fresh attrs</h1>
<div class="f-client-nav-true" f-client-nav>f-client-nav=true</div>
<div class="f-client-nav-false" f-client-nav={false}>
f-client-nav=false
</div>
</div>
);
}
@@ -0,0 +1,19 @@
import { useSignal } from "@preact/signals";
import { Counter } from "./Counter.tsx";
export function IslandInIsland() {
const sig = useSignal(0);
return (
<div>
<button
type="button"
class="trigger"
onClick={() => sig.value = sig.peek() + 1}
>
trigger
</button>
<Counter count={sig} />
</div>
);
}
@@ -0,0 +1,5 @@
import data from "./data.json" with { type: "json" };
export function JsonIsland() {
return <pre>{JSON.stringify(data)}</pre>;
}
@@ -0,0 +1,22 @@
import { useSignal } from "@preact/signals";
import { useEffect } from "preact/hooks";
import type { ComponentChildren } from "preact";
export interface JsxIslandProps {
children?: ComponentChildren;
}
export function JsxChildrenIsland(props: JsxIslandProps) {
const active = useSignal(false);
useEffect(() => {
active.value = true;
}, []);
return (
<div class={active.value ? "ready" : ""}>
<div class="children">{props.children}</div>
{active.value ? <div class="after">{props.children}</div> : null}
</div>
);
}
@@ -0,0 +1,32 @@
import { useSignal } from "@preact/signals";
import { useEffect } from "preact/hooks";
import type { ComponentChildren } from "preact";
export interface JsxConditionalProps {
jsx?: ComponentChildren;
children?: ComponentChildren;
}
export function JsxConditional(props: JsxConditionalProps) {
const active = useSignal(false);
const sig = useSignal(0);
useEffect(() => {
active.value = true;
}, []);
return (
<div class={active.value ? "ready" : ""}>
<p class="cond-output">{sig}</p>
<button
type="button"
class="cond-update"
onClick={() => sig.value = sig.peek() + 1}
>
update
</button>
<div class="jsx">{active.value ? props.jsx : null}</div>
<div class="children">{active.value ? props.children : null}</div>
</div>
);
}
@@ -0,0 +1,32 @@
import { useSignal } from "@preact/signals";
import { useEffect } from "preact/hooks";
import { type ComponentChildren, isValidElement } from "preact";
export interface JsxIslandProps {
jsx?: ComponentChildren;
children?: ComponentChildren;
}
export function JsxIsland(props: JsxIslandProps) {
const active = useSignal(false);
const sig = useSignal(0);
useEffect(() => {
active.value = true;
}, []);
return (
<div class={active.value ? "ready" : ""}>
<p class="output">{sig}</p>
<button
type="button"
class="update"
onClick={() => sig.value = sig.peek() + 1}
>
update
</button>
<div class="jsx">{props.jsx}</div>
<div class="children">{props.children}</div>
<pre>{JSON.stringify({jsx: isValidElement(props.jsx), children: isValidElement(props.children)})}</pre>
</div>
);
}
@@ -0,0 +1,17 @@
import type { ComponentChildren } from "preact";
import { Counter } from "./Counter.tsx";
import { useSignal } from "@preact/signals";
export interface MultipleProps {
id?: string;
children?: ComponentChildren;
}
export function Multiple1(props: MultipleProps) {
const sig = useSignal(0);
return <Counter id={props.id} count={sig} />;
}
export function Multiple2(props: MultipleProps) {
const sig = useSignal(0);
return <Counter id={props.id} count={sig} />;
}
@@ -0,0 +1,21 @@
import { useEffect } from "preact/hooks";
import { useSignal } from "@preact/signals";
import { IS_BROWSER } from "fresh/runtime";
export function NodeProcess() {
const active = useSignal(false);
useEffect(() => {
active.value = true;
}, []);
// @ts-ignore bundling
// deno-lint-ignore no-process-global
const value = IS_BROWSER ? process.env.NODE_ENV : "no";
return (
<div class={active.value ? "ready" : ""}>
value: {value}
</div>
);
}
@@ -0,0 +1,10 @@
import { useEffect } from "preact/hooks";
export function NullIsland() {
useEffect(() => {
const div = document.createElement("div");
div.className = "ready";
document.body.appendChild(div);
}, []);
return null;
}
@@ -0,0 +1,7 @@
export function OptOutPartialLink(props: { href: string; partial: string }) {
return (
<div f-client-nav={false}>
<a class="update" href={props.href} f-partial={props.partial}>link</a>
</div>
);
}
@@ -0,0 +1,9 @@
import { Partial } from "fresh/runtime";
export function PartialInIsland() {
return (
<Partial name="invalid">
<p class="invalid">invalid</p>
</Partial>
);
}
@@ -0,0 +1,9 @@
import type { ComponentChildren } from "preact";
export function PassThrough(props: { children?: ComponentChildren }) {
return (
<div class="passthrough">
{props.children}
</div>
);
}
@@ -0,0 +1,27 @@
import { useSignal } from "@preact/signals";
import { useEffect } from "preact/hooks";
export interface SelfCounterProps {
id?: string;
}
export function SelfCounter(props: SelfCounterProps) {
const count = useSignal(0);
const active = useSignal(false);
useEffect(() => {
active.value = true;
}, []);
return (
<div id={props.id} class={active.value ? "ready self-counter" : ""}>
<button type="button" class="decrement" onClick={() => count.value -= 1}>
-1
</button>
<p class="output">{count}</p>
<button type="button" class="increment" onClick={() => count.value += 1}>
+1
</button>
</div>
);
}
@@ -0,0 +1,3 @@
{
"foo": 123
}
+755
View File
@@ -0,0 +1,755 @@
import { App, staticFiles } from "fresh";
import { Counter } from "./fixtures_islands/Counter.tsx";
import { IslandInIsland } from "./fixtures_islands/IslandInIsland.tsx";
import { JsonIsland } from "./fixtures_islands/JsonIsland.tsx";
import { SelfCounter } from "./fixtures_islands/SelfCounter.tsx";
import { CounterWithSlots } from "./fixtures_islands/CounterWithSlots.tsx";
import { PassThrough } from "./fixtures_islands/PassThrough.tsx";
import { NullIsland } from "./fixtures_islands/NullIsland.tsx";
import { Multiple1, Multiple2 } from "./fixtures_islands/Multiple.tsx";
import { JsxIsland } from "./fixtures_islands/JsxIsland.tsx";
import { JsxChildrenIsland } from "./fixtures_islands/JsxChildrenIsland.tsx";
import { NodeProcess } from "./fixtures_islands/NodeProcess.tsx";
import { signal } from "@preact/signals";
import {
ALL_ISLAND_DIR,
buildProd,
Doc,
ISLAND_GROUP_DIR,
withBrowserApp,
} from "./test_utils.tsx";
import { parseHtml, waitForText } from "./test_utils.tsx";
import { expect } from "@std/expect";
import { JsxConditional } from "./fixtures_islands/JsxConditional.tsx";
import { FnIsland } from "./fixtures_islands/FnIsland.tsx";
import { EscapeIsland } from "./fixtures_islands/EscapeIsland.tsx";
import type { FreshConfig } from "../src/config.ts";
import { FreshAttrs } from "./fixtures_islands/FreshAttrs.tsx";
import { FakeServer } from "../src/test_utils.ts";
import { PARTIAL_SEARCH_PARAM } from "../src/constants.ts";
import { ComputedSignal } from "./fixtures_islands/Computed.tsx";
const allIslandCache = await buildProd({ islandDir: ALL_ISLAND_DIR });
const islandGroupCache = await buildProd({ root: ISLAND_GROUP_DIR });
function testApp(config?: FreshConfig): App<unknown> {
const app = new App(config)
.use(staticFiles())
.fsRoutes();
allIslandCache(app);
return app;
}
function testGroupApp(config?: FreshConfig): App<unknown> {
const app = new App(config)
.use(staticFiles())
.fsRoutes();
islandGroupCache(app);
return app;
}
Deno.test({
name: "islands - should make signals interactive",
fn: async () => {
const app = testApp()
.get("/", (ctx) => {
const sig = signal(3);
return ctx.render(
<Doc>
<Counter count={sig} />
</Doc>,
);
});
await withBrowserApp(app, async (page, address) => {
await page.goto(address, { waitUntil: "load" });
await page.locator(".ready").wait();
await page.locator(".increment").click();
await waitForText(page, ".output", "4");
});
},
});
Deno.test({
name: "islands - revive multiple islands from one island file",
fn: async () => {
const app = testApp()
.get("/", (ctx) => {
return ctx.render(
<Doc>
<Multiple1 id="multiple-1" />
<Multiple2 id="multiple-2" />
</Doc>,
);
});
await withBrowserApp(app, async (page, address) => {
await page.goto(address, { waitUntil: "load" });
await page.locator("#multiple-1.ready").wait();
await page.locator("#multiple-2.ready").wait();
await page.locator("#multiple-1 .increment").click();
await page.locator("#multiple-2 .increment").click();
await waitForText(page, "#multiple-1 .output", "1");
await waitForText(page, "#multiple-2 .output", "1");
});
},
});
Deno.test({
name: "islands - revive multiple islands with shared signal",
fn: async () => {
const app = testApp()
.get("/", (ctx) => {
const sig = signal(0);
return ctx.render(
<Doc>
<Counter id="counter-1" count={sig} />
<Counter id="counter-2" count={sig} />
</Doc>,
);
});
await withBrowserApp(app, async (page, address) => {
await page.goto(address, { waitUntil: "load" });
await page.locator("#counter-1.ready").wait();
await page.locator("#counter-2.ready").wait();
await page.locator("#counter-1 .increment").click();
await waitForText(page, "#counter-1 .output", "1");
await waitForText(page, "#counter-2 .output", "1");
});
},
});
Deno.test({
// Note that computed signals are detached because we cannot
// serialize the whole signal tree at the moment.
name: "islands - should serialize computed",
fn: async () => {
const app = testApp()
.get("/", (ctx) => {
return ctx.render(
<Doc>
<ComputedSignal id="comp" />
</Doc>,
);
});
await withBrowserApp(app, async (page, address) => {
await page.goto(address, { waitUntil: "load" });
await page.locator("#comp.ready").wait();
await page.locator("#comp .trigger").click();
await waitForText(page, "#comp .output", "it works");
});
},
});
Deno.test({
name: "islands - import json",
fn: async () => {
const app = testApp()
.get("/", (ctx) => {
return ctx.render(
<Doc>
<JsonIsland />
</Doc>,
);
});
await withBrowserApp(app, async (page, address) => {
await page.goto(address, { waitUntil: "load" });
await page.locator("pre").wait();
const text = await page
.locator<HTMLPreElement>("pre")
.evaluate((el) => el.textContent!);
const json = JSON.parse(text);
expect(json).toEqual({ foo: 123 });
});
},
});
Deno.test({
name: "islands - returns null",
fn: async () => {
const app = testApp()
.get("/", (ctx) => {
return ctx.render(
<Doc>
<NullIsland />
</Doc>,
);
});
await withBrowserApp(app, async (page, address) => {
await page.goto(address, { waitUntil: "load" });
await page.locator(".ready").wait();
});
},
});
Deno.test({
name: "islands - only instantiate top level island",
fn: async () => {
const app = testApp()
.get("/", (ctx) => {
return ctx.render(
<Doc>
<IslandInIsland />
</Doc>,
);
});
await withBrowserApp(app, async (page, address) => {
await page.goto(address, { waitUntil: "load" });
await page.locator(".ready").wait();
await page.locator(".trigger").click();
await waitForText(page, ".output", "1");
const html = await page.content();
expect(html).not.toContain("import { Counter }");
});
},
});
Deno.test({
name: "islands - pass null JSX props to islands",
fn: async () => {
const app = testApp()
.get("/", (ctx) => {
return ctx.render(
<Doc>
<JsxIsland jsx={null}>{null}</JsxIsland>
</Doc>,
);
});
await withBrowserApp(app, async (page, address) => {
await page.goto(address, { waitUntil: "load" });
await page.locator(".ready").wait();
const html = await page.content();
const doc = parseHtml(html);
expect(doc.querySelector(".jsx")!.childNodes.length).toEqual(0);
expect(doc.querySelector(".children")!.childNodes.length).toEqual(0);
});
},
});
Deno.test({
name: "islands - pass JSX props to islands",
fn: async () => {
const app = testApp()
.get("/", (ctx) => {
return ctx.render(
<Doc>
<JsxIsland jsx={<p>foo</p>}>
<p>bar</p>
</JsxIsland>
</Doc>,
);
});
await withBrowserApp(app, async (page, address) => {
await page.goto(address, { waitUntil: "load" });
await page.locator(".ready").wait();
const text = await page
.locator<HTMLPreElement>("pre")
.evaluate((el) => el.textContent!);
expect(JSON.parse(text)).toEqual({ jsx: true, children: true });
});
},
});
Deno.test({
name: "islands - never serialize children prop",
fn: async () => {
const app = testApp()
.get("/", (ctx) => {
return ctx.render(
<Doc>
<JsxChildrenIsland>
foobar
</JsxChildrenIsland>
</Doc>,
);
});
await withBrowserApp(app, async (page, address) => {
await page.goto(address, { waitUntil: "load" });
await page.locator(".ready").wait();
const text = await page
.locator<HTMLScriptElement>("script")
.evaluate((el) => el.textContent!);
expect(text).not.toContain("foobar");
const childText = await page
.locator<HTMLDivElement>(".after")
.evaluate((el) => el.textContent!);
expect(childText).toEqual("foobar");
});
},
});
Deno.test({
name: "islands - instantiate islands in jsx children",
fn: async () => {
const app = testApp()
.get("/", (ctx) => {
return ctx.render(
<Doc>
<PassThrough>
<div>
<SelfCounter />
</div>
</PassThrough>
</Doc>,
);
});
await withBrowserApp(app, async (page, address) => {
await page.goto(address, { waitUntil: "load" });
await page.locator(".ready").wait();
await page.locator(".increment").click();
await waitForText(page, ".output", "1");
});
},
});
Deno.test({
name: "islands - instantiate islands in jsx children with slots",
fn: async () => {
const app = testApp()
.get("/", (ctx) => {
return ctx.render(
<Doc>
<CounterWithSlots
jsx={
<div>
<SelfCounter />
</div>
}
>
<div>
<SelfCounter />
</div>
</CounterWithSlots>
</Doc>,
);
});
await withBrowserApp(app, async (page, address) => {
await page.goto(address, { waitUntil: "load" });
await page.locator(".ready").wait();
await page.locator(".jsx .increment").click();
await page.locator(".children .increment").click();
await page.locator(".counter-with-children button").click();
await waitForText(page, ".counter-with-children .output", "1");
await waitForText(page, ".jsx .output", "1");
await waitForText(page, ".children .output", "1");
});
},
});
Deno.test({
name: "islands - nested children slots",
fn: async () => {
const app = testApp()
.get("/", (ctx) => {
return ctx.render(
<Doc>
<PassThrough>
<PassThrough>
<div>
<SelfCounter id="a" />
</div>
</PassThrough>
<PassThrough>
<div>
<SelfCounter id="b" />
</div>
</PassThrough>
</PassThrough>
</Doc>,
);
});
await withBrowserApp(app, async (page, address) => {
await page.goto(address, { waitUntil: "load" });
await page.locator(".ready").wait();
await page.locator("#a .increment").click();
await page.locator("#b .increment").click();
await waitForText(page, "#a .output", "1");
await waitForText(page, "#b .output", "1");
});
},
});
Deno.test({
name: "islands - conditional jsx children",
fn: async () => {
const app = testApp()
.get("/", (ctx) => {
return ctx.render(
<Doc>
<JsxConditional
jsx={
<div>
<SelfCounter />
</div>
}
>
<div>
<SelfCounter />
</div>
</JsxConditional>
</Doc>,
);
});
await withBrowserApp(app, async (page, address) => {
await page.goto(address, { waitUntil: "load" });
await page.locator(".ready").wait();
await page.locator(".jsx .increment").click();
await page.locator(".children .increment").click();
await page.locator(".cond-update").click();
await waitForText(page, ".cond-output", "1");
await waitForText(page, ".jsx .output", "1");
await waitForText(page, ".children .output", "1");
});
},
});
Deno.test({
name: "islands - revive DOM attributes",
fn: async () => {
const app = testApp()
.get("/", (ctx) => {
return ctx.render(
<Doc>
<JsxConditional>
<div class="foo">
<form>
<label for="check">
checked
</label>
<input name="check" type="checkbox" checked />
<label for="text">
is required
</label>
<input name="text" type="text" required />
<label for="foo-1">
not selected
</label>
<input id="foo-1" type="radio" name="foo" value="1" />
<label for="foo-2">
selected
</label>
<input id="foo-2" type="radio" name="foo" value="2" checked />
<label for="select">
select value should be "bar"
</label>
<select name="select">
<option value="foo">foo</option>
<option value="bar" selected>bar</option>
</select>
</form>
<SelfCounter />
</div>
</JsxConditional>
</Doc>,
);
});
await withBrowserApp(app, async (page, address) => {
await page.goto(address, { waitUntil: "load" });
await page.locator(".ready").wait();
await page.locator(".children > .foo").wait();
const checkboxChecked = await page
.locator<HTMLInputElement>("input[name='check']")
.evaluate((el) => el.checked);
expect(checkboxChecked).toEqual(true);
const required = await page
.locator<HTMLInputElement>("input[name='text']")
.evaluate((el) => el.required);
expect(required).toEqual(true);
const radio1 = await page
.locator<HTMLInputElement>("input[type='radio'][value='1']")
.evaluate((el) => el.checked);
expect(radio1).toEqual(false);
const radio2 = await page
.locator<HTMLInputElement>("input[type='radio'][value='2']")
.evaluate((el) => el.checked);
expect(radio2).toEqual(true);
});
},
});
Deno.test({
name: "islands - revive island with fn inside",
fn: async () => {
const app = testApp()
.get("/", (ctx) => {
return ctx.render(
<Doc>
<FnIsland />
</Doc>,
);
});
await withBrowserApp(app, async (page, address) => {
await page.goto(address, { waitUntil: "load" });
await page.locator(".ready").wait();
const text = await page
.locator<HTMLDivElement>(".ready")
.evaluate((el) => el.textContent!);
expect(text).toEqual("it works");
});
},
});
Deno.test({
name: "islands - escape props",
fn: async () => {
const app = testApp()
.get("/", (ctx) => {
return ctx.render(
<Doc>
<EscapeIsland str={`"foo"asdf`} />
</Doc>,
);
})
.get("/foo", (ctx) => {
return ctx.render(
<Doc>
<EscapeIsland str={`<script>alert('hey')</script>`} />
</Doc>,
);
})
.get("/bar", (ctx) => {
return ctx.render(
<Doc>
<EscapeIsland str={`<!--<script>alert('hey')</script>`} />
</Doc>,
);
});
await withBrowserApp(app, async (page, address) => {
await page.goto(address, { waitUntil: "load" });
await page.locator(".ready").wait();
// Page would error here
const text = await page
.locator<HTMLDivElement>(".ready p")
.evaluate((el) => el.textContent!);
expect(text).toEqual("it works");
// Page would error here
const text2 = await page
.locator<HTMLDivElement>(".ready div")
.evaluate((el) => el.textContent!);
expect(text2).toEqual(`"foo"asdf`);
});
// Check escaping of `</`
await withBrowserApp(app, async (page, address) => {
await page.goto(`${address}/foo`, { waitUntil: "load" });
await page.locator(".ready").wait();
const text = await page
.locator<HTMLDivElement>(".ready p")
.evaluate((el) => el.textContent!);
expect(text).toEqual("it works");
const text2 = await page
.locator<HTMLDivElement>(".ready div")
.evaluate((el) => el.textContent!);
expect(text2).toEqual(`<script>alert('hey')</script>`);
});
// Check escaping of `<!--`
await withBrowserApp(app, async (page, address) => {
await page.goto(`${address}/bar`, { waitUntil: "load" });
await page.locator(".ready").wait();
const text = await page
.locator<HTMLDivElement>(".ready p")
.evaluate((el) => el.textContent!);
expect(text).toEqual("it works");
const text2 = await page
.locator<HTMLDivElement>(".ready div")
.evaluate((el) => el.textContent!);
expect(text2).toEqual(`<!--<script>alert('hey')</script>`);
});
// Partials (they use a different code path)
await withBrowserApp(app, async (page, address) => {
await page.goto(`${address}/foo?${PARTIAL_SEARCH_PARAM}`, {
waitUntil: "load",
});
const text = await page
.locator<HTMLScriptElement>("script[type='application/json']")
.evaluate((el) => el.textContent!);
const json = JSON.parse(text);
expect(json.props).toContain("<script>alert('hey')</script>");
});
},
});
Deno.test({
name: "islands - stub Node 'process.env'",
fn: async () => {
const app = testApp()
.get("/", (ctx) =>
ctx.render(
<Doc>
<NodeProcess />
</Doc>,
));
await withBrowserApp(app, async (page, address) => {
await page.goto(`${address}/`, { waitUntil: "load" });
await page.locator(".ready").wait();
// Page would error here
const text = await page
.locator<HTMLDivElement>(".ready")
.evaluate((el) => el.textContent!);
expect(text).toEqual("value: production");
});
},
});
Deno.test({
name: "islands - in base path",
fn: async () => {
const app = testApp({ basePath: "/foo" })
.get("/", (ctx) =>
ctx.render(
<Doc>
<SelfCounter />
</Doc>,
));
await withBrowserApp(app, async (page, address) => {
await page.goto(`${address}/foo`, { waitUntil: "load" });
await page.locator(".ready").wait();
await page.locator(".increment").click();
await waitForText(page, ".output", "1");
});
},
});
Deno.test({
name: "islands - preserve f-* attributes",
fn: async () => {
const app = testApp()
.get("/", (ctx) =>
ctx.render(
<Doc>
<FreshAttrs />
</Doc>,
));
await withBrowserApp(app, async (page, address) => {
await page.goto(address, { waitUntil: "load" });
await page.locator(".ready").wait();
const truthy = await page.locator<HTMLDivElement>(".f-client-nav-true")
.evaluate((el) => el.getAttribute("f-client-nav"));
const falsy = await page.locator<HTMLDivElement>(".f-client-nav-false")
.evaluate((el) => el.getAttribute("f-client-nav"));
expect(truthy).toEqual("true");
expect(falsy).toEqual("false");
});
},
});
Deno.test({
name: "fsRoutes - load islands from group folder",
fn: async () => {
const app = testGroupApp();
await withBrowserApp(app, async (page, address) => {
await page.goto(`${address}/foo`, { waitUntil: "load" });
await page.locator(".ready").wait();
// Page would error here
const text = await page
.locator<HTMLDivElement>(".ready")
.evaluate((el) => el.textContent!);
expect(text).toEqual("it works");
});
},
});
Deno.test({
name: "fsRoutes - load islands from group folder with same name",
fn: async () => {
const app = testGroupApp();
await withBrowserApp(app, async (page, address) => {
await page.goto(`${address}/both`, { waitUntil: "load" });
await page.locator(".ready").wait();
// Page would error here
let text = await page
.locator<HTMLDivElement>("#foo.ready")
.evaluate((el) => el.textContent!);
expect(text).toEqual("it works");
text = await page
.locator<HTMLDivElement>("#foo-both.ready")
.evaluate((el) => el.textContent!);
expect(text).toEqual("it works");
});
},
});
Deno.test({
name: "islands - adds preload HTTP headers",
fn: async () => {
const app = testApp()
.get("/", (ctx) =>
ctx.render(
<Doc>
<SelfCounter />
</Doc>,
));
const server = new FakeServer(app.handler());
const res = await server.get("/");
await res.body?.cancel();
const link = res.headers.get("Link");
expect(link).toMatch(
/<\/_fresh\/js\/[a-zA-Z0-9]+\/fresh-runtime\.js>; rel="modulepreload"; as="script", <\/_fresh\/js\/[a-zA-Z0-9]+\/SelfCounter\.js>; rel="modulepreload"; as="script"/,
);
},
});
+24
View File
@@ -0,0 +1,24 @@
Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Aenean commodo ligula eget dolor. Aenean massa. Cum sociis
natoque penatibus et magnis dis parturient montes, nascetur
ridiculus mus. Donec quam felis, ultricies nec, pellentesque
eu, pretium quis, sem. Nulla consequat massa quis enim.
Donec pede justo, fringilla vel, aliquet nec, vulputate
eget, arcu. In enim justo, rhoncus ut, imperdiet a,
venenatis vitae, justo. Nullam dictum felis eu pede mollis
pretium. Integer tincidunt. Cras dapibus. Vivamus elementum
semper nisi. Aenean vulputate eleifend tellus. Aenean leo
ligula, porttitor eu, consequat vitae, eleifend ac, enim.
Aliquam lorem ante, dapibus in, viverra quis, feugiat a,
tellus. Phasellus viverra nulla ut metus varius laoreet.
Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel
augue. Curabitur ullamcorper ultricies nisi. Nam eget dui.
Etiam rhoncus. Maecenas tempus, tellus eget condimentum
rhoncus, sem quam semper libero, sit amet adipiscing sem
neque sed ipsum. Nam quam nunc, blandit vel, luctus
pulvinar, hendrerit id, lorem. Maecenas nec odio et ante
tincidunt tempus. Donec vitae sapien ut libero venenatis
faucibus. Nullam quis ante. Etiam sit amet orci eget eros
faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet
nibh. Donec sodales sagittis magna. Sed consequat, leo eget
bibendum sodales, augue velit cursus nunc,
File diff suppressed because it is too large Load Diff
+26
View File
@@ -0,0 +1,26 @@
import { expect } from "@std/expect";
Deno.test("JSX precompile - check config", async () => {
const { stderr, success } = await new Deno.Command(Deno.execPath(), {
args: ["run", "-A", "dev.ts"],
cwd: new URL("./fixture_precompile/invalid", import.meta.url),
}).output();
const stderrText = new TextDecoder().decode(stderr);
expect(stderrText).toContain("jsxPrecompileSkipElements to contain");
expect(success).toEqual(false);
});
Deno.test("JSX precompile - run vnode hooks", async () => {
const { stdout, success } = await new Deno.Command(Deno.execPath(), {
args: ["run", "-A", "main.tsx"],
cwd: new URL("./fixture_precompile/valid", import.meta.url),
}).output();
const stdoutText = new TextDecoder().decode(stdout);
expect(stdoutText).toContain('<img src="/foo.jpg?__frsh_c=');
expect(stdoutText).toContain('<source src="/bar.jpg?__frsh_c=');
expect(stdoutText).toContain('<div f-client-nav="true">');
expect(stdoutText).toContain('<span f-client-nav="false">');
expect(success).toEqual(true);
});
+362
View File
@@ -0,0 +1,362 @@
import type { App } from "../src/app.ts";
import { launch, type Page } from "@astral/astral";
import * as colors from "@std/fmt/colors";
import { DOMParser, HTMLElement } from "linkedom";
import { Builder, type BuildOptions } from "../src/dev/builder.ts";
import { TextLineStream } from "@std/streams/text-line-stream";
import * as path from "@std/path";
import type { ComponentChildren } from "preact";
import { expect } from "@std/expect";
import { mergeReadableStreams } from "@std/streams";
const browser = await launch({
args: [
"--window-size=1280,720",
...((Deno.env.get("CI") && Deno.build.os === "linux")
? ["--no-sandbox"]
: []),
],
headless: Deno.env.get("HEADLESS") !== "false",
});
export const charset = <meta charset="utf-8" />;
export const favicon = (
<link
href="data:image/x-icon;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQEAYAAABPYyMiAAAABmJLR0T///////8JWPfcAAAACXBIWXMAAABIAAAASABGyWs+AAAAF0lEQVRIx2NgGAWjYBSMglEwCkbBSAcACBAAAeaR9cIAAAAASUVORK5CYII="
rel="icon"
type="image/x-icon"
/>
);
export function Doc(props: { children?: ComponentChildren; title?: string }) {
return (
<html>
<head>
{charset}
<title>{props.title ?? "Test"}</title>
{favicon}
</head>
<body>
{props.children}
</body>
</html>
);
}
export const ALL_ISLAND_DIR = path.join(
import.meta.dirname!,
"fixtures_islands",
);
export const ISLAND_GROUP_DIR = path.join(
import.meta.dirname!,
"fixture_island_groups",
);
export async function buildProd(
options: Omit<BuildOptions, "outDir">,
): Promise<<T>(app: App<T>) => void> {
const outDir = await Deno.makeTempDir();
const builder = new Builder({ outDir, ...options });
return await builder.build({ mode: "production", snapshot: "memory" });
}
export async function withBrowserApp(
app: App<unknown>,
fn: (page: Page, address: string) => void | Promise<void>,
) {
const aborter = new AbortController();
await using server = Deno.serve({
hostname: "localhost",
port: 0,
signal: aborter.signal,
onListen: () => {}, // Don't spam terminal with "Listening on..."
}, app.handler());
try {
await using page = await browser.newPage();
await fn(page, `http://localhost:${server.addr.port}`);
} finally {
aborter.abort();
}
}
export async function withBrowser(fn: (page: Page) => void | Promise<void>) {
await using page = await browser.newPage();
try {
await fn(page);
} catch (err) {
const raw = await page.content();
const doc = parseHtml(raw);
const html = prettyDom(doc);
// deno-lint-ignore no-console
console.log(html);
throw err;
}
}
export async function withChildProcessServer(
options: {
cwd: string;
args: string[];
bin?: string;
env?: Record<string, string>;
},
fn: (address: string) => void | Promise<void>,
) {
const aborter = new AbortController();
const cp = await new Deno.Command(options.bin ?? Deno.execPath(), {
args: options.args,
stdin: "null",
stdout: "piped",
stderr: "piped",
cwd: options.cwd,
signal: aborter.signal,
env: options.env,
}).spawn();
const linesStdout: ReadableStream<string> = cp.stdout
.pipeThrough(new TextDecoderStream())
.pipeThrough(new TextLineStream());
const linesStderr: ReadableStream<string> = cp.stderr
.pipeThrough(new TextDecoderStream())
.pipeThrough(new TextLineStream());
const lines = mergeReadableStreams(linesStdout, linesStderr);
const output: string[] = [];
let address = "";
let found = false;
// @ts-ignore yes it does
for await (const raw of lines.values({ preventCancel: true })) {
const line = colors.stripAnsiCode(raw);
output.push(line);
const match = line.match(
/https?:\/\/[^:]+:\d+(\/\w+[-\w]*)*/g,
);
if (match) {
address = match[0];
found = true;
break;
}
}
if (!found) {
// deno-lint-ignore no-console
console.log(output);
throw new Error(`Could not find server address`);
}
let failed = false;
try {
await fn(address);
} catch (err) {
// deno-lint-ignore no-console
console.log(output);
failed = true;
throw err;
} finally {
aborter.abort();
await cp.status;
for await (const line of lines) {
output.push(line);
}
if (failed) {
// deno-lint-ignore no-console
console.log(output);
}
}
}
export const VOID_ELEMENTS =
/^(?:area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)$/;
function prettyDom(doc: Document) {
let out = colors.dim(`<!DOCTYPE ${doc.doctype?.name ?? ""}>\n`);
const node = doc.documentElement;
out += _printDomNode(node, 0);
return out;
}
function _printDomNode(
node: HTMLElement | Text | Node,
indent: number,
) {
const space = " ".repeat(indent);
if (node.nodeType === 3) {
return space + colors.dim(node.textContent ?? "") + "\n";
} else if (node.nodeType === 8) {
return space + colors.dim(`<--${(node as Text).data}-->`) + "\n";
}
let out = space;
if (node instanceof HTMLElement || node instanceof HTMLMetaElement) {
out += colors.dim(colors.cyan("<"));
out += colors.cyan(node.localName);
for (let i = 0; i < node.attributes.length; i++) {
const attr = node.attributes.item(i);
if (attr === null) continue;
out += " " + colors.yellow(attr.name);
out += colors.dim("=");
out += colors.green(`"${attr.value}"`);
}
if (VOID_ELEMENTS.test(node.localName)) {
out += colors.dim(colors.cyan(">")) + "\n";
return out;
}
out += colors.dim(colors.cyan(">"));
if (node.childNodes.length) {
out += "\n";
for (let i = 0; i < node.childNodes.length; i++) {
const child = node.childNodes[i];
out += _printDomNode(child, indent + 1);
}
out += space;
}
out += colors.dim(colors.cyan("</"));
out += colors.cyan(node.localName);
out += colors.dim(colors.cyan(">"));
out += "\n";
}
return out;
}
export interface TestDocument extends Document {
debug(): void;
}
export function parseHtml(input: string): TestDocument {
// deno-lint-ignore no-explicit-any
const doc = new DOMParser().parseFromString(input, "text/html") as any;
Object.defineProperty(doc, "debug", {
// deno-lint-ignore no-console
value: () => console.log(prettyDom(doc)),
enumerable: false,
});
return doc;
}
export function assertSelector(doc: Document, selector: string) {
if (doc.querySelector(selector) === null) {
const html = prettyDom(doc);
throw new Error(
`Selector "${selector}" not found in document.\n\n${html}`,
);
}
}
export function assertNotSelector(doc: Document, selector: string) {
if (doc.querySelector(selector) !== null) {
const html = prettyDom(doc);
throw new Error(
`Selector "${selector}" found in document.\n\n${html}`,
);
}
}
export function assertMetaContent(
doc: Document,
nameOrProperty: string,
expected: string,
) {
let el = doc.querySelector(`meta[name="${nameOrProperty}"]`) as
| HTMLMetaElement
| null;
if (el === null) {
el = doc.querySelector(`meta[property="${nameOrProperty}"]`) as
| HTMLMetaElement
| null;
}
if (el === null) {
// deno-lint-ignore no-console
console.log(prettyDom(doc));
throw new Error(
`No <meta>-tag found with content "${expected}"`,
);
}
expect(el.content).toEqual(expected);
}
export async function waitForText(
page: Page,
selector: string,
text: string,
) {
await page.waitForSelector(selector);
try {
await page.waitForFunction(
(sel: string, value: string) => {
const el = document.querySelector(sel);
if (el === null) return false;
return el.textContent === value;
},
{ args: [selector, String(text)] },
);
} catch (err) {
const body = await page.content();
// deno-lint-ignore no-explicit-any
const pretty = prettyDom(parseHtml(body) as any);
// deno-lint-ignore no-console
console.log(
`Text "${text}" not found on selector "${selector}" in html:\n\n${pretty}`,
);
throw err;
}
}
export async function waitFor(
fn: () => Promise<unknown> | unknown,
): Promise<void> {
let now = Date.now();
const limit = now + 2000;
while (now < limit) {
try {
if (await fn()) return;
} catch (err) {
if (now > limit) {
throw err;
}
} finally {
await new Promise((r) => setTimeout(r, 250));
now = Date.now();
}
}
throw new Error(`Timed out`);
}
export function getStdOutput(
out: Deno.CommandOutput,
): { stdout: string; stderr: string } {
const decoder = new TextDecoder();
const stdout = colors.stripAnsiCode(decoder.decode(out.stdout));
const decoderErr = new TextDecoder();
const stderr = colors.stripAnsiCode(decoderErr.decode(out.stderr));
return { stdout, stderr };
}
const ISLAND_FIXTURE_DIR = path.join(import.meta.dirname!, "fixtures_islands");
const allIslandBuilder = new Builder({});
for await (const entry of Deno.readDirSync(ISLAND_FIXTURE_DIR)) {
if (entry.name.endsWith(".json")) continue;
const spec = path.join(ISLAND_FIXTURE_DIR, entry.name);
allIslandBuilder.registerIsland(spec);
}