From 3fd8fe89d320389463a5652875f078838c836403 Mon Sep 17 00:00:00 2001 From: Marvin Hagemeister Date: Wed, 20 Sep 2023 10:40:09 +0200 Subject: [PATCH] feat: add build.outDir option (#1797) --- .gitignore | 1 + deno.json | 3 +- src/dev/build.ts | 36 +- src/dev/dev_command.ts | 43 +- src/server/config.ts | 90 +++ src/server/context.ts | 659 ++++++++---------- src/server/deps.ts | 1 + src/server/mod.ts | 25 +- src/server/types.ts | 41 ++ tests/build_test.ts | 110 ++- tests/dev_command_test.ts | 11 +- tests/fixture_build_out_dir/deno.json | 15 + tests/fixture_build_out_dir/dev.ts | 9 + tests/fixture_build_out_dir/fresh.gen.ts | 18 + .../fixture_build_out_dir/islands/Counter.tsx | 22 + tests/fixture_build_out_dir/main.ts | 10 + tests/fixture_build_out_dir/routes/index.tsx | 15 + tests/fixture_build_out_dir_sub/deno.json | 15 + tests/fixture_build_out_dir_sub/src/dev.ts | 9 + .../src/fresh.gen.ts | 18 + .../src/islands/Counter.tsx | 22 + tests/fixture_build_out_dir_sub/src/main.ts | 10 + .../src/routes/index.tsx | 15 + tests/fixture_build_out_dir_sub2/deno.json | 15 + tests/fixture_build_out_dir_sub2/src/dev.ts | 9 + .../src/fresh.gen.ts | 18 + .../src/islands/Counter.tsx | 22 + tests/fixture_build_out_dir_sub2/src/main.ts | 10 + .../src/routes/index.tsx | 15 + tests/plugin_test.ts | 7 +- 30 files changed, 846 insertions(+), 448 deletions(-) create mode 100644 src/server/config.ts create mode 100644 tests/fixture_build_out_dir/deno.json create mode 100755 tests/fixture_build_out_dir/dev.ts create mode 100644 tests/fixture_build_out_dir/fresh.gen.ts create mode 100644 tests/fixture_build_out_dir/islands/Counter.tsx create mode 100644 tests/fixture_build_out_dir/main.ts create mode 100644 tests/fixture_build_out_dir/routes/index.tsx create mode 100644 tests/fixture_build_out_dir_sub/deno.json create mode 100755 tests/fixture_build_out_dir_sub/src/dev.ts create mode 100644 tests/fixture_build_out_dir_sub/src/fresh.gen.ts create mode 100644 tests/fixture_build_out_dir_sub/src/islands/Counter.tsx create mode 100644 tests/fixture_build_out_dir_sub/src/main.ts create mode 100644 tests/fixture_build_out_dir_sub/src/routes/index.tsx create mode 100644 tests/fixture_build_out_dir_sub2/deno.json create mode 100755 tests/fixture_build_out_dir_sub2/src/dev.ts create mode 100644 tests/fixture_build_out_dir_sub2/src/fresh.gen.ts create mode 100644 tests/fixture_build_out_dir_sub2/src/islands/Counter.tsx create mode 100644 tests/fixture_build_out_dir_sub2/src/main.ts create mode 100644 tests/fixture_build_out_dir_sub2/src/routes/index.tsx diff --git a/.gitignore b/.gitignore index 03b773a3..5a0f580b 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ _fresh/ +tmp/ diff --git a/deno.json b/deno.json index 4604fcbb..a572c0a5 100644 --- a/deno.json +++ b/deno.json @@ -9,7 +9,8 @@ "ok": "deno fmt --check && deno lint && deno task check:types && deno task test" }, "exclude": [ - "**/_fresh/*" + "**/_fresh/*", + "**/tmp/*" ], "importMap": "./.vscode/import_map.json", "compilerOptions": { diff --git a/src/dev/build.ts b/src/dev/build.ts index ddc3ad4a..3e611391 100644 --- a/src/dev/build.ts +++ b/src/dev/build.ts @@ -1,28 +1,20 @@ -import { ServerContext } from "../server/context.ts"; -import { FreshOptions, Manifest } from "../server/mod.ts"; -import { dirname, fromFileUrl, join, toFileUrl } from "../server/deps.ts"; -import { fs } from "./deps.ts"; +import { getServerContext } from "../server/context.ts"; +import { join } from "../server/deps.ts"; +import { colors, fs } from "./deps.ts"; import { BuildSnapshotJson } from "../build/mod.ts"; -import { BUILD_ID } from "$fresh/src/server/build_id.ts"; +import { BUILD_ID } from "../server/build_id.ts"; +import { InternalFreshOptions } from "../server/types.ts"; export async function build( - manifestPath: string, - opts: FreshOptions, + config: InternalFreshOptions, ) { - const manifest = (await import(toFileUrl(manifestPath).href)) - .default as Manifest; - - const outDir = join(dirname(fromFileUrl(manifest.baseUrl)), "_fresh"); - // Ensure that build dir is empty - await fs.emptyDir(outDir); + await fs.emptyDir(config.build.outDir); - const ctx = await ServerContext.fromManifest(manifest, { - ...opts, - skipSnapshot: true, - }); + await Promise.all(config.plugins.map((plugin) => plugin.buildStart?.())); // Bundle assets + const ctx = await getServerContext(config); const snapshot = await ctx.buildSnapshot(); // Write output files to disk @@ -30,7 +22,7 @@ export async function build( const data = await snapshot.read(fileName); if (data === null) return; - return Deno.writeFile(join(outDir, fileName), data); + return Deno.writeFile(join(config.build.outDir, fileName), data); })); // Write dependency snapshot file to disk @@ -43,6 +35,12 @@ export async function build( jsonSnapshot.files[filePath] = dependencies; } - const snapshotPath = join(outDir, "snapshot.json"); + const snapshotPath = join(config.build.outDir, "snapshot.json"); await Deno.writeTextFile(snapshotPath, JSON.stringify(jsonSnapshot, null, 2)); + + console.log( + `Assets written to: ${colors.green(config.build.outDir)}`, + ); + + await Promise.all(config.plugins.map((plugin) => plugin.buildEnd?.())); } diff --git a/src/dev/dev_command.ts b/src/dev/dev_command.ts index b22a890c..fe190c7c 100644 --- a/src/dev/dev_command.ts +++ b/src/dev/dev_command.ts @@ -1,13 +1,11 @@ import { updateCheck } from "./update_check.ts"; -import { DAY, dirname, fromFileUrl, fs, join, toFileUrl } from "./deps.ts"; -import { - FreshOptions, - Manifest as ServerManifest, - ServerContext, -} from "../server/mod.ts"; +import { DAY, dirname, fromFileUrl, join, toFileUrl } from "./deps.ts"; +import { FreshOptions, Manifest as ServerManifest } from "../server/mod.ts"; import { build } from "./build.ts"; import { collect, ensureMinDenoVersion, generate, Manifest } from "./mod.ts"; import { startFromContext } from "../server/boot.ts"; +import { getFreshConfigWithDefaults } from "../server/config.ts"; +import { getServerContext } from "$fresh/src/server/context.ts"; export async function dev( base: string, @@ -40,25 +38,22 @@ export async function dev( 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"); - if (isBuild) { - // Ensure that build dir is empty - await fs.emptyDir(outDir); - - options = options ?? {}; - const plugins = options.plugins ?? []; - - await Promise.all(plugins.map((plugin) => plugin.buildStart?.())); - await build(join(dir, "fresh.gen.ts"), options); - await Promise.all(plugins.map((plugin) => plugin.buildEnd?.())); + if (Deno.args.includes("build")) { + const config = await getFreshConfigWithDefaults( + manifest, + options ?? {}, + ); + config.dev = false; + config.loadSnapshot = false; + await build(config); } else if (options) { - const ctx = await ServerContext.fromManifest(manifest, { - ...options, - skipSnapshot: true, - dev: true, - }); + const config = await getFreshConfigWithDefaults( + manifest, + options, + ); + config.dev = true; + config.loadSnapshot = false; + const ctx = await getServerContext(config); await startFromContext(ctx, options); } else { // Legacy entry point: Back then `dev.ts` would call `main.ts` but diff --git a/src/server/config.ts b/src/server/config.ts new file mode 100644 index 00000000..16c2b742 --- /dev/null +++ b/src/server/config.ts @@ -0,0 +1,90 @@ +import { DEV_MODE } from "./constants.ts"; +import { dirname, fromFileUrl, isAbsolute, join, JSONC } from "./deps.ts"; +import { FromManifestOptions, Manifest } from "./mod.ts"; +import { DenoConfig, InternalFreshOptions } from "./types.ts"; + +export async function readDenoConfig( + directory: string, +): Promise<{ config: DenoConfig; path: string }> { + let dir = directory; + while (true) { + for (const name of ["deno.json", "deno.jsonc"]) { + const path = join(dir, name); + try { + const file = await Deno.readTextFile(path); + if (name.endsWith(".jsonc")) { + return { config: JSONC.parse(file) as DenoConfig, path }; + } else { + return { config: JSON.parse(file), path }; + } + } catch (err) { + if (!(err instanceof Deno.errors.NotFound)) { + throw err; + } + } + } + const parent = dirname(dir); + if (parent === dir) { + throw new Error( + `Could not find a deno.json file in the current directory or any parent directory.`, + ); + } + dir = parent; + } +} + +function isObject(value: unknown) { + return value !== null && typeof value === "object" && + !Array.isArray(value); +} + +export async function getFreshConfigWithDefaults( + manifest: Manifest, + opts: FromManifestOptions, +): Promise { + const base = dirname(fromFileUrl(manifest.baseUrl)); + const { config: denoJson, path: denoJsonPath } = await readDenoConfig(base); + + if (typeof denoJson.importMap !== "string" && !isObject(denoJson.imports)) { + throw new Error( + "deno.json must contain an 'importMap' or 'imports' property.", + ); + } + + const config: InternalFreshOptions = { + loadSnapshot: typeof opts.skipSnapshot === "boolean" + ? !opts.skipSnapshot + : false, + dev: opts.dev ?? DEV_MODE, + denoJsonPath, + denoJson, + manifest, + build: { + outDir: "", + }, + plugins: opts.plugins ?? [], + staticDir: "", + render: opts.render, + router: opts.router, + }; + + config.build.outDir = opts.build?.outDir + ? parseFileOrUrl(opts.build.outDir, base) + : join(base, "_fresh"); + + config.staticDir = opts.staticDir + ? parseFileOrUrl(opts.staticDir, base) + : join(base, "static"); + + return config; +} + +function parseFileOrUrl(input: string, base: string) { + if (input.startsWith("file://")) { + return fromFileUrl(input); + } else if (!isAbsolute(input)) { + return join(base, input); + } + + return input; +} diff --git a/src/server/context.ts b/src/server/context.ts index 5b817358..918aa9d2 100644 --- a/src/server/context.ts +++ b/src/server/context.ts @@ -1,10 +1,7 @@ import { colors, - dirname, extname, - fromFileUrl, join, - JSONC, Status, toFileUrl, typeByExtension, @@ -12,7 +9,7 @@ import { } from "./deps.ts"; import { ComponentType, h } from "preact"; import * as router from "./router.ts"; -import { DenoConfig, Manifest } from "./mod.ts"; +import { Manifest } from "./mod.ts"; import { ALIVE_URL, JS_PREFIX, @@ -28,6 +25,7 @@ import { ErrorPageModule, FreshOptions, Handler, + InternalFreshOptions, Island, LayoutModule, LayoutRoute, @@ -64,6 +62,7 @@ import { import { InternalRoute } from "./router.ts"; import { setAllIslands } from "./rendering/preact_hooks.ts"; import { getCodeFrame } from "./code_frame.ts"; +import { getFreshConfigWithDefaults } from "./config.ts"; const DEFAULT_CONN_INFO: ServeHandlerInfo = { localAddr: { transport: "tcp", hostname: "localhost", port: 8080 }, @@ -72,12 +71,6 @@ const DEFAULT_CONN_INFO: ServeHandlerInfo = { const ROOT_BASE_ROUTE = toBaseRoute("/"); -function isObject(value: unknown) { - return typeof value === "object" && - !Array.isArray(value) && - value !== null; -} - interface StaticFile { /** The URL to the static file on disk. */ localUrl: URL; @@ -96,6 +89,303 @@ export type FromManifestOptions = FreshOptions & { dev?: boolean; }; +export async function getServerContext(opts: InternalFreshOptions) { + const { manifest, denoJson: config, denoJsonPath: configPath } = opts; + // Get the manifest' base URL. + const baseUrl = new URL("./", manifest.baseUrl).href; + + // Restore snapshot if available + let snapshot: BuildSnapshot | null = null; + if (opts.loadSnapshot) { + const snapshotDirPath = opts.build.outDir; + try { + if ((await Deno.stat(snapshotDirPath)).isDirectory) { + console.log( + `Using snapshot found at ${colors.cyan(snapshotDirPath)}`, + ); + + const snapshotPath = join(snapshotDirPath, "snapshot.json"); + const json = JSON.parse( + await Deno.readTextFile(snapshotPath), + ) as BuildSnapshotJson; + setBuildId(json.build_id); + + const dependencies = new Map( + Object.entries(json.files), + ); + + const files = new Map(); + Object.keys(json.files).forEach((name) => { + const filePath = join(snapshotDirPath, name); + files.set(name, filePath); + }); + + snapshot = new AotSnapshot(files, dependencies); + } + } catch (err) { + if (!(err instanceof Deno.errors.NotFound)) { + throw err; + } + } + } + + config.compilerOptions ??= {}; + + let jsx: "react" | "react-jsx"; + switch (config.compilerOptions.jsx) { + case "react": + case undefined: + jsx = "react"; + break; + case "react-jsx": + jsx = "react-jsx"; + break; + default: + throw new Error("Unknown jsx option: " + config.compilerOptions.jsx); + } + + const jsxConfig: JSXConfig = { + jsx, + jsxImportSource: config.compilerOptions.jsxImportSource, + }; + + // Extract all routes, and prepare them into the `Page` structure. + const routes: Route[] = []; + const islands: Island[] = []; + const middlewares: MiddlewareRoute[] = []; + let app: AppModule = DEFAULT_APP; + const layouts: LayoutRoute[] = []; + let notFound: UnknownPage = DEFAULT_NOT_FOUND; + let error: ErrorPage = DEFAULT_ERROR; + const allRoutes = [ + ...Object.entries(manifest.routes), + ...(opts.plugins ? getMiddlewareRoutesFromPlugins(opts.plugins) : []), + ...(opts.plugins ? getRoutesFromPlugins(opts.plugins) : []), + ]; + + // Presort all routes so that we only need to sort once + allRoutes.sort((a, b) => sortRoutePaths(a[0], b[0])); + + for ( + const [self, module] of allRoutes + ) { + const url = new URL(self, baseUrl).href; + if (!url.startsWith(baseUrl + "routes")) { + throw new TypeError("Page is not a child of the basepath."); + } + const path = url.substring(baseUrl.length).substring("routes".length); + const baseRoute = path.substring(1, path.length - extname(path).length); + const name = baseRoute.replace("/", "-"); + const isLayout = path.endsWith("/_layout.tsx") || + path.endsWith("/_layout.ts") || path.endsWith("/_layout.jsx") || + path.endsWith("/_layout.js"); + const isMiddleware = path.endsWith("/_middleware.tsx") || + path.endsWith("/_middleware.ts") || path.endsWith("/_middleware.jsx") || + path.endsWith("/_middleware.js"); + if ( + !path.startsWith("/_") && !isLayout && !isMiddleware + ) { + const { default: component, config } = module as RouteModule; + let pattern = pathToPattern(baseRoute); + if (config?.routeOverride) { + pattern = String(config.routeOverride); + } + let { handler } = module as RouteModule; + if (!handler && "handlers" in module) { + throw new Error( + `Found named export "handlers" in ${self} instead of "handler". Did you mean "handler"?`, + ); + } + handler ??= {}; + if ( + component && typeof handler === "object" && handler.GET === undefined + ) { + handler.GET = (_req, { render }) => render(); + } + if ( + typeof handler === "object" && handler.GET !== undefined && + handler.HEAD === undefined + ) { + const GET = handler.GET; + handler.HEAD = async (req, ctx) => { + const resp = await GET(req, ctx); + resp.body?.cancel(); + return new Response(null, { + headers: resp.headers, + status: resp.status, + statusText: resp.statusText, + }); + }; + } + const route: Route = { + baseRoute: toBaseRoute(baseRoute), + pattern, + url, + name, + component, + handler, + csp: Boolean(config?.csp ?? false), + appWrapper: !config?.skipAppWrapper, + inheritLayouts: !config?.skipInheritedLayouts, + }; + routes.push(route); + } else if (isMiddleware) { + middlewares.push({ + baseRoute: toBaseRoute(baseRoute), + module: module as MiddlewareModule, + }); + } else if ( + path === "/_app.tsx" || path === "/_app.ts" || + path === "/_app.jsx" || path === "/_app.js" + ) { + app = module as AppModule; + } else if (isLayout) { + const mod = module as LayoutModule; + const config = mod.config; + layouts.push({ + baseRoute: toBaseRoute(baseRoute), + handler: mod.handler, + component: mod.default, + appWrapper: !config?.skipAppWrapper, + inheritLayouts: !config?.skipInheritedLayouts, + }); + } else if ( + path === "/_404.tsx" || path === "/_404.ts" || + path === "/_404.jsx" || path === "/_404.js" + ) { + const { default: component, config } = module as UnknownPageModule; + let { handler } = module as UnknownPageModule; + if (component && handler === undefined) { + handler = (_req, { render }) => render(); + } + + notFound = { + baseRoute: ROOT_BASE_ROUTE, + pattern: pathToPattern(baseRoute), + url, + name, + component, + handler: handler ?? ((req) => router.defaultOtherHandler(req)), + csp: Boolean(config?.csp ?? false), + appWrapper: !config?.skipAppWrapper, + inheritLayouts: !config?.skipInheritedLayouts, + }; + } else if ( + path === "/_500.tsx" || path === "/_500.ts" || + path === "/_500.jsx" || path === "/_500.js" + ) { + const { default: component, config } = module as ErrorPageModule; + let { handler } = module as ErrorPageModule; + if (component && handler === undefined) { + handler = (_req, { render }) => render(); + } + + error = { + baseRoute: toBaseRoute("/"), + pattern: pathToPattern(baseRoute), + url, + name, + component, + handler: handler ?? + ((req, ctx) => router.defaultErrorHandler(req, ctx, ctx.error)), + csp: Boolean(config?.csp ?? false), + appWrapper: !config?.skipAppWrapper, + inheritLayouts: !config?.skipInheritedLayouts, + }; + } + } + + for (const [self, module] of Object.entries(manifest.islands)) { + const url = new URL(self, baseUrl).href; + if (!url.startsWith(baseUrl)) { + throw new TypeError("Island is not a child of the basepath."); + } + let path = url.substring(baseUrl.length); + if (path.startsWith("islands")) { + path = path.slice("islands".length + 1); + } + const baseRoute = path.substring(0, path.length - extname(path).length); + + for (const [exportName, exportedFunction] of Object.entries(module)) { + if (typeof exportedFunction !== "function") { + continue; + } + const name = sanitizeIslandName(baseRoute); + const id = `${name}_${exportName}`.toLowerCase(); + islands.push({ + id, + name, + url, + component: exportedFunction, + exportName, + }); + } + } + + const staticFiles: StaticFile[] = []; + try { + const staticDirUrl = toFileUrl(opts.staticDir); + const entries = walk(opts.staticDir, { + includeFiles: true, + includeDirs: false, + followSymlinks: false, + }); + const encoder = new TextEncoder(); + for await (const entry of entries) { + const localUrl = toFileUrl(entry.path); + const path = localUrl.href.substring(staticDirUrl.href.length); + const stat = await Deno.stat(localUrl); + const contentType = typeByExtension(extname(path)) ?? + "application/octet-stream"; + const etag = await crypto.subtle.digest( + "SHA-1", + encoder.encode(BUILD_ID + path), + ).then((hash) => + Array.from(new Uint8Array(hash)) + .map((byte) => byte.toString(16).padStart(2, "0")) + .join("") + ); + const staticFile: StaticFile = { + localUrl, + path, + size: stat.size, + contentType, + etag, + }; + staticFiles.push(staticFile); + } + } catch (err) { + if (err.cause instanceof Deno.errors.NotFound) { + // Do nothing. + } else { + throw err; + } + } + + if (opts.dev) { + // Ensure that debugging hooks are set up for SSR rendering + await import("preact/debug"); + } + + return new ServerContext( + routes, + islands, + staticFiles, + opts.render ?? DEFAULT_RENDER_FN, + middlewares, + app, + layouts, + notFound, + error, + opts.plugins ?? [], + configPath, + jsxConfig, + opts.dev, + opts.router ?? DEFAULT_ROUTER_OPTIONS, + snapshot, + ); +} + export class ServerContext { #dev: boolean; #routes: Route[]; @@ -156,324 +446,17 @@ export class ServerContext { manifest: Manifest, opts: FromManifestOptions, ): Promise { - const dev = Deno.env.get("__FRSH_LEGACY_DEV") === "true" || + const isLegacyDev = Deno.env.get("__FRSH_LEGACY_DEV") === "true"; + const dev = isLegacyDev || Boolean(opts.dev); setDevMode(dev); - // Get the manifest' base URL. - const baseUrl = new URL("./", manifest.baseUrl).href; - - const { config, path: configPath } = await readDenoConfig( - fromFileUrl(baseUrl), - ); - if (typeof config.importMap !== "string" && !isObject(config.imports)) { - throw new Error( - "deno.json must contain an 'importMap' or 'imports' property.", - ); + if (isLegacyDev) { + opts.skipSnapshot = true; } - // Restore snapshot if available - let snapshot: BuildSnapshot | null = null; - // Load from snapshot if not explicitly requested not to - let loadFromSnapshot = !opts.skipSnapshot; - // We still need to check for a legacy entry point :S - if (Deno.env.has("__FRSH_LEGACY_DEV")) { - loadFromSnapshot = false; - } - if (loadFromSnapshot) { - const snapshotDirPath = join( - dirname(fromFileUrl(manifest.baseUrl)), - "_fresh", - ); - try { - if ((await Deno.stat(snapshotDirPath)).isDirectory) { - console.log( - `Using snapshot found at ${colors.cyan(snapshotDirPath)}`, - ); - - const snapshotPath = join(snapshotDirPath, "snapshot.json"); - const json = JSON.parse( - await Deno.readTextFile(snapshotPath), - ) as BuildSnapshotJson; - setBuildId(json.build_id); - - const dependencies = new Map( - Object.entries(json.files), - ); - - const files = new Map(); - Object.keys(json.files).forEach((name) => { - const filePath = join(snapshotDirPath, name); - files.set(name, filePath); - }); - - snapshot = new AotSnapshot(files, dependencies); - } - } catch (err) { - if (!(err instanceof Deno.errors.NotFound)) { - throw err; - } - } - } - - config.compilerOptions ??= {}; - - let jsx: "react" | "react-jsx"; - switch (config.compilerOptions.jsx) { - case "react": - case undefined: - jsx = "react"; - break; - case "react-jsx": - jsx = "react-jsx"; - break; - default: - throw new Error("Unknown jsx option: " + config.compilerOptions.jsx); - } - - const jsxConfig: JSXConfig = { - jsx, - jsxImportSource: config.compilerOptions.jsxImportSource, - }; - - // Extract all routes, and prepare them into the `Page` structure. - const routes: Route[] = []; - const islands: Island[] = []; - const middlewares: MiddlewareRoute[] = []; - let app: AppModule = DEFAULT_APP; - const layouts: LayoutRoute[] = []; - let notFound: UnknownPage = DEFAULT_NOT_FOUND; - let error: ErrorPage = DEFAULT_ERROR; - const allRoutes = [ - ...Object.entries(manifest.routes), - ...(opts.plugins ? getMiddlewareRoutesFromPlugins(opts.plugins) : []), - ...(opts.plugins ? getRoutesFromPlugins(opts.plugins) : []), - ]; - - // Presort all routes so that we only need to sort once - allRoutes.sort((a, b) => sortRoutePaths(a[0], b[0])); - - for ( - const [self, module] of allRoutes - ) { - const url = new URL(self, baseUrl).href; - if (!url.startsWith(baseUrl + "routes")) { - throw new TypeError("Page is not a child of the basepath."); - } - const path = url.substring(baseUrl.length).substring("routes".length); - const baseRoute = path.substring(1, path.length - extname(path).length); - const name = baseRoute.replace("/", "-"); - const isLayout = path.endsWith("/_layout.tsx") || - path.endsWith("/_layout.ts") || path.endsWith("/_layout.jsx") || - path.endsWith("/_layout.js"); - const isMiddleware = path.endsWith("/_middleware.tsx") || - path.endsWith("/_middleware.ts") || path.endsWith("/_middleware.jsx") || - path.endsWith("/_middleware.js"); - if ( - !path.startsWith("/_") && !isLayout && !isMiddleware - ) { - const { default: component, config } = module as RouteModule; - let pattern = pathToPattern(baseRoute); - if (config?.routeOverride) { - pattern = String(config.routeOverride); - } - let { handler } = module as RouteModule; - if (!handler && "handlers" in module) { - throw new Error( - `Found named export "handlers" in ${self} instead of "handler". Did you mean "handler"?`, - ); - } - handler ??= {}; - if ( - component && typeof handler === "object" && handler.GET === undefined - ) { - handler.GET = (_req, { render }) => render(); - } - if ( - typeof handler === "object" && handler.GET !== undefined && - handler.HEAD === undefined - ) { - const GET = handler.GET; - handler.HEAD = async (req, ctx) => { - const resp = await GET(req, ctx); - resp.body?.cancel(); - return new Response(null, { - headers: resp.headers, - status: resp.status, - statusText: resp.statusText, - }); - }; - } - const route: Route = { - baseRoute: toBaseRoute(baseRoute), - pattern, - url, - name, - component, - handler, - csp: Boolean(config?.csp ?? false), - appWrapper: !config?.skipAppWrapper, - inheritLayouts: !config?.skipInheritedLayouts, - }; - routes.push(route); - } else if (isMiddleware) { - middlewares.push({ - baseRoute: toBaseRoute(baseRoute), - module: module as MiddlewareModule, - }); - } else if ( - path === "/_app.tsx" || path === "/_app.ts" || - path === "/_app.jsx" || path === "/_app.js" - ) { - app = module as AppModule; - } else if (isLayout) { - const mod = module as LayoutModule; - const config = mod.config; - layouts.push({ - baseRoute: toBaseRoute(baseRoute), - handler: mod.handler, - component: mod.default, - appWrapper: !config?.skipAppWrapper, - inheritLayouts: !config?.skipInheritedLayouts, - }); - } else if ( - path === "/_404.tsx" || path === "/_404.ts" || - path === "/_404.jsx" || path === "/_404.js" - ) { - const { default: component, config } = module as UnknownPageModule; - let { handler } = module as UnknownPageModule; - if (component && handler === undefined) { - handler = (_req, { render }) => render(); - } - - notFound = { - baseRoute: ROOT_BASE_ROUTE, - pattern: pathToPattern(baseRoute), - url, - name, - component, - handler: handler ?? ((req) => router.defaultOtherHandler(req)), - csp: Boolean(config?.csp ?? false), - appWrapper: !config?.skipAppWrapper, - inheritLayouts: !config?.skipInheritedLayouts, - }; - } else if ( - path === "/_500.tsx" || path === "/_500.ts" || - path === "/_500.jsx" || path === "/_500.js" - ) { - const { default: component, config } = module as ErrorPageModule; - let { handler } = module as ErrorPageModule; - if (component && handler === undefined) { - handler = (_req, { render }) => render(); - } - - error = { - baseRoute: toBaseRoute("/"), - pattern: pathToPattern(baseRoute), - url, - name, - component, - handler: handler ?? - ((req, ctx) => router.defaultErrorHandler(req, ctx, ctx.error)), - csp: Boolean(config?.csp ?? false), - appWrapper: !config?.skipAppWrapper, - inheritLayouts: !config?.skipInheritedLayouts, - }; - } - } - - for (const [self, module] of Object.entries(manifest.islands)) { - const url = new URL(self, baseUrl).href; - if (!url.startsWith(baseUrl)) { - throw new TypeError("Island is not a child of the basepath."); - } - let path = url.substring(baseUrl.length); - if (path.startsWith("islands")) { - path = path.slice("islands".length + 1); - } - const baseRoute = path.substring(0, path.length - extname(path).length); - - for (const [exportName, exportedFunction] of Object.entries(module)) { - if (typeof exportedFunction !== "function") { - continue; - } - const name = sanitizeIslandName(baseRoute); - const id = `${name}_${exportName}`.toLowerCase(); - islands.push({ - id, - name, - url, - component: exportedFunction, - exportName, - }); - } - } - - const staticFiles: StaticFile[] = []; - try { - const staticFolder = new URL( - opts.staticDir ?? "./static", - manifest.baseUrl, - ); - const entries = walk(fromFileUrl(staticFolder), { - includeFiles: true, - includeDirs: false, - followSymlinks: false, - }); - const encoder = new TextEncoder(); - for await (const entry of entries) { - const localUrl = toFileUrl(entry.path); - const path = localUrl.href.substring(staticFolder.href.length); - const stat = await Deno.stat(localUrl); - const contentType = typeByExtension(extname(path)) ?? - "application/octet-stream"; - const etag = await crypto.subtle.digest( - "SHA-1", - encoder.encode(BUILD_ID + path), - ).then((hash) => - Array.from(new Uint8Array(hash)) - .map((byte) => byte.toString(16).padStart(2, "0")) - .join("") - ); - const staticFile: StaticFile = { - localUrl, - path, - size: stat.size, - contentType, - etag, - }; - staticFiles.push(staticFile); - } - } catch (err) { - if (err.cause instanceof Deno.errors.NotFound) { - // Do nothing. - } else { - throw err; - } - } - - if (dev) { - // Ensure that debugging hooks are set up for SSR rendering - await import("preact/debug"); - } - - return new ServerContext( - routes, - islands, - staticFiles, - opts.render ?? DEFAULT_RENDER_FN, - middlewares, - app, - layouts, - notFound, - error, - opts.plugins ?? [], - configPath, - jsxConfig, - dev, - opts.router ?? DEFAULT_ROUTER_OPTIONS, - snapshot, - ); + const config = await getFreshConfigWithDefaults(manifest, opts); + return getServerContext(config); } /** @@ -1352,36 +1335,6 @@ function collectEntrypoints( return entryPoints; } -async function readDenoConfig( - directory: string, -): Promise<{ config: DenoConfig; path: string }> { - let dir = directory; - while (true) { - for (const name of ["deno.json", "deno.jsonc"]) { - const path = join(dir, name); - try { - const file = await Deno.readTextFile(path); - if (name.endsWith(".jsonc")) { - return { config: JSONC.parse(file) as DenoConfig, path }; - } else { - return { config: JSON.parse(file), path }; - } - } catch (err) { - if (!(err instanceof Deno.errors.NotFound)) { - throw err; - } - } - } - const parent = dirname(dir); - if (parent === dir) { - throw new Error( - `Could not find a deno.json file in the current directory or any parent directory.`, - ); - } - dir = parent; - } -} - function formatMiddlewarePath(path: string): string { const prefix = !path.startsWith("/") ? "/" : ""; const suffix = !path.endsWith("/") ? "/" : ""; diff --git a/src/server/deps.ts b/src/server/deps.ts index 23e66404..e048212b 100644 --- a/src/server/deps.ts +++ b/src/server/deps.ts @@ -3,6 +3,7 @@ export { dirname, extname, fromFileUrl, + isAbsolute, join, toFileUrl, } from "https://deno.land/std@0.193.0/path/mod.ts"; diff --git a/src/server/mod.ts b/src/server/mod.ts index 5b6f3f98..b4a8833a 100644 --- a/src/server/mod.ts +++ b/src/server/mod.ts @@ -24,6 +24,7 @@ export { export type { AppContext, AppProps, + DenoConfig, ErrorHandler, ErrorHandlerContext, ErrorPageProps, @@ -81,24 +82,6 @@ export interface Manifest { baseUrl: string; } -export interface DenoConfig { - imports?: Record; - importMap?: string; - tasks?: Record; - lint?: { - rules: { tags?: string[] }; - exclude?: string[]; - }; - fmt?: { - exclude?: string[]; - }; - exclude?: string[]; - compilerOptions?: { - jsx?: string; - jsxImportSource?: string; - }; -} - export { ServerContext }; export async function createHandler( @@ -112,6 +95,10 @@ export async function createHandler( } export async function start(routes: Manifest, opts: StartOptions = {}) { - const ctx = await ServerContext.fromManifest(routes, opts); + const ctx = await ServerContext.fromManifest(routes, { + ...opts, + skipSnapshot: false, + dev: false, + }); await startFromContext(ctx, opts); } diff --git a/src/server/types.ts b/src/server/types.ts index 2f8598ed..4452a139 100644 --- a/src/server/types.ts +++ b/src/server/types.ts @@ -1,18 +1,59 @@ import { ComponentChildren, ComponentType, VNode } from "preact"; import * as router from "./router.ts"; import { InnerRenderFunction, RenderContext } from "./render.ts"; +import { Manifest } from "./mod.ts"; + +export interface DenoConfig { + imports?: Record; + importMap?: string; + tasks?: Record; + lint?: { + rules: { tags?: string[] }; + exclude?: string[]; + }; + fmt?: { + exclude?: string[]; + }; + exclude?: string[]; + compilerOptions?: { + jsx?: string; + jsxImportSource?: string; + }; +} // --- APPLICATION CONFIGURATION --- export type StartOptions = Partial & FreshOptions; export interface FreshOptions { + build?: { + /** + * The directory to write generated files to when `dev.ts build` is run. + * This can be an absolute path, a file URL or a relative path. + */ + outDir?: string; + }; render?: RenderFunction; plugins?: Plugin[]; staticDir?: string; router?: RouterOptions; } +export interface InternalFreshOptions { + dev: boolean; + loadSnapshot: boolean; + denoJsonPath: string; + denoJson: DenoConfig; + manifest: Manifest; + build: { + outDir: string; + }; + render?: RenderFunction; + plugins: Plugin[]; + staticDir: string; + router?: RouterOptions; +} + export interface RouterOptions { /** * Controls whether Fresh will append a trailing slash to the URL. diff --git a/tests/build_test.ts b/tests/build_test.ts index 9b10206e..60af436c 100644 --- a/tests/build_test.ts +++ b/tests/build_test.ts @@ -1,38 +1,49 @@ import * as path from "$std/path/mod.ts"; import { puppeteer } from "./deps.ts"; import { assert } from "$std/_util/asserts.ts"; -import { startFreshServer, waitForText } from "$fresh/tests/test_utils.ts"; +import { + getStdOutput, + 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"; +function runBuild(fixture: string, subDirPath: string, outDir: string) { + return new Deno.Command(Deno.execPath(), { + args: [ + "run", + "-A", + path.join(fixture, subDirPath, "dev.ts"), + "build", + ], + env: { + GITHUB_SHA: "__BUILD_ID__", + DENO_DEPLOYMENT_ID: "__BUILD_ID__", + FRESH_TEST_OUTDIR: outDir, + }, + stdin: "null", + stdout: "piped", + stderr: "piped", + }).output(); +} + async function testBuild( t: Deno.TestContext, fixture: string, - subDirPath = "", + options: { + subDirPath?: string; + outDir?: string; + } = {}, ) { - const outDir = path.join(fixture, subDirPath, "_fresh"); + const subDirPath = options.subDirPath ?? ""; + const outDir = options.outDir ?? path.join(fixture, subDirPath, "_fresh"); try { await t.step("build snapshot", async () => { - const res = await new Deno.Command(Deno.execPath(), { - args: [ - "run", - "-A", - path.join(fixture, subDirPath, "dev.ts"), - "build", - ], - env: { - GITHUB_SHA: "__BUILD_ID__", - DENO_DEPLOYMENT_ID: "__BUILD_ID__", - }, - stdin: "null", - stdout: "piped", - stderr: "inherit", - }).output(); - - const decoder = new TextDecoder(); - const stdout = decoder.decode(res.stdout); + const res = await runBuild(fixture, subDirPath, outDir); + const { stdout } = getStdOutput(res); assert( !/Using snapshot found at/.test(stdout), "Using snapshot message was shown during build", @@ -161,5 +172,60 @@ Deno.test("build snapshot and restore from it", async (t) => { Deno.test("build snapshot and restore from it when has sub dirs", async (t) => { const fixture = path.join(Deno.cwd(), "tests", "fixture_build_sub_dir"); - await testBuild(t, fixture, "src"); + await testBuild(t, fixture, { subDirPath: "src" }); }); + +Deno.test( + "build snapshot with custom build.outDir", + async (t) => { + async function assertOutputDir(outDir: string, out: Deno.CommandOutput) { + const { stdout, stderr } = getStdOutput(out); + + const msg = + `Missing output directory: ${outDir}\n\nCLI output:\n${stdout}\n${stderr}`; + + const dir: string | URL = outDir.startsWith("file://") + ? new URL(outDir) + : outDir; + try { + assert((await Deno.stat(dir)).isDirectory, msg); + } catch (err) { + throw new Error(msg, { cause: err }); + } + } + + await t.step("uses on relative outDir", async () => { + const fixture = path.join(Deno.cwd(), "tests", "fixture_build_out_dir"); + const out = await runBuild(fixture, "", "./tmp/asdf"); + const outDir = path.join(fixture, "tmp", "asdf"); + + await assertOutputDir(outDir, out); + }); + + await t.step("uses absolute outDir", async () => { + const fixture = path.join( + Deno.cwd(), + "tests", + "fixture_build_out_dir_sub", + ); + + const outDir = path.join(fixture, "tmp"); + const out = await runBuild(fixture, "src", outDir); + + await assertOutputDir(outDir, out); + }); + + await t.step("uses file:// outDir", async () => { + const fixture = path.join( + Deno.cwd(), + "tests", + "fixture_build_out_dir_sub2", + ); + + const outDirPath = path.join(fixture, "tmp"); + const outDir = path.toFileUrl(outDirPath).href; + const out = await runBuild(fixture, "src", outDir); + await assertOutputDir(outDir, out); + }); + }, +); diff --git a/tests/dev_command_test.ts b/tests/dev_command_test.ts index 03f88ea6..e7acb29a 100644 --- a/tests/dev_command_test.ts +++ b/tests/dev_command_test.ts @@ -53,20 +53,19 @@ Deno.test("adds refresh script to html", async () => { }); Deno.test("preact/debug is active in dev mode", async () => { - await withPageName( + await withFakeServe( "./tests/fixture_render_error/dev.ts", - async (page, address) => { + async (server) => { // SSR error is shown - const resp = await fetch(address); + const resp = await server.get("/"); const text = await resp.text(); assertEquals(resp.status, Status.InternalServerError); assertStringIncludes(text, "Objects are not valid as a child"); - await page.goto(address); + const html = await server.getHtml("/"); // Error page is shown with error message - const el = await page.waitForSelector(".frsh-error-page"); - const text2 = await page.evaluate((el) => el.textContent, el); + const text2 = html.querySelector(".frsh-error-page")!.textContent!; assertStringIncludes(text2, "Objects are not valid as a child"); }, ); diff --git a/tests/fixture_build_out_dir/deno.json b/tests/fixture_build_out_dir/deno.json new file mode 100644 index 00000000..9d782057 --- /dev/null +++ b/tests/fixture_build_out_dir/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.0", + "@preact/signals": "https://esm.sh/*@preact/signals@1.1.3", + "@preact/signals-core": "https://esm.sh/@preact/signals-core@1.2.3" + }, + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "preact" + } +} diff --git a/tests/fixture_build_out_dir/dev.ts b/tests/fixture_build_out_dir/dev.ts new file mode 100755 index 00000000..f2ab753b --- /dev/null +++ b/tests/fixture_build_out_dir/dev.ts @@ -0,0 +1,9 @@ +#!/usr/bin/env -S deno run -A --watch=static/,routes/ + +import dev from "$fresh/dev.ts"; + +await dev(import.meta.url, "./main.ts", { + build: { + outDir: Deno.env.get("FRESH_TEST_OUTDIR") ?? undefined, + }, +}); diff --git a/tests/fixture_build_out_dir/fresh.gen.ts b/tests/fixture_build_out_dir/fresh.gen.ts new file mode 100644 index 00000000..fa16c42d --- /dev/null +++ b/tests/fixture_build_out_dir/fresh.gen.ts @@ -0,0 +1,18 @@ +// 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 $$0 from "./islands/Counter.tsx"; + +const manifest = { + routes: { + "./routes/index.tsx": $0, + }, + islands: { + "./islands/Counter.tsx": $$0, + }, + baseUrl: import.meta.url, +}; + +export default manifest; diff --git a/tests/fixture_build_out_dir/islands/Counter.tsx b/tests/fixture_build_out_dir/islands/Counter.tsx new file mode 100644 index 00000000..5f015b1e --- /dev/null +++ b/tests/fixture_build_out_dir/islands/Counter.tsx @@ -0,0 +1,22 @@ +import type { Signal } from "@preact/signals"; +import { IS_BROWSER } from "$fresh/runtime.ts"; + +interface CounterProps { + count: Signal; + id: string; +} + +export default function Counter(props: CounterProps) { + return ( +
+

{props.count}

+ +
+ ); +} diff --git a/tests/fixture_build_out_dir/main.ts b/tests/fixture_build_out_dir/main.ts new file mode 100644 index 00000000..bb97cc80 --- /dev/null +++ b/tests/fixture_build_out_dir/main.ts @@ -0,0 +1,10 @@ +/// +/// +/// +/// +/// + +import { start } from "$fresh/server.ts"; +import routes from "./fresh.gen.ts"; + +await start(routes); diff --git a/tests/fixture_build_out_dir/routes/index.tsx b/tests/fixture_build_out_dir/routes/index.tsx new file mode 100644 index 00000000..7473a787 --- /dev/null +++ b/tests/fixture_build_out_dir/routes/index.tsx @@ -0,0 +1,15 @@ +import { useSignal } from "@preact/signals"; +import Counter from "../islands/Counter.tsx"; +import { asset, Head } from "$fresh/runtime.ts"; + +export default function Home() { + const signal = useSignal(0); + return ( +
+ + + + +
+ ); +} diff --git a/tests/fixture_build_out_dir_sub/deno.json b/tests/fixture_build_out_dir_sub/deno.json new file mode 100644 index 00000000..9d782057 --- /dev/null +++ b/tests/fixture_build_out_dir_sub/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.0", + "@preact/signals": "https://esm.sh/*@preact/signals@1.1.3", + "@preact/signals-core": "https://esm.sh/@preact/signals-core@1.2.3" + }, + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "preact" + } +} diff --git a/tests/fixture_build_out_dir_sub/src/dev.ts b/tests/fixture_build_out_dir_sub/src/dev.ts new file mode 100755 index 00000000..f2ab753b --- /dev/null +++ b/tests/fixture_build_out_dir_sub/src/dev.ts @@ -0,0 +1,9 @@ +#!/usr/bin/env -S deno run -A --watch=static/,routes/ + +import dev from "$fresh/dev.ts"; + +await dev(import.meta.url, "./main.ts", { + build: { + outDir: Deno.env.get("FRESH_TEST_OUTDIR") ?? undefined, + }, +}); diff --git a/tests/fixture_build_out_dir_sub/src/fresh.gen.ts b/tests/fixture_build_out_dir_sub/src/fresh.gen.ts new file mode 100644 index 00000000..fa16c42d --- /dev/null +++ b/tests/fixture_build_out_dir_sub/src/fresh.gen.ts @@ -0,0 +1,18 @@ +// 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 $$0 from "./islands/Counter.tsx"; + +const manifest = { + routes: { + "./routes/index.tsx": $0, + }, + islands: { + "./islands/Counter.tsx": $$0, + }, + baseUrl: import.meta.url, +}; + +export default manifest; diff --git a/tests/fixture_build_out_dir_sub/src/islands/Counter.tsx b/tests/fixture_build_out_dir_sub/src/islands/Counter.tsx new file mode 100644 index 00000000..5f015b1e --- /dev/null +++ b/tests/fixture_build_out_dir_sub/src/islands/Counter.tsx @@ -0,0 +1,22 @@ +import type { Signal } from "@preact/signals"; +import { IS_BROWSER } from "$fresh/runtime.ts"; + +interface CounterProps { + count: Signal; + id: string; +} + +export default function Counter(props: CounterProps) { + return ( +
+

