diff --git a/src/build/deps.ts b/src/build/deps.ts index 7a3996ca..2e2c9c22 100644 --- a/src/build/deps.ts +++ b/src/build/deps.ts @@ -10,10 +10,11 @@ export { escape as regexpEscape } from "https://deno.land/std@0.193.0/regexp/esc import * as esbuildWasm from "https://deno.land/x/esbuild@v0.19.4/wasm.js"; import * as esbuildNative from "https://deno.land/x/esbuild@v0.19.4/mod.js"; // @ts-ignore trust me -// deno-lint-ignore no-deprecated-deno-api -const esbuild: typeof esbuildWasm = Deno.run === undefined - ? esbuildWasm - : esbuildNative; +const esbuild: typeof esbuildWasm = + // deno-lint-ignore no-deprecated-deno-api + Deno.run === undefined || Deno.env.get("FRESH_ESBUILD_LOADER") === "portable" + ? esbuildWasm + : esbuildNative; const esbuildWasmURL = new URL("./esbuild_v0.19.4.wasm", import.meta.url).href; export { esbuild, esbuildWasm as esbuildTypes, esbuildWasmURL }; diff --git a/src/runtime/client.ts b/src/runtime/entrypoints/client.ts similarity index 100% rename from src/runtime/client.ts rename to src/runtime/entrypoints/client.ts diff --git a/src/runtime/entrypoints/main_dev.ts b/src/runtime/entrypoints/main_dev.ts index 4fe0bdb9..4e4f0c56 100644 --- a/src/runtime/entrypoints/main_dev.ts +++ b/src/runtime/entrypoints/main_dev.ts @@ -1,3 +1,2 @@ import "preact/debug"; -import "../client.ts"; export * from "./main.ts"; diff --git a/src/server/constants.ts b/src/server/constants.ts index 648594de..b0810924 100644 --- a/src/server/constants.ts +++ b/src/server/constants.ts @@ -1,6 +1,7 @@ import { INTERNAL_PREFIX } from "../runtime/utils.ts"; import { BUILD_ID } from "./build_id.ts"; +export const DEV_CLIENT_URL = `${INTERNAL_PREFIX}/fresh_dev_client.js`; export const ALIVE_URL = `${INTERNAL_PREFIX}/alive`; export const JS_PREFIX = `/js`; export const DEBUG = !Deno.env.get("DENO_DEPLOYMENT_ID"); diff --git a/src/server/context.ts b/src/server/context.ts index 27eb3ff4..36288b28 100644 --- a/src/server/context.ts +++ b/src/server/context.ts @@ -10,7 +10,7 @@ import { import { ComponentType, h } from "preact"; import * as router from "./router.ts"; import { FreshConfig, Manifest } from "./mod.ts"; -import { ALIVE_URL, JS_PREFIX } from "./constants.ts"; +import { ALIVE_URL, DEV_CLIENT_URL, JS_PREFIX } from "./constants.ts"; import { BUILD_ID, setBuildId } from "./build_id.ts"; import DefaultErrorHandler from "./default_error_page.tsx"; import { @@ -490,6 +490,7 @@ export class ServerContext { ); const trailingSlashEnabled = this.#routerOptions?.trailingSlash; const isDev = this.#dev; + const bundleAssetRoute = this.#bundleAssetRoute(); return async function handler( req: Request, @@ -497,20 +498,24 @@ export class ServerContext { ) { const url = new URL(req.url); - // Live reload: Send updates to browser - if (isDev && url.pathname === ALIVE_URL) { - if (req.headers.get("upgrade") !== "websocket") { - return new Response(null, { status: 501 }); + if (isDev) { + // Live reload: Send updates to browser + if (url.pathname === ALIVE_URL) { + 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 } = Deno.upgradeWebSocket(req); + + return response; + } else if (url.pathname === DEV_CLIENT_URL) { + return bundleAssetRoute(req, connInfo, { path: "client.js" }); } - - // 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 } = Deno.upgradeWebSocket(req); - - return response; } // Redirect requests that end with a trailing slash to their non-trailing @@ -771,6 +776,7 @@ export class ServerContext { status: number, ) => { const imports: string[] = []; + if (this.#dev) imports.push(DEV_CLIENT_URL); return ( req: Request, params: Record, @@ -1296,6 +1302,7 @@ function collectEntrypoints( ? import.meta.resolve(`${entrypointBase}/main_dev.ts`) : import.meta.resolve(`${entrypointBase}/main.ts`), deserializer: import.meta.resolve(`${entrypointBase}/deserializer.ts`), + client: import.meta.resolve(`${entrypointBase}/client.ts`), }; try { diff --git a/tests/deps.ts b/tests/deps.ts index 360beb29..dbfaec7f 100644 --- a/tests/deps.ts +++ b/tests/deps.ts @@ -37,4 +37,5 @@ export { dirname, fromFileUrl, join, + relative, } from "https://deno.land/std@0.193.0/path/mod.ts"; diff --git a/tests/fixture_hmr/deno.json b/tests/fixture_hmr/deno.json new file mode 100644 index 00000000..2b73c679 --- /dev/null +++ b/tests/fixture_hmr/deno.json @@ -0,0 +1,15 @@ +{ + "lock": false, + "imports": { + "$fresh/": "../../", + "preact": "https://esm.sh/preact@10.15.1", + "preact/": "https://esm.sh/preact@10.15.1/", + "preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.2.1", + "@preact/signals": "https://esm.sh/*@preact/signals@1.1.5", + "@preact/signals-core": "https://esm.sh/@preact/signals-core@1.3.1" + }, + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "preact" + } +} diff --git a/tests/fixture_hmr/dev.ts b/tests/fixture_hmr/dev.ts new file mode 100755 index 00000000..2d85d6c1 --- /dev/null +++ b/tests/fixture_hmr/dev.ts @@ -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"); diff --git a/tests/fixture_hmr/fresh.gen.ts b/tests/fixture_hmr/fresh.gen.ts new file mode 100644 index 00000000..23d6ef79 --- /dev/null +++ b/tests/fixture_hmr/fresh.gen.ts @@ -0,0 +1,22 @@ +// 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 $0 from "./routes/index.tsx"; +import * as $1 from "./routes/island.tsx"; +import * as $2 from "./routes/no_island.tsx"; +import * as $$0 from "./islands/Counter.tsx"; + +const manifest = { + routes: { + "./routes/index.tsx": $0, + "./routes/island.tsx": $1, + "./routes/no_island.tsx": $2, + }, + islands: { + "./islands/Counter.tsx": $$0, + }, + baseUrl: import.meta.url, +}; + +export default manifest; diff --git a/tests/fixture_hmr/islands/Counter.tsx b/tests/fixture_hmr/islands/Counter.tsx new file mode 100644 index 00000000..9e3f9244 --- /dev/null +++ b/tests/fixture_hmr/islands/Counter.tsx @@ -0,0 +1,12 @@ +import { useSignal } from "@preact/signals"; + +export default function Counter() { + const sig = useSignal(0); + + return ( +
+

