From b1a02108c5de2125b5cf2d44fac8c11b82aa6182 Mon Sep 17 00:00:00 2001 From: Marvin Hagemeister Date: Tue, 5 Sep 2023 12:34:05 +0200 Subject: [PATCH] fix: dev command loading snapshot (#1735) --- src/dev/dev_command.ts | 30 +++++++++++++++++-- src/server/boot.ts | 68 ++++++++++++++++++++++++++++++++++++++++++ src/server/context.ts | 4 +-- src/server/mod.ts | 67 ++--------------------------------------- tests/build_test.ts | 29 +++++++++++++++++- 5 files changed, 127 insertions(+), 71 deletions(-) create mode 100644 src/server/boot.ts diff --git a/src/dev/dev_command.ts b/src/dev/dev_command.ts index d092b0ee..8e7c780a 100644 --- a/src/dev/dev_command.ts +++ b/src/dev/dev_command.ts @@ -1,8 +1,13 @@ import { updateCheck } from "./update_check.ts"; -import { DAY, dirname, fromFileUrl, join } from "./deps.ts"; -import { FreshOptions } from "../server/mod.ts"; +import { DAY, dirname, fromFileUrl, fs, join, toFileUrl } from "./deps.ts"; +import { + FreshOptions, + Manifest as ServerManifest, + ServerContext, +} from "../server/mod.ts"; import { build } from "./build.ts"; import { collect, ensureMinDenoVersion, generate, Manifest } from "./mod.ts"; +import { startFromContext } from "../server/boot.ts"; export async function dev( base: string, @@ -34,9 +39,28 @@ export async function dev( if (manifestChanged) await generate(dir, newManifest); - if (Deno.args.includes("build")) { + const manifest = (await import(toFileUrl(join(dir, "fresh.gen.ts")).href)) + .default as ServerManifest; + + const outDir = join(dir, "_fresh"); + + const isBuild = Deno.args.includes("build"); + const ctx = await ServerContext.fromManifest(manifest, { + ...options, + skipSnapshot: true, + dev: !isBuild, + }); + + if (isBuild) { + // Ensure that build dir is empty + await fs.emptyDir(outDir); await build(join(dir, "fresh.gen.ts"), options); + } else if (options) { + await startFromContext(ctx, options); } else { + // Legacy entry point: Back then `dev.ts` would call `main.ts` but + // this causes duplicate plugin instantiation if both `dev.ts` and + // `main.ts` instantiate plugins. await import(entrypoint); } } diff --git a/src/server/boot.ts b/src/server/boot.ts new file mode 100644 index 00000000..b949289e --- /dev/null +++ b/src/server/boot.ts @@ -0,0 +1,68 @@ +import { ServerContext } from "./context.ts"; +import { colors } from "./deps.ts"; +import { ServeHandler, StartOptions } from "./types.ts"; + +export async function startFromContext(ctx: ServerContext, opts: StartOptions) { + if (!opts.onListen) { + opts.onListen = (params) => { + console.log(); + console.log( + colors.bgRgb8(colors.black(colors.bold(" 🍋 Fresh ready ")), 121), + ); + + const address = colors.cyan(`http://localhost:${params.port}/`); + const localLabel = colors.bold("Local:"); + console.log(` ${localLabel} ${address}\n`); + }; + } + + const portEnv = Deno.env.get("PORT"); + if (portEnv !== undefined) { + opts.port ??= parseInt(portEnv, 10); + } + + const handler = ctx.handler(); + + if (opts.port) { + await bootServer(handler, opts); + } else { + // No port specified, check for a free port. Instead of picking just + // any port we'll check if the next one is free for UX reasons. + // That way the user only needs to increment a number when running + // multiple apps vs having to remember completely different ports. + let firstError; + for (let port = 8000; port < 8020; port++) { + try { + await bootServer(handler, { ...opts, port }); + firstError = undefined; + break; + } catch (err) { + if (err instanceof Deno.errors.AddrInUse) { + // Throw first EADDRINUSE error + // if no port is free + if (!firstError) { + firstError = err; + } + continue; + } + + throw err; + } + } + + if (firstError) { + throw firstError; + } + } +} + +async function bootServer(handler: ServeHandler, opts: StartOptions) { + // @ts-ignore Ignore type error when type checking with Deno versions + if (typeof Deno.serve === "function") { + // @ts-ignore Ignore type error when type checking with Deno versions + await Deno.serve(opts, handler).finished; + } else { + // @ts-ignore Deprecated std serve way + await serve(handler, opts); + } +} diff --git a/src/server/context.ts b/src/server/context.ts index d6ef139b..5491c4a9 100644 --- a/src/server/context.ts +++ b/src/server/context.ts @@ -148,7 +148,7 @@ export class ServerContext { */ static async fromManifest( manifest: Manifest, - opts: FreshOptions & { skipSnapshot?: boolean }, + opts: FreshOptions & { skipSnapshot?: boolean; dev?: boolean }, ): Promise { // Get the manifest' base URL. const baseUrl = new URL("./", manifest.baseUrl).href; @@ -435,7 +435,7 @@ export class ServerContext { } } - const dev = isDevMode(); + const dev = opts.dev ?? isDevMode(); if (dev) { // Ensure that debugging hooks are set up for SSR rendering await import("preact/debug"); diff --git a/src/server/mod.ts b/src/server/mod.ts index 6e61101d..2ca0572d 100644 --- a/src/server/mod.ts +++ b/src/server/mod.ts @@ -2,7 +2,6 @@ import { LayoutConfig } from "$fresh/server.ts"; import { ComponentChildren } from "preact"; import { ServerContext } from "./context.ts"; export { Status } from "./deps.ts"; -import { colors, serve } from "./deps.ts"; import { ErrorHandler, Handler, @@ -10,11 +9,11 @@ import { IslandModule, MiddlewareModule, RouteConfig, - ServeHandler, ServeHandlerInfo, StartOptions, UnknownHandler, } from "./types.ts"; +import { startFromContext } from "./boot.ts"; export { defineApp, defineConfig, @@ -112,67 +111,5 @@ export async function createHandler( export async function start(routes: Manifest, opts: StartOptions = {}) { const ctx = await ServerContext.fromManifest(routes, opts); - - if (!opts.onListen) { - opts.onListen = (params) => { - console.log(); - console.log( - colors.bgRgb8(colors.black(colors.bold(" 🍋 Fresh ready ")), 121), - ); - - const address = colors.cyan(`http://localhost:${params.port}/`); - const localLabel = colors.bold("Local:"); - console.log(` ${localLabel} ${address}\n`); - }; - } - - const portEnv = Deno.env.get("PORT"); - if (portEnv !== undefined) { - opts.port ??= parseInt(portEnv, 10); - } - - const handler = ctx.handler(); - - if (opts.port) { - await bootServer(handler, opts); - } else { - // No port specified, check for a free port. Instead of picking just - // any port we'll check if the next one is free for UX reasons. - // That way the user only needs to increment a number when running - // multiple apps vs having to remember completely different ports. - let firstError; - for (let port = 8000; port < 8020; port++) { - try { - await bootServer(handler, { ...opts, port }); - firstError = undefined; - break; - } catch (err) { - if (err instanceof Deno.errors.AddrInUse) { - // Throw first EADDRINUSE error - // if no port is free - if (!firstError) { - firstError = err; - } - continue; - } - - throw err; - } - } - - if (firstError) { - throw firstError; - } - } -} - -async function bootServer(handler: ServeHandler, opts: StartOptions) { - // @ts-ignore Ignore type error when type checking with Deno versions - if (typeof Deno.serve === "function") { - // @ts-ignore Ignore type error when type checking with Deno versions - await Deno.serve(opts, handler).finished; - } else { - // @ts-ignore Deprecated std serve way - await serve(handler, opts); - } + await startFromContext(ctx, opts); } diff --git a/tests/build_test.ts b/tests/build_test.ts index 0fa782b8..7b80910a 100644 --- a/tests/build_test.ts +++ b/tests/build_test.ts @@ -4,6 +4,7 @@ import { assert } from "$std/_util/asserts.ts"; import { startFreshServer, waitForText } from "$fresh/tests/test_utils.ts"; import { BuildSnapshotJson } from "$fresh/src/build/mod.ts"; import { assertStringIncludes } from "$std/testing/asserts.ts"; +import { assertNotMatch } from "$std/testing/asserts.ts"; Deno.test("build snapshot and restore from it", async (t) => { const fixture = path.join(Deno.cwd(), "tests", "fixture_build"); @@ -41,7 +42,7 @@ Deno.test("build snapshot and restore from it", async (t) => { await Deno.readTextFile(path.join(outDir, "snapshot.json")), ) as BuildSnapshotJson; - await t.step("check snapshot file", () => { + await t.step("check snapshot file", async () => { assert( Array.isArray(snapshot.files["island-counter_default.js"]), "Island output file not found in snapshot", @@ -58,6 +59,10 @@ Deno.test("build snapshot and restore from it", async (t) => { Array.isArray(snapshot.files["deserializer.js"]), "deserializer.js output file not found in snapshot", ); + + // Should not include `preact/debug` + const mainJs = await Deno.readTextFile(path.join(outDir, "main.js")); + assertNotMatch(mainJs, /Undefined parent passed to render()/); }); await t.step("restore from snapshot", async () => { @@ -112,6 +117,28 @@ Deno.test("build snapshot and restore from it", async (t) => { await serverProcess.status; } }); + + await t.step("should not restore from snapshot in dev mode", async () => { + const { lines, serverProcess, output } = await startFreshServer({ + args: [ + "run", + "-A", + path.join(fixture, "./dev.ts"), + ], + }); + + try { + // Check that restore snapshot message was NOT printed + assert( + !output.find((line) => line.includes("Using snapshot found at")), + "Restoring from snapshot message should not appear in dev mode", + ); + } finally { + await lines.cancel(); + serverProcess.kill("SIGTERM"); + await serverProcess.status; + } + }); } finally { await Deno.remove(path.join(fixture, "_fresh"), { recursive: true }); }