{props.count}

+ +
+ ); +} diff --git a/tests/fixture_build_out_dir_sub/src/main.ts b/tests/fixture_build_out_dir_sub/src/main.ts new file mode 100644 index 00000000..bb97cc80 --- /dev/null +++ b/tests/fixture_build_out_dir_sub/src/main.ts @@ -0,0 +1,10 @@ +/// +/// +/// +/// +/// + +import { start } from "$fresh/server.ts"; +import routes from "./fresh.gen.ts"; + +await start(routes); diff --git a/tests/fixture_build_out_dir_sub/src/routes/index.tsx b/tests/fixture_build_out_dir_sub/src/routes/index.tsx new file mode 100644 index 00000000..7473a787 --- /dev/null +++ b/tests/fixture_build_out_dir_sub/src/routes/index.tsx @@ -0,0 +1,15 @@ +import { useSignal } from "@preact/signals"; +import Counter from "../islands/Counter.tsx"; +import { asset, Head } from "$fresh/runtime.ts"; + +export default function Home() { + const signal = useSignal(0); + return ( +
+ + + + +
+ ); +} diff --git a/tests/fixture_build_out_dir_sub2/deno.json b/tests/fixture_build_out_dir_sub2/deno.json new file mode 100644 index 00000000..9d782057 --- /dev/null +++ b/tests/fixture_build_out_dir_sub2/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.0", + "@preact/signals": "https://esm.sh/*@preact/signals@1.1.3", + "@preact/signals-core": "https://esm.sh/@preact/signals-core@1.2.3" + }, + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "preact" + } +} diff --git a/tests/fixture_build_out_dir_sub2/src/dev.ts b/tests/fixture_build_out_dir_sub2/src/dev.ts new file mode 100755 index 00000000..f2ab753b --- /dev/null +++ b/tests/fixture_build_out_dir_sub2/src/dev.ts @@ -0,0 +1,9 @@ +#!/usr/bin/env -S deno run -A --watch=static/,routes/ + +import dev from "$fresh/dev.ts"; + +await dev(import.meta.url, "./main.ts", { + build: { + outDir: Deno.env.get("FRESH_TEST_OUTDIR") ?? undefined, + }, +}); diff --git a/tests/fixture_build_out_dir_sub2/src/fresh.gen.ts b/tests/fixture_build_out_dir_sub2/src/fresh.gen.ts new file mode 100644 index 00000000..fa16c42d --- /dev/null +++ b/tests/fixture_build_out_dir_sub2/src/fresh.gen.ts @@ -0,0 +1,18 @@ +// 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 $$0 from "./islands/Counter.tsx"; + +const manifest = { + routes: { + "./routes/index.tsx": $0, + }, + islands: { + "./islands/Counter.tsx": $$0, + }, + baseUrl: import.meta.url, +}; + +export default manifest; diff --git a/tests/fixture_build_out_dir_sub2/src/islands/Counter.tsx b/tests/fixture_build_out_dir_sub2/src/islands/Counter.tsx new file mode 100644 index 00000000..5f015b1e --- /dev/null +++ b/tests/fixture_build_out_dir_sub2/src/islands/Counter.tsx @@ -0,0 +1,22 @@ +import type { Signal } from "@preact/signals"; +import { IS_BROWSER } from "$fresh/runtime.ts"; + +interface CounterProps { + count: Signal; + id: string; +} + +export default function Counter(props: CounterProps) { + return ( +
+

