feat: pass resolved config to plugin.buildStart() (#1961)

This commit is contained in:
Marvin Hagemeister
2023-10-19 17:25:16 +02:00
committed by GitHub
parent c41cfc9227
commit cbd5b842b0
7 changed files with 85 additions and 61 deletions
+13 -10
View File
@@ -3,18 +3,21 @@ import { join } from "../server/deps.ts";
import { colors, fs } from "./deps.ts"; import { colors, fs } from "./deps.ts";
import { BuildSnapshotJson } from "../build/mod.ts"; import { BuildSnapshotJson } from "../build/mod.ts";
import { BUILD_ID } from "../server/build_id.ts"; import { BUILD_ID } from "../server/build_id.ts";
import { InternalFreshConfig } from "../server/types.ts"; import { InternalFreshState } from "../server/types.ts";
export async function build( export async function build(
config: InternalFreshConfig, state: InternalFreshState,
) { ) {
// Ensure that build dir is empty const outDir = state.config.build.outDir;
await fs.emptyDir(config.build.outDir); const plugins = state.config.plugins;
await Promise.all(config.plugins.map((plugin) => plugin.buildStart?.())); // Ensure that build dir is empty
await fs.emptyDir(outDir);
await Promise.all(plugins.map((plugin) => plugin.buildStart?.(state.config)));
// Bundle assets // Bundle assets
const ctx = await getServerContext(config); const ctx = await getServerContext(state);
const snapshot = await ctx.buildSnapshot(); const snapshot = await ctx.buildSnapshot();
// Write output files to disk // Write output files to disk
@@ -22,7 +25,7 @@ export async function build(
const data = await snapshot.read(fileName); const data = await snapshot.read(fileName);
if (data === null) return; if (data === null) return;
return Deno.writeFile(join(config.build.outDir, fileName), data); return Deno.writeFile(join(outDir, fileName), data);
})); }));
// Write dependency snapshot file to disk // Write dependency snapshot file to disk
@@ -35,12 +38,12 @@ export async function build(
jsonSnapshot.files[filePath] = dependencies; jsonSnapshot.files[filePath] = dependencies;
} }
const snapshotPath = join(config.build.outDir, "snapshot.json"); const snapshotPath = join(outDir, "snapshot.json");
await Deno.writeTextFile(snapshotPath, JSON.stringify(jsonSnapshot, null, 2)); await Deno.writeTextFile(snapshotPath, JSON.stringify(jsonSnapshot, null, 2));
console.log( console.log(
`Assets written to: ${colors.green(config.build.outDir)}`, `Assets written to: ${colors.green(outDir)}`,
); );
await Promise.all(config.plugins.map((plugin) => plugin.buildEnd?.())); await Promise.all(plugins.map((plugin) => plugin.buildEnd?.()));
} }
+10 -10
View File
@@ -4,7 +4,7 @@ import { FreshConfig, Manifest as ServerManifest } from "../server/mod.ts";
import { build } from "./build.ts"; import { build } from "./build.ts";
import { collect, ensureMinDenoVersion, generate, Manifest } from "./mod.ts"; import { collect, ensureMinDenoVersion, generate, Manifest } from "./mod.ts";
import { startServer } from "../server/boot.ts"; import { startServer } from "../server/boot.ts";
import { getFreshConfigWithDefaults } from "../server/config.ts"; import { getInternalFreshState } from "../server/config.ts";
import { getServerContext } from "$fresh/src/server/context.ts"; import { getServerContext } from "$fresh/src/server/context.ts";
export async function dev( export async function dev(
@@ -39,22 +39,22 @@ export async function dev(
.default as ServerManifest; .default as ServerManifest;
if (Deno.args.includes("build")) { if (Deno.args.includes("build")) {
const configWithDefaults = await getFreshConfigWithDefaults( const state = await getInternalFreshState(
manifest, manifest,
config ?? {}, config ?? {},
); );
configWithDefaults.dev = false; state.config.dev = false;
configWithDefaults.loadSnapshot = false; state.loadSnapshot = false;
await build(configWithDefaults); await build(state);
} else if (config) { } else if (config) {
const configWithDefaults = await getFreshConfigWithDefaults( const state = await getInternalFreshState(
manifest, manifest,
config, config,
); );
configWithDefaults.dev = true; state.config.dev = true;
configWithDefaults.loadSnapshot = false; state.loadSnapshot = false;
const ctx = await getServerContext(configWithDefaults); const ctx = await getServerContext(state);
await startServer(ctx.handler(), configWithDefaults.server); await startServer(ctx.handler(), state.config.server);
} else { } else {
// Legacy entry point: Back then `dev.ts` would call `main.ts` but // Legacy entry point: Back then `dev.ts` would call `main.ts` but
// this causes duplicate plugin instantiation if both `dev.ts` and // this causes duplicate plugin instantiation if both `dev.ts` and
+17 -11
View File
@@ -1,6 +1,10 @@
import { dirname, fromFileUrl, isAbsolute, join, JSONC } from "./deps.ts"; import { dirname, fromFileUrl, isAbsolute, join, JSONC } from "./deps.ts";
import { FromManifestConfig, Manifest } from "./mod.ts"; import { FromManifestConfig, Manifest } from "./mod.ts";
import { DenoConfig, InternalFreshConfig } from "./types.ts"; import {
DenoConfig,
InternalFreshState,
ResolvedFreshConfig,
} from "./types.ts";
export async function readDenoConfig( export async function readDenoConfig(
directory: string, directory: string,
@@ -37,10 +41,10 @@ function isObject(value: unknown) {
!Array.isArray(value); !Array.isArray(value);
} }
export async function getFreshConfigWithDefaults( export async function getInternalFreshState(
manifest: Manifest, manifest: Manifest,
config: FromManifestConfig, config: FromManifestConfig,
): Promise<InternalFreshConfig> { ): Promise<InternalFreshState> {
const base = dirname(fromFileUrl(manifest.baseUrl)); const base = dirname(fromFileUrl(manifest.baseUrl));
const { config: denoJson, path: denoJsonPath } = await readDenoConfig(base); const { config: denoJson, path: denoJsonPath } = await readDenoConfig(base);
@@ -50,14 +54,8 @@ export async function getFreshConfigWithDefaults(
); );
} }
const internalConfig: InternalFreshConfig = { const internalConfig: ResolvedFreshConfig = {
loadSnapshot: typeof config.skipSnapshot === "boolean"
? !config.skipSnapshot
: false,
dev: config.dev ?? false, dev: config.dev ?? false,
denoJsonPath,
denoJson,
manifest,
build: { build: {
outDir: "", outDir: "",
target: config.build?.target ?? ["chrome99", "firefox99", "safari15"], target: config.build?.target ?? ["chrome99", "firefox99", "safari15"],
@@ -102,7 +100,15 @@ export async function getFreshConfigWithDefaults(
? parseFileOrUrl(config.staticDir, base) ? parseFileOrUrl(config.staticDir, base)
: join(base, "static"); : join(base, "static");
return internalConfig; return {
config: internalConfig,
manifest,
loadSnapshot: typeof config.skipSnapshot === "boolean"
? !config.skipSnapshot
: false,
denoJsonPath,
denoJson,
};
} }
function parseFileOrUrl(input: string, base: string) { function parseFileOrUrl(input: string, base: string) {
+27 -26
View File
@@ -19,7 +19,7 @@ import {
ErrorPage, ErrorPage,
ErrorPageModule, ErrorPageModule,
Handler, Handler,
InternalFreshConfig, InternalFreshState,
Island, Island,
LayoutModule, LayoutModule,
LayoutRoute, LayoutRoute,
@@ -56,7 +56,7 @@ import {
import { InternalRoute } from "./router.ts"; import { InternalRoute } from "./router.ts";
import { setAllIslands } from "./rendering/preact_hooks.ts"; import { setAllIslands } from "./rendering/preact_hooks.ts";
import { getCodeFrame } from "./code_frame.ts"; import { getCodeFrame } from "./code_frame.ts";
import { getFreshConfigWithDefaults } from "./config.ts"; import { getInternalFreshState } from "./config.ts";
const DEFAULT_CONN_INFO: ServeHandlerInfo = { const DEFAULT_CONN_INFO: ServeHandlerInfo = {
localAddr: { transport: "tcp", hostname: "localhost", port: 8080 }, localAddr: { transport: "tcp", hostname: "localhost", port: 8080 },
@@ -88,15 +88,15 @@ export type FromManifestConfig = FreshConfig & {
dev?: boolean; dev?: boolean;
}; };
export async function getServerContext(opts: InternalFreshConfig) { export async function getServerContext(state: InternalFreshState) {
const { manifest, denoJson: config, denoJsonPath: configPath } = opts; const { manifest, config, denoJson, denoJsonPath: configPath } = state;
// Get the manifest' base URL. // Get the manifest' base URL.
const baseUrl = new URL("./", manifest.baseUrl).href; const baseUrl = new URL("./", manifest.baseUrl).href;
// Restore snapshot if available // Restore snapshot if available
let snapshot: BuildSnapshot | null = null; let snapshot: BuildSnapshot | null = null;
if (opts.loadSnapshot) { if (state.loadSnapshot) {
const snapshotDirPath = opts.build.outDir; const snapshotDirPath = config.build.outDir;
try { try {
if ((await Deno.stat(snapshotDirPath)).isDirectory) { if ((await Deno.stat(snapshotDirPath)).isDirectory) {
console.log( console.log(
@@ -128,10 +128,10 @@ export async function getServerContext(opts: InternalFreshConfig) {
} }
} }
config.compilerOptions ??= {}; denoJson.compilerOptions ??= {};
let jsx: "react" | "react-jsx"; let jsx: "react" | "react-jsx";
switch (config.compilerOptions.jsx) { switch (denoJson.compilerOptions.jsx) {
case "react": case "react":
case undefined: case undefined:
jsx = "react"; jsx = "react";
@@ -140,12 +140,12 @@ export async function getServerContext(opts: InternalFreshConfig) {
jsx = "react-jsx"; jsx = "react-jsx";
break; break;
default: default:
throw new Error("Unknown jsx option: " + config.compilerOptions.jsx); throw new Error("Unknown jsx option: " + denoJson.compilerOptions.jsx);
} }
const jsxConfig: JSXConfig = { const jsxConfig: JSXConfig = {
jsx, jsx,
jsxImportSource: config.compilerOptions.jsxImportSource, jsxImportSource: denoJson.compilerOptions.jsxImportSource,
}; };
// Extract all routes, and prepare them into the `Page` structure. // Extract all routes, and prepare them into the `Page` structure.
@@ -158,8 +158,8 @@ export async function getServerContext(opts: InternalFreshConfig) {
let error: ErrorPage = DEFAULT_ERROR; let error: ErrorPage = DEFAULT_ERROR;
const allRoutes = [ const allRoutes = [
...Object.entries(manifest.routes), ...Object.entries(manifest.routes),
...(opts.plugins ? getMiddlewareRoutesFromPlugins(opts.plugins) : []), ...(config.plugins ? getMiddlewareRoutesFromPlugins(config.plugins) : []),
...(opts.plugins ? getRoutesFromPlugins(opts.plugins) : []), ...(config.plugins ? getRoutesFromPlugins(config.plugins) : []),
]; ];
// Presort all routes so that we only need to sort once // Presort all routes so that we only need to sort once
@@ -273,7 +273,8 @@ export async function getServerContext(opts: InternalFreshConfig) {
path === "/_500.tsx" || path === "/_500.ts" || path === "/_500.tsx" || path === "/_500.ts" ||
path === "/_500.jsx" || path === "/_500.js" path === "/_500.jsx" || path === "/_500.js"
) { ) {
const { default: component, config } = module as ErrorPageModule; const { default: component, config: routeConfig } =
module as ErrorPageModule;
let { handler } = module as ErrorPageModule; let { handler } = module as ErrorPageModule;
if (component && handler === undefined) { if (component && handler === undefined) {
handler = (_req, { render }) => render(); handler = (_req, { render }) => render();
@@ -286,7 +287,7 @@ export async function getServerContext(opts: InternalFreshConfig) {
name, name,
component, component,
handler: (req, ctx) => { handler: (req, ctx) => {
if (opts.dev) { if (config.dev) {
const prevComp = error.component; const prevComp = error.component;
error.component = DefaultErrorHandler; error.component = DefaultErrorHandler;
try { try {
@@ -300,9 +301,9 @@ export async function getServerContext(opts: InternalFreshConfig) {
? handler(req, ctx) ? handler(req, ctx)
: router.defaultErrorHandler(req, ctx, ctx.error); : router.defaultErrorHandler(req, ctx, ctx.error);
}, },
csp: Boolean(config?.csp ?? false), csp: Boolean(routeConfig?.csp ?? false),
appWrapper: !config?.skipAppWrapper, appWrapper: !routeConfig?.skipAppWrapper,
inheritLayouts: !config?.skipInheritedLayouts, inheritLayouts: !routeConfig?.skipInheritedLayouts,
}; };
} }
} }
@@ -336,8 +337,8 @@ export async function getServerContext(opts: InternalFreshConfig) {
const staticFiles: StaticFile[] = []; const staticFiles: StaticFile[] = [];
try { try {
const staticDirUrl = toFileUrl(opts.staticDir); const staticDirUrl = toFileUrl(config.staticDir);
const entries = walk(opts.staticDir, { const entries = walk(config.staticDir, {
includeFiles: true, includeFiles: true,
includeDirs: false, includeDirs: false,
followSymlinks: false, followSymlinks: false,
@@ -374,7 +375,7 @@ export async function getServerContext(opts: InternalFreshConfig) {
} }
} }
if (opts.dev) { if (config.dev) {
// Ensure that debugging hooks are set up for SSR rendering // Ensure that debugging hooks are set up for SSR rendering
await import("preact/debug"); await import("preact/debug");
} }
@@ -383,18 +384,18 @@ export async function getServerContext(opts: InternalFreshConfig) {
routes, routes,
islands, islands,
staticFiles, staticFiles,
opts.render ?? DEFAULT_RENDER_FN, config.render ?? DEFAULT_RENDER_FN,
middlewares, middlewares,
app, app,
layouts, layouts,
notFound, notFound,
error, error,
opts.plugins ?? [], config.plugins ?? [],
configPath, configPath,
jsxConfig, jsxConfig,
opts.dev, config.dev,
opts.router ?? DEFAULT_ROUTER_OPTIONS, config.router ?? DEFAULT_ROUTER_OPTIONS,
opts.build.target, config.build.target,
snapshot, snapshot,
); );
} }
@@ -470,7 +471,7 @@ export class ServerContext {
config.skipSnapshot = true; config.skipSnapshot = true;
} }
const configWithDefaults = await getFreshConfigWithDefaults( const configWithDefaults = await getInternalFreshState(
manifest, manifest,
config, config,
); );
+8 -4
View File
@@ -108,12 +108,16 @@ export interface FreshConfig {
onListen?: (params: { hostname: string; port: number }) => void; onListen?: (params: { hostname: string; port: number }) => void;
} }
export interface InternalFreshConfig { export interface InternalFreshState {
dev: boolean; config: ResolvedFreshConfig;
manifest: Manifest;
loadSnapshot: boolean; loadSnapshot: boolean;
denoJsonPath: string; denoJsonPath: string;
denoJson: DenoConfig; denoJson: DenoConfig;
manifest: Manifest; }
export interface ResolvedFreshConfig {
dev: boolean;
build: { build: {
outDir: string; outDir: string;
target: string | string[]; target: string | string[];
@@ -545,7 +549,7 @@ export interface Plugin<State = Record<string, unknown>> {
/** /**
* Called before running the Fresh build task * Called before running the Fresh build task
*/ */
buildStart?(): Promise<void> | void; buildStart?(config: ResolvedFreshConfig): Promise<void> | void;
/** /**
* Called after completing the Fresh build task * Called after completing the Fresh build task
*/ */
@@ -1,4 +1,5 @@
import { defineConfig } from "$fresh/src/server/defines.ts"; import { defineConfig } from "$fresh/src/server/defines.ts";
import * as path from "https://deno.land/std@0.193.0/path/mod.ts";
export default defineConfig({ export default defineConfig({
plugins: [ plugins: [
@@ -20,5 +21,12 @@ export default defineConfig({
console.log("Plugin b: buildStart"); console.log("Plugin b: buildStart");
}, },
}, },
{
name: "c",
buildStart(config) {
const outDir = path.relative(Deno.cwd(), config.build.outDir);
console.log(`Plugin c: ${outDir}`);
},
},
], ],
}); });
+2
View File
@@ -5,6 +5,7 @@ import {
assertEquals, assertEquals,
assertStringIncludes, assertStringIncludes,
delay, delay,
join,
puppeteer, puppeteer,
} from "./deps.ts"; } from "./deps.ts";
import manifest from "./fixture_plugin/fresh.gen.ts"; import manifest from "./fixture_plugin/fresh.gen.ts";
@@ -146,6 +147,7 @@ Deno.test("calls buildStart() and buildEnd()", async () => {
assertEquals(out, [ assertEquals(out, [
"Plugin a: buildStart", "Plugin a: buildStart",
"Plugin b: buildStart", "Plugin b: buildStart",
`Plugin c: ${join("tests", "fixture_plugin_lifecycle", "_fresh")}`,
"Plugin a: buildEnd", "Plugin a: buildEnd",
"Plugin b: buildEnd", "Plugin b: buildEnd",
]); ]);