{sig}

+ +
+ ); +} diff --git a/tests/fixture_hmr/main.ts b/tests/fixture_hmr/main.ts new file mode 100644 index 00000000..dedce9cb --- /dev/null +++ b/tests/fixture_hmr/main.ts @@ -0,0 +1,10 @@ +/// +/// +/// +/// +/// + +import { start } from "$fresh/server.ts"; +import manifest from "./fresh.gen.ts"; + +await start(manifest); diff --git a/tests/fixture_hmr/routes/index.tsx b/tests/fixture_hmr/routes/index.tsx new file mode 100644 index 00000000..9c432289 --- /dev/null +++ b/tests/fixture_hmr/routes/index.tsx @@ -0,0 +1,27 @@ +import * as path from "https://deno.land/std@0.192.0/path/mod.ts"; + +const __dirname = path.dirname(path.fromFileUrl(import.meta.url)); + +const links: string[] = []; +for (const file of Deno.readDirSync(__dirname)) { + if (file.name.startsWith("index")) continue; + const name = path.basename(file.name, path.extname(file.name)); + links.push(name); +} + +export default function Home() { + return ( +
+

Tests

+
    + {links.sort().map((link) => { + return ( +
  • + {link} +
  • + ); + })} +
+
+ ); +} diff --git a/tests/fixture_hmr/routes/island.tsx b/tests/fixture_hmr/routes/island.tsx new file mode 100644 index 00000000..f2682430 --- /dev/null +++ b/tests/fixture_hmr/routes/island.tsx @@ -0,0 +1,10 @@ +import Counter from "../islands/Counter.tsx"; + +export default function Home() { + return ( +
+

foo

+ +
+ ); +} diff --git a/tests/fixture_hmr/routes/no_island.tsx b/tests/fixture_hmr/routes/no_island.tsx new file mode 100644 index 00000000..e8027d58 --- /dev/null +++ b/tests/fixture_hmr/routes/no_island.tsx @@ -0,0 +1,3 @@ +export default function Home() { + return

foo

; +} diff --git a/tests/hmr_test.ts b/tests/hmr_test.ts new file mode 100644 index 00000000..e0f4d1d7 --- /dev/null +++ b/tests/hmr_test.ts @@ -0,0 +1,107 @@ +import { copy } from "https://deno.land/std@0.204.0/fs/copy.ts"; +import { + basename, + delay, + dirname, + join, + Page, + puppeteer, + relative, +} from "./deps.ts"; +import { startFreshServer } from "./test_utils.ts"; +import { retry } from "$std/async/retry.ts"; + +async function withTmpFixture( + name: string, + fn: (page: Page, address: string, dir: string) => Promise, +) { + const tmp = join(await Deno.makeTempDir(), "project"); + const src = join(Deno.cwd(), dirname(name)); + await copy(src, tmp); + + // Update Fresh path + const denoJsonPath = join(tmp, "deno.json"); + const json = JSON.parse(await Deno.readTextFile(denoJsonPath)); + json.imports["$fresh/"] = relative(denoJsonPath, Deno.cwd()) + "/"; + await Deno.writeTextFile(denoJsonPath, JSON.stringify(json, null, 2)); + + // Watcher tests tend to be flaky + await retry(async () => { + const { lines, serverProcess, address } = await startFreshServer({ + args: ["run", "-A", "--watch", join(tmp, basename(name))], + env: { + "FRESH_ESBUILD_LOADER": "portable", + }, + }); + + try { + await delay(100); + const browser = await puppeteer.launch({ args: ["--no-sandbox"] }); + + try { + const page = await browser.newPage(); + await fn(page, address, tmp); + } finally { + await browser.close(); + } + } finally { + serverProcess.kill("SIGTERM"); + + // Wait until the process exits + await serverProcess.status; + + // Drain the lines stream + for await (const _ of lines) { /* noop */ } + } + }, { maxAttempts: 3 }); +} + +Deno.test({ + name: "page reloads with no island present", + // Watcher tests are pretty flaky in CI and non-UNIX systems. + // Until we know why, we'll gate these tests behind an + // environment variable. + ignore: !Deno.env.has("FRESH_WATCH_TESTS"), + fn: async () => { + await withTmpFixture( + "./tests/fixture_hmr/dev.ts", + async (page, address, dir) => { + await page.goto(`${address}/no_island`); + await page.waitForSelector("h1"); + + // Trigger file change + const file = join(dir, "routes", "no_island.tsx"); + const text = await Deno.readTextFile(file); + await Deno.writeTextFile(file, text.replaceAll("foo", "bar")); + + await page.waitForSelector(".bar"); + }, + ); + }, +}); + +Deno.test({ + name: "page reloads with island", + // Watcher tests are pretty flaky in CI and non-UNIX systems. + // Until we know why, we'll gate these tests behind an + // environment variable. + ignore: !Deno.env.has("FRESH_WATCH_TESTS"), + fn: async () => { + await withTmpFixture( + "./tests/fixture_hmr/dev.ts", + async (page, address, dir) => { + await page.goto(`${address}/island`); + await page.waitForSelector("h1"); + + // Trigger file change + const file = join(dir, "routes", "island.tsx"); + const text = await Deno.readTextFile(file); + await Deno.writeTextFile(file, text.replaceAll("foo", "bar")); + + await page.waitForSelector(".bar"); + // TODO: Once we support proper HMR check that state stays + // the same + }, + ); + }, +});