{props.count}

+ +
+ ); +} diff --git a/tests/fixture_build_out_dir_sub2/src/main.ts b/tests/fixture_build_out_dir_sub2/src/main.ts new file mode 100644 index 00000000..bb97cc80 --- /dev/null +++ b/tests/fixture_build_out_dir_sub2/src/main.ts @@ -0,0 +1,10 @@ +/// +/// +/// +/// +/// + +import { start } from "$fresh/server.ts"; +import routes from "./fresh.gen.ts"; + +await start(routes); diff --git a/tests/fixture_build_out_dir_sub2/src/routes/index.tsx b/tests/fixture_build_out_dir_sub2/src/routes/index.tsx new file mode 100644 index 00000000..7473a787 --- /dev/null +++ b/tests/fixture_build_out_dir_sub2/src/routes/index.tsx @@ -0,0 +1,15 @@ +import { useSignal } from "@preact/signals"; +import Counter from "../islands/Counter.tsx"; +import { asset, Head } from "$fresh/runtime.ts"; + +export default function Home() { + const signal = useSignal(0); + return ( +
+ + + + +
+ ); +} diff --git a/tests/plugin_test.ts b/tests/plugin_test.ts index 340331f2..498057f0 100644 --- a/tests/plugin_test.ts +++ b/tests/plugin_test.ts @@ -133,10 +133,9 @@ Deno.test({ Deno.test("calls buildStart() and buildEnd()", async () => { const result = await runBuild("./tests/fixture_plugin_lifecycle/dev.ts"); - let out = result.stdout.split("\n"); - const idx = out.findIndex((line) => line.startsWith("Plugin")); - const idxEnd = out.findLastIndex((line) => line.startsWith("Plugin")); - out = out.slice(idx, idxEnd + 1); + const out = result.stdout.split("\n").filter((line) => + line.startsWith("Plugin") + ); assertEquals(out, [ "Plugin a: buildStart",