feat: add build.outDir option (#1797)
This commit is contained in:
@@ -1 +1,2 @@
|
||||
_fresh/
|
||||
tmp/
|
||||
|
||||
@@ -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": {
|
||||
|
||||
+17
-19
@@ -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?.()));
|
||||
}
|
||||
|
||||
+19
-24
@@ -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
|
||||
|
||||
@@ -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<InternalFreshOptions> {
|
||||
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;
|
||||
}
|
||||
+85
-132
@@ -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,95 +89,15 @@ export type FromManifestOptions = FreshOptions & {
|
||||
dev?: boolean;
|
||||
};
|
||||
|
||||
export class ServerContext {
|
||||
#dev: boolean;
|
||||
#routes: Route[];
|
||||
#islands: Island[];
|
||||
#staticFiles: StaticFile[];
|
||||
#renderFn: RenderFunction;
|
||||
#middlewares: MiddlewareRoute[];
|
||||
#app: AppModule;
|
||||
#layouts: LayoutRoute[];
|
||||
#notFound: UnknownPage;
|
||||
#error: ErrorPage;
|
||||
#plugins: Plugin[];
|
||||
#builder: Builder | Promise<BuildSnapshot> | BuildSnapshot;
|
||||
#routerOptions: RouterOptions;
|
||||
|
||||
constructor(
|
||||
routes: Route[],
|
||||
islands: Island[],
|
||||
staticFiles: StaticFile[],
|
||||
renderfn: RenderFunction,
|
||||
middlewares: MiddlewareRoute[],
|
||||
app: AppModule,
|
||||
layouts: LayoutRoute[],
|
||||
notFound: UnknownPage,
|
||||
error: ErrorPage,
|
||||
plugins: Plugin[],
|
||||
configPath: string,
|
||||
jsxConfig: JSXConfig,
|
||||
dev: boolean,
|
||||
routerOptions: RouterOptions,
|
||||
snapshot: BuildSnapshot | null = null,
|
||||
) {
|
||||
this.#routes = routes;
|
||||
this.#islands = islands;
|
||||
this.#staticFiles = staticFiles;
|
||||
this.#renderFn = renderfn;
|
||||
this.#middlewares = middlewares;
|
||||
this.#app = app;
|
||||
this.#layouts = layouts;
|
||||
this.#notFound = notFound;
|
||||
this.#error = error;
|
||||
this.#plugins = plugins;
|
||||
this.#dev = dev;
|
||||
this.#builder = snapshot ?? new EsbuildBuilder({
|
||||
buildID: BUILD_ID,
|
||||
entrypoints: collectEntrypoints(this.#dev, this.#islands, this.#plugins),
|
||||
configPath,
|
||||
dev: this.#dev,
|
||||
jsxConfig,
|
||||
});
|
||||
this.#routerOptions = routerOptions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process the manifest into individual components and pages.
|
||||
*/
|
||||
static async fromManifest(
|
||||
manifest: Manifest,
|
||||
opts: FromManifestOptions,
|
||||
): Promise<ServerContext> {
|
||||
const dev = Deno.env.get("__FRSH_LEGACY_DEV") === "true" ||
|
||||
Boolean(opts.dev);
|
||||
setDevMode(dev);
|
||||
|
||||
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;
|
||||
|
||||
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.",
|
||||
);
|
||||
}
|
||||
|
||||
// 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",
|
||||
);
|
||||
if (opts.loadSnapshot) {
|
||||
const snapshotDirPath = opts.build.outDir;
|
||||
try {
|
||||
if ((await Deno.stat(snapshotDirPath)).isDirectory) {
|
||||
console.log(
|
||||
@@ -411,11 +324,8 @@ export class ServerContext {
|
||||
|
||||
const staticFiles: StaticFile[] = [];
|
||||
try {
|
||||
const staticFolder = new URL(
|
||||
opts.staticDir ?? "./static",
|
||||
manifest.baseUrl,
|
||||
);
|
||||
const entries = walk(fromFileUrl(staticFolder), {
|
||||
const staticDirUrl = toFileUrl(opts.staticDir);
|
||||
const entries = walk(opts.staticDir, {
|
||||
includeFiles: true,
|
||||
includeDirs: false,
|
||||
followSymlinks: false,
|
||||
@@ -423,7 +333,7 @@ export class ServerContext {
|
||||
const encoder = new TextEncoder();
|
||||
for await (const entry of entries) {
|
||||
const localUrl = toFileUrl(entry.path);
|
||||
const path = localUrl.href.substring(staticFolder.href.length);
|
||||
const path = localUrl.href.substring(staticDirUrl.href.length);
|
||||
const stat = await Deno.stat(localUrl);
|
||||
const contentType = typeByExtension(extname(path)) ??
|
||||
"application/octet-stream";
|
||||
@@ -452,7 +362,7 @@ export class ServerContext {
|
||||
}
|
||||
}
|
||||
|
||||
if (dev) {
|
||||
if (opts.dev) {
|
||||
// Ensure that debugging hooks are set up for SSR rendering
|
||||
await import("preact/debug");
|
||||
}
|
||||
@@ -470,12 +380,85 @@ export class ServerContext {
|
||||
opts.plugins ?? [],
|
||||
configPath,
|
||||
jsxConfig,
|
||||
dev,
|
||||
opts.dev,
|
||||
opts.router ?? DEFAULT_ROUTER_OPTIONS,
|
||||
snapshot,
|
||||
);
|
||||
}
|
||||
|
||||
export class ServerContext {
|
||||
#dev: boolean;
|
||||
#routes: Route[];
|
||||
#islands: Island[];
|
||||
#staticFiles: StaticFile[];
|
||||
#renderFn: RenderFunction;
|
||||
#middlewares: MiddlewareRoute[];
|
||||
#app: AppModule;
|
||||
#layouts: LayoutRoute[];
|
||||
#notFound: UnknownPage;
|
||||
#error: ErrorPage;
|
||||
#plugins: Plugin[];
|
||||
#builder: Builder | Promise<BuildSnapshot> | BuildSnapshot;
|
||||
#routerOptions: RouterOptions;
|
||||
|
||||
constructor(
|
||||
routes: Route[],
|
||||
islands: Island[],
|
||||
staticFiles: StaticFile[],
|
||||
renderfn: RenderFunction,
|
||||
middlewares: MiddlewareRoute[],
|
||||
app: AppModule,
|
||||
layouts: LayoutRoute[],
|
||||
notFound: UnknownPage,
|
||||
error: ErrorPage,
|
||||
plugins: Plugin[],
|
||||
configPath: string,
|
||||
jsxConfig: JSXConfig,
|
||||
dev: boolean,
|
||||
routerOptions: RouterOptions,
|
||||
snapshot: BuildSnapshot | null = null,
|
||||
) {
|
||||
this.#routes = routes;
|
||||
this.#islands = islands;
|
||||
this.#staticFiles = staticFiles;
|
||||
this.#renderFn = renderfn;
|
||||
this.#middlewares = middlewares;
|
||||
this.#app = app;
|
||||
this.#layouts = layouts;
|
||||
this.#notFound = notFound;
|
||||
this.#error = error;
|
||||
this.#plugins = plugins;
|
||||
this.#dev = dev;
|
||||
this.#builder = snapshot ?? new EsbuildBuilder({
|
||||
buildID: BUILD_ID,
|
||||
entrypoints: collectEntrypoints(this.#dev, this.#islands, this.#plugins),
|
||||
configPath,
|
||||
dev: this.#dev,
|
||||
jsxConfig,
|
||||
});
|
||||
this.#routerOptions = routerOptions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process the manifest into individual components and pages.
|
||||
*/
|
||||
static async fromManifest(
|
||||
manifest: Manifest,
|
||||
opts: FromManifestOptions,
|
||||
): Promise<ServerContext> {
|
||||
const isLegacyDev = Deno.env.get("__FRSH_LEGACY_DEV") === "true";
|
||||
const dev = isLegacyDev ||
|
||||
Boolean(opts.dev);
|
||||
setDevMode(dev);
|
||||
|
||||
if (isLegacyDev) {
|
||||
opts.skipSnapshot = true;
|
||||
}
|
||||
|
||||
const config = await getFreshConfigWithDefaults(manifest, opts);
|
||||
return getServerContext(config);
|
||||
}
|
||||
|
||||
/**
|
||||
* This functions returns a request handler that handles all routes required
|
||||
* by Fresh, including static files.
|
||||
@@ -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("/") ? "/" : "";
|
||||
|
||||
@@ -3,6 +3,7 @@ export {
|
||||
dirname,
|
||||
extname,
|
||||
fromFileUrl,
|
||||
isAbsolute,
|
||||
join,
|
||||
toFileUrl,
|
||||
} from "https://deno.land/std@0.193.0/path/mod.ts";
|
||||
|
||||
+6
-19
@@ -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<string, string>;
|
||||
importMap?: string;
|
||||
tasks?: Record<string, string>;
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -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<string, string>;
|
||||
importMap?: string;
|
||||
tasks?: Record<string, string>;
|
||||
lint?: {
|
||||
rules: { tags?: string[] };
|
||||
exclude?: string[];
|
||||
};
|
||||
fmt?: {
|
||||
exclude?: string[];
|
||||
};
|
||||
exclude?: string[];
|
||||
compilerOptions?: {
|
||||
jsx?: string;
|
||||
jsxImportSource?: string;
|
||||
};
|
||||
}
|
||||
|
||||
// --- APPLICATION CONFIGURATION ---
|
||||
|
||||
export type StartOptions = Partial<Deno.ServeTlsOptions> & 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.
|
||||
|
||||
+81
-15
@@ -1,21 +1,17 @@
|
||||
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";
|
||||
|
||||
async function testBuild(
|
||||
t: Deno.TestContext,
|
||||
fixture: string,
|
||||
subDirPath = "",
|
||||
) {
|
||||
const outDir = path.join(fixture, subDirPath, "_fresh");
|
||||
|
||||
try {
|
||||
await t.step("build snapshot", async () => {
|
||||
const res = await new Deno.Command(Deno.execPath(), {
|
||||
function runBuild(fixture: string, subDirPath: string, outDir: string) {
|
||||
return new Deno.Command(Deno.execPath(), {
|
||||
args: [
|
||||
"run",
|
||||
"-A",
|
||||
@@ -25,14 +21,29 @@ async function testBuild(
|
||||
env: {
|
||||
GITHUB_SHA: "__BUILD_ID__",
|
||||
DENO_DEPLOYMENT_ID: "__BUILD_ID__",
|
||||
FRESH_TEST_OUTDIR: outDir,
|
||||
},
|
||||
stdin: "null",
|
||||
stdout: "piped",
|
||||
stderr: "inherit",
|
||||
stderr: "piped",
|
||||
}).output();
|
||||
}
|
||||
|
||||
const decoder = new TextDecoder();
|
||||
const stdout = decoder.decode(res.stdout);
|
||||
async function testBuild(
|
||||
t: Deno.TestContext,
|
||||
fixture: string,
|
||||
options: {
|
||||
subDirPath?: string;
|
||||
outDir?: string;
|
||||
} = {},
|
||||
) {
|
||||
const subDirPath = options.subDirPath ?? "";
|
||||
const outDir = options.outDir ?? path.join(fixture, subDirPath, "_fresh");
|
||||
|
||||
try {
|
||||
await t.step("build snapshot", async () => {
|
||||
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);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
@@ -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");
|
||||
},
|
||||
);
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
Executable
+9
@@ -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,
|
||||
},
|
||||
});
|
||||
@@ -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;
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { Signal } from "@preact/signals";
|
||||
import { IS_BROWSER } from "$fresh/runtime.ts";
|
||||
|
||||
interface CounterProps {
|
||||
count: Signal<number>;
|
||||
id: string;
|
||||
}
|
||||
|
||||
export default function Counter(props: CounterProps) {
|
||||
return (
|
||||
<div id={props.id}>
|
||||
<p>{props.count}</p>
|
||||
<button
|
||||
id={`b-${props.id}`}
|
||||
onClick={() => props.count.value += 1}
|
||||
disabled={!IS_BROWSER}
|
||||
>
|
||||
+1
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/// <reference no-default-lib="true" />
|
||||
/// <reference lib="dom" />
|
||||
/// <reference lib="dom.iterable" />
|
||||
/// <reference lib="dom.asynciterable" />
|
||||
/// <reference lib="deno.ns" />
|
||||
|
||||
import { start } from "$fresh/server.ts";
|
||||
import routes from "./fresh.gen.ts";
|
||||
|
||||
await start(routes);
|
||||
@@ -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 (
|
||||
<div>
|
||||
<Head>
|
||||
<link rel="stylesheet" href={asset("/style.css")} />
|
||||
</Head>
|
||||
<Counter id="counter" count={signal} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
Executable
+9
@@ -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,
|
||||
},
|
||||
});
|
||||
@@ -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;
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { Signal } from "@preact/signals";
|
||||
import { IS_BROWSER } from "$fresh/runtime.ts";
|
||||
|
||||
interface CounterProps {
|
||||
count: Signal<number>;
|
||||
id: string;
|
||||
}
|
||||
|
||||
export default function Counter(props: CounterProps) {
|
||||
return (
|
||||
<div id={props.id}>
|
||||
<p>{props.count}</p>
|
||||
<button
|
||||
id={`b-${props.id}`}
|
||||
onClick={() => props.count.value += 1}
|
||||
disabled={!IS_BROWSER}
|
||||
>
|
||||
+1
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/// <reference no-default-lib="true" />
|
||||
/// <reference lib="dom" />
|
||||
/// <reference lib="dom.iterable" />
|
||||
/// <reference lib="dom.asynciterable" />
|
||||
/// <reference lib="deno.ns" />
|
||||
|
||||
import { start } from "$fresh/server.ts";
|
||||
import routes from "./fresh.gen.ts";
|
||||
|
||||
await start(routes);
|
||||
@@ -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 (
|
||||
<div>
|
||||
<Head>
|
||||
<link rel="stylesheet" href={asset("/style.css")} />
|
||||
</Head>
|
||||
<Counter id="counter" count={signal} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
Executable
+9
@@ -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,
|
||||
},
|
||||
});
|
||||
@@ -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;
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { Signal } from "@preact/signals";
|
||||
import { IS_BROWSER } from "$fresh/runtime.ts";
|
||||
|
||||
interface CounterProps {
|
||||
count: Signal<number>;
|
||||
id: string;
|
||||
}
|
||||
|
||||
export default function Counter(props: CounterProps) {
|
||||
return (
|
||||
<div id={props.id}>
|
||||
<p>{props.count}</p>
|
||||
<button
|
||||
id={`b-${props.id}`}
|
||||
onClick={() => props.count.value += 1}
|
||||
disabled={!IS_BROWSER}
|
||||
>
|
||||
+1
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/// <reference no-default-lib="true" />
|
||||
/// <reference lib="dom" />
|
||||
/// <reference lib="dom.iterable" />
|
||||
/// <reference lib="dom.asynciterable" />
|
||||
/// <reference lib="deno.ns" />
|
||||
|
||||
import { start } from "$fresh/server.ts";
|
||||
import routes from "./fresh.gen.ts";
|
||||
|
||||
await start(routes);
|
||||
@@ -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 (
|
||||
<div>
|
||||
<Head>
|
||||
<link rel="stylesheet" href={asset("/style.css")} />
|
||||
</Head>
|
||||
<Counter id="counter" count={signal} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
Reference in New Issue
Block a user