This reverts commit a1571b76ed.
It broke fresh.deno.dev :S
This commit is contained in:
+4
-6
@@ -1,6 +1,6 @@
|
||||
import { trace } from "@opentelemetry/api";
|
||||
|
||||
import { DENO_DEPLOYMENT_ID } from "fresh/build-id";
|
||||
import { DENO_DEPLOYMENT_ID } from "./runtime/build_id.ts";
|
||||
import * as colors from "@std/fmt/colors";
|
||||
import {
|
||||
type MaybeLazyMiddleware,
|
||||
@@ -152,7 +152,6 @@ export let getBuildCache: <State>(app: App<State>) => BuildCache<State> | null;
|
||||
export let setBuildCache: <State>(
|
||||
app: App<State>,
|
||||
cache: BuildCache<State>,
|
||||
mode: "development" | "production",
|
||||
) => void;
|
||||
|
||||
/**
|
||||
@@ -165,9 +164,8 @@ export class App<State> {
|
||||
|
||||
static {
|
||||
getBuildCache = (app) => app.#getBuildCache();
|
||||
setBuildCache = (app, cache, mode: "development" | "production") => {
|
||||
setBuildCache = (app, cache) => {
|
||||
app.config.root = cache.root;
|
||||
app.config.mode = mode;
|
||||
app.#getBuildCache = () => cache;
|
||||
};
|
||||
}
|
||||
@@ -181,7 +179,7 @@ export class App<State> {
|
||||
this.config = {
|
||||
root: Deno.cwd(),
|
||||
basePath: config.basePath ?? "",
|
||||
mode: config.mode ?? "production",
|
||||
mode: "production",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -365,7 +363,7 @@ export class App<State> {
|
||||
`Could not find _fresh directory. Maybe you forgot to run "deno task build"?`,
|
||||
);
|
||||
} else {
|
||||
buildCache = new MockBuildCache([], this.config.mode);
|
||||
buildCache = new MockBuildCache([]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
-9
@@ -1,10 +1,10 @@
|
||||
import * as path from "@std/path";
|
||||
import { setBuildId } from "./runtime/build_id.ts";
|
||||
import type { Command } from "./commands.ts";
|
||||
import { fsItemsToCommands, type FsRouteFile } from "./fs_routes.ts";
|
||||
import type { ServerIslandRegistry } from "./context.ts";
|
||||
import type { AnyComponent } from "preact";
|
||||
import { UniqueNamer } from "./utils.ts";
|
||||
import { setBuildId } from "fresh/build-id";
|
||||
|
||||
export interface FileSnapshot {
|
||||
name: string;
|
||||
@@ -15,7 +15,6 @@ export interface FileSnapshot {
|
||||
|
||||
export interface BuildSnapshot<State> {
|
||||
version: string;
|
||||
clientEntry: string;
|
||||
fsRoutes: FsRouteFile<State>[];
|
||||
staticFiles: Map<string, FileSnapshot>;
|
||||
islands: ServerIslandRegistry;
|
||||
@@ -33,10 +32,6 @@ export interface StaticFile {
|
||||
export interface BuildCache<State = any> {
|
||||
root: string;
|
||||
islandRegistry: ServerIslandRegistry;
|
||||
clientEntry: string;
|
||||
features: {
|
||||
errorOverlay: boolean;
|
||||
};
|
||||
getFsRoutes(): Command<State>[];
|
||||
readFile(pathname: string): Promise<StaticFile | null>;
|
||||
}
|
||||
@@ -44,14 +39,11 @@ export interface BuildCache<State = any> {
|
||||
export class ProdBuildCache<State> implements BuildCache<State> {
|
||||
#snapshot: BuildSnapshot<State>;
|
||||
islandRegistry: ServerIslandRegistry;
|
||||
clientEntry: string;
|
||||
features = { errorOverlay: false };
|
||||
|
||||
constructor(public root: string, snapshot: BuildSnapshot<State>) {
|
||||
setBuildId(snapshot.version);
|
||||
this.#snapshot = snapshot;
|
||||
this.islandRegistry = snapshot.islands;
|
||||
this.clientEntry = snapshot.clientEntry;
|
||||
}
|
||||
|
||||
getFsRoutes(): Command<State>[] {
|
||||
|
||||
@@ -7,10 +7,6 @@ export interface FreshConfig {
|
||||
* @default undefined
|
||||
*/
|
||||
basePath?: string;
|
||||
/**
|
||||
* The mode Fresh can run in.
|
||||
*/
|
||||
mode?: "development" | "production";
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -296,3 +296,15 @@ export class Context<State> {
|
||||
return new Response(html, responseInit);
|
||||
}
|
||||
}
|
||||
|
||||
Object.defineProperties(Context.prototype, {
|
||||
config: { enumerable: true },
|
||||
url: { enumerable: true },
|
||||
req: { enumerable: true },
|
||||
params: { enumerable: true },
|
||||
state: { enumerable: true },
|
||||
data: { enumerable: true },
|
||||
error: { enumerable: true },
|
||||
next: { enumerable: true },
|
||||
info: { enumerable: true },
|
||||
});
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Context } from "./context.ts";
|
||||
import { App } from "fresh";
|
||||
import { asset } from "fresh/runtime";
|
||||
import { FakeServer } from "./test_utils.ts";
|
||||
import { BUILD_ID } from "fresh/build-id";
|
||||
import { BUILD_ID } from "./runtime/build_id.ts";
|
||||
import { parseHtml } from "../tests/test_utils.tsx";
|
||||
|
||||
Deno.test("FreshReqContext.prototype.redirect", () => {
|
||||
|
||||
+19
-17
@@ -24,7 +24,7 @@ import { automaticWorkspaceFolders } from "./middlewares/automatic_workspace_fol
|
||||
import { parseDirPath } from "../config.ts";
|
||||
import { pathToExportName, UniqueNamer } from "../utils.ts";
|
||||
import { checkDenoCompilerOptions } from "./check.ts";
|
||||
import { crawlFsItem } from "./fs_crawl.ts";
|
||||
import { crawlRouteDir, walkDir } from "./fs_crawl.ts";
|
||||
import { DAY } from "../constants.ts";
|
||||
|
||||
export interface BuildOptions {
|
||||
@@ -169,7 +169,7 @@ export class Builder<State = any> {
|
||||
|
||||
app.config.root = this.config.root;
|
||||
app.config.mode = "development";
|
||||
setBuildCache(app, buildCache, "development");
|
||||
setBuildCache(app, buildCache);
|
||||
|
||||
const appHandler = app.handler();
|
||||
|
||||
@@ -187,7 +187,7 @@ export class Builder<State = any> {
|
||||
devApp.config.root = this.config.root;
|
||||
devApp.config.mode = "development";
|
||||
|
||||
setBuildCache(devApp, buildCache, "development");
|
||||
setBuildCache(devApp, buildCache);
|
||||
|
||||
// Boot in parallel to spin up the server quicker. We'll hold
|
||||
// requests until the required assets are processed.
|
||||
@@ -248,24 +248,26 @@ export class Builder<State = any> {
|
||||
await buildCache.prepare();
|
||||
|
||||
return (app) => {
|
||||
setBuildCache(app, buildCache, app.config.mode);
|
||||
setBuildCache(app, buildCache);
|
||||
};
|
||||
}
|
||||
|
||||
async #crawlFsItems() {
|
||||
const { islands, routes } = await crawlFsItem(
|
||||
{
|
||||
islandDir: this.config.islandDir,
|
||||
routeDir: this.config.routeDir,
|
||||
ignore: this.config.ignore,
|
||||
},
|
||||
);
|
||||
|
||||
for (let i = 0; i < islands.length; i++) {
|
||||
this.registerIsland(islands[i]);
|
||||
}
|
||||
|
||||
this.#fsRoutes.files = routes;
|
||||
await Promise.all([
|
||||
walkDir(
|
||||
fsAdapter,
|
||||
this.config.islandDir,
|
||||
(entry) => this.registerIsland(entry.path),
|
||||
this.config.ignore,
|
||||
),
|
||||
crawlRouteDir(
|
||||
fsAdapter,
|
||||
this.config.routeDir,
|
||||
this.config.ignore,
|
||||
(entry) => this.registerIsland(entry),
|
||||
this.#fsRoutes.files,
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
async #build<T>(buildCache: DevBuildCache<T>, dev: boolean): Promise<void> {
|
||||
|
||||
@@ -3,7 +3,7 @@ import * as path from "@std/path";
|
||||
import { Builder, specToName } from "./builder.ts";
|
||||
import { App } from "../app.ts";
|
||||
import { DEV_ERROR_OVERLAY_URL } from "../constants.ts";
|
||||
import { BUILD_ID } from "fresh/build-id";
|
||||
import { BUILD_ID } from "../runtime/build_id.ts";
|
||||
import { withTmpDir, writeFiles } from "../test_utils.ts";
|
||||
import { withChildProcessServer } from "../../tests/test_utils.tsx";
|
||||
|
||||
@@ -64,7 +64,7 @@ Deno.test({
|
||||
await builder.build();
|
||||
|
||||
const snapshotJson = await Deno.readTextFile(
|
||||
path.join(tmp, "dist", "snapshot.js"),
|
||||
path.join(tmp, "dist", "static-files.json"),
|
||||
);
|
||||
expect(snapshotJson).toContain("/images/batman.svg");
|
||||
},
|
||||
|
||||
+120
-175
@@ -1,10 +1,11 @@
|
||||
import {
|
||||
type BuildCache,
|
||||
type FileSnapshot,
|
||||
IslandPreparer,
|
||||
type StaticFile,
|
||||
} from "../build_cache.ts";
|
||||
import * as path from "@std/path";
|
||||
import * as pathWin32 from "@std/path/windows";
|
||||
import { SEPARATOR as WINDOWS_SEPARATOR } from "@std/path/windows/constants";
|
||||
import { encodeHex } from "@std/encoding/hex";
|
||||
import { fsAdapter } from "../fs.ts";
|
||||
import type { FileTransformer } from "./file_transformer.ts";
|
||||
@@ -15,8 +16,6 @@ import type { Command } from "../commands.ts";
|
||||
import type { ServerIslandRegistry } from "../context.ts";
|
||||
import { contentType as getStdContentType } from "@std/media-types/content-type";
|
||||
|
||||
const WINDOWS_SEPARATOR = pathWin32.SEPARATOR;
|
||||
|
||||
export interface MemoryFile {
|
||||
hash: string | null;
|
||||
contentType: string;
|
||||
@@ -61,24 +60,16 @@ export class MemoryBuildCache<State> implements DevBuildCache<State> {
|
||||
#commands: Command<State>[] = [];
|
||||
root: string;
|
||||
islandRegistry: ServerIslandRegistry = new Map();
|
||||
clientEntry: string;
|
||||
features = { errorOverlay: false };
|
||||
|
||||
constructor(
|
||||
config: ResolvedBuildConfig,
|
||||
fsRoutes: FsRoute<State>,
|
||||
transformer: FileTransformer,
|
||||
) {
|
||||
if (config.mode === "development") {
|
||||
this.features.errorOverlay = true;
|
||||
}
|
||||
|
||||
this.#config = config;
|
||||
this.#fsRoutes = fsRoutes;
|
||||
this.#transformer = transformer;
|
||||
this.root = config.root;
|
||||
|
||||
this.clientEntry = getClientEntry(config.buildId);
|
||||
}
|
||||
|
||||
getFsRoutes(): Command<State>[] {
|
||||
@@ -229,17 +220,12 @@ export class DiskBuildCache<State> implements DevBuildCache<State> {
|
||||
#fsRoutes: FsRoute<State>;
|
||||
root: string;
|
||||
islandRegistry: ServerIslandRegistry = new Map();
|
||||
clientEntry: string = "";
|
||||
features = { errorOverlay: false };
|
||||
|
||||
constructor(
|
||||
config: ResolvedBuildConfig,
|
||||
fsRoutes: FsRoute<State>,
|
||||
transformer: FileTransformer,
|
||||
) {
|
||||
if (config.mode === "development") {
|
||||
this.features.errorOverlay = true;
|
||||
}
|
||||
this.#fsRoutes = fsRoutes;
|
||||
this.#transformer = transformer;
|
||||
this.#config = config;
|
||||
@@ -322,62 +308,155 @@ export class DiskBuildCache<State> implements DevBuildCache<State> {
|
||||
}
|
||||
}
|
||||
|
||||
const staticFiles: PendingStaticFile[] = [];
|
||||
const staticFiles = new Map<string, FileSnapshot>();
|
||||
for (const [name, filePath] of this.#unprocessedFiles.entries()) {
|
||||
staticFiles.push({ filePath, pathname: name, hash: null });
|
||||
const file = await Deno.open(filePath);
|
||||
const hash = await hashContent(file.readable);
|
||||
|
||||
staticFiles.set(name, {
|
||||
name,
|
||||
hash,
|
||||
filePath: path.relative(root, filePath),
|
||||
contentType: getContentType(filePath),
|
||||
});
|
||||
}
|
||||
|
||||
for (const [name, maybeHash] of this.#processedFiles.entries()) {
|
||||
let hash = maybeHash;
|
||||
|
||||
// Ignore esbuild meta file. It's not intended for serving
|
||||
if (name === "/metafile.json") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const filePath = path.join(outDir, "static", name);
|
||||
staticFiles.push({ filePath, pathname: name, hash: maybeHash });
|
||||
if (maybeHash === null) {
|
||||
const file = await Deno.open(filePath);
|
||||
hash = await hashContent(file.readable);
|
||||
}
|
||||
|
||||
staticFiles.set(name, {
|
||||
name,
|
||||
hash,
|
||||
filePath: path.relative(root, filePath),
|
||||
contentType: getContentType(filePath),
|
||||
});
|
||||
}
|
||||
|
||||
await Deno.writeTextFile(
|
||||
path.join(outDir, "static-files.json"),
|
||||
JSON.stringify(Array.from(staticFiles.values()), null, 2),
|
||||
);
|
||||
|
||||
const islandSpecifiers: string[] = [];
|
||||
for (const spec of this.islandModNameToChunk.keys()) {
|
||||
islandSpecifiers.push(spec);
|
||||
}
|
||||
|
||||
const editWarning =
|
||||
`// WARNING: DO NOT EDIT THIS FILE. It is autogenerated by Fresh.`;
|
||||
|
||||
const islands = Array.from(this.islandModNameToChunk.values());
|
||||
|
||||
await Deno.writeTextFile(
|
||||
path.join(outDir, "snapshot.js"),
|
||||
await generateSnapshotServer({
|
||||
buildId: this.#config.buildId,
|
||||
clientEntry: getClientEntry(this.#config.buildId),
|
||||
staticFiles,
|
||||
islands,
|
||||
writeSpecifier: (filePath) => {
|
||||
return pathToSpec(outDir, filePath);
|
||||
},
|
||||
fsRoutesFiles: this.#fsRoutes.files,
|
||||
outDir: root,
|
||||
}),
|
||||
`${editWarning}
|
||||
|
||||
import { IslandPreparer } from "fresh/do-not-use";
|
||||
import staticFileData from "./static-files.json" with { type: "json" };
|
||||
|
||||
// Import islands
|
||||
${
|
||||
islands
|
||||
.map((item) => {
|
||||
const spec = pathToSpec(outDir, item.server);
|
||||
return `import * as ${item.name} from "${spec}";`;
|
||||
})
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
// Import routes
|
||||
${
|
||||
this.#fsRoutes.files
|
||||
.map((item, i) => {
|
||||
if (item.lazy) return null;
|
||||
const spec = pathToSpec(outDir, item.filePath);
|
||||
return `import * as fsRoute_${i} from "${spec}"`;
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
export const version = ${JSON.stringify(this.#config.buildId)};
|
||||
|
||||
const prefix = \`/_fresh/js/\${version}\`;
|
||||
|
||||
export const islands = new Map();
|
||||
const islandPreparer = new IslandPreparer();
|
||||
${
|
||||
islands.map((item) => {
|
||||
// Strip prefix
|
||||
const prefix = `/_fresh/js/${this.#config.buildId}`;
|
||||
const chunkName = item.browser
|
||||
? item.browser.slice(prefix.length)
|
||||
: item.browser;
|
||||
return `islandPreparer.prepare(islands, ${item.name}, \`\${prefix}${chunkName}\`, ${
|
||||
JSON.stringify(item.name)
|
||||
});`;
|
||||
}).join("\n")
|
||||
}
|
||||
|
||||
export const staticFiles = new Map();
|
||||
for (let i = 0; i < staticFileData.length; i++) {
|
||||
const data = staticFileData[i];
|
||||
staticFiles.set(data.name, data);
|
||||
}
|
||||
|
||||
export const fsRoutes = [
|
||||
${
|
||||
this.#fsRoutes.files
|
||||
.map((item, i) => {
|
||||
const id = JSON.stringify(item.id);
|
||||
const pattern = JSON.stringify(item.pattern);
|
||||
const type = JSON.stringify(item.type);
|
||||
const routePattern = JSON.stringify(item.routePattern);
|
||||
|
||||
let mod = "";
|
||||
if (item.lazy) {
|
||||
const spec = pathToSpec(outDir, item.filePath);
|
||||
mod = `() => import(${JSON.stringify(spec)})`;
|
||||
} else {
|
||||
mod = `fsRoute_${i}`;
|
||||
}
|
||||
|
||||
return ` { id: ${id}, mod: ${mod}, type: ${type}, pattern: ${pattern}, routePattern: ${routePattern} },`;
|
||||
})
|
||||
.join("\n")
|
||||
}
|
||||
];
|
||||
`,
|
||||
);
|
||||
|
||||
// TODO: Make main file configurable
|
||||
const appPath = path.relative(outDir, root);
|
||||
await Deno.writeTextFile(
|
||||
path.join(outDir, "server.js"),
|
||||
generateServerEntry({
|
||||
root: appPath,
|
||||
serverEntry: path
|
||||
.join(appPath, "main.ts")
|
||||
.replaceAll(/[\\/]+/g, "/"),
|
||||
snapshotSpecifier: "./snapshot.js",
|
||||
}),
|
||||
`${editWarning}
|
||||
import { setBuildCache, ProdBuildCache, path } from "fresh/do-not-use";
|
||||
import * as snapshot from "./snapshot.js";
|
||||
import { app } from "${appPath}/main.ts";
|
||||
|
||||
const root = path.join(import.meta.dirname, ${JSON.stringify(appPath)});
|
||||
setBuildCache(app, new ProdBuildCache(root, snapshot));
|
||||
|
||||
export default {
|
||||
fetch: app.handler()
|
||||
}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const EDIT_WARNING =
|
||||
`// WARNING: DO NOT EDIT THIS FILE. It is autogenerated by Fresh.`;
|
||||
|
||||
export async function hashContent(
|
||||
async function hashContent(
|
||||
content: Uint8Array | ReadableStream<Uint8Array>,
|
||||
): Promise<string> {
|
||||
const buffer = await new Response(content).arrayBuffer();
|
||||
@@ -397,137 +476,3 @@ export function getContentType(filePath: string): string {
|
||||
function maybeToFileUrl(file: string) {
|
||||
return file.startsWith("file://") ? file : path.toFileUrl(file).href;
|
||||
}
|
||||
|
||||
export interface PendingStaticFile {
|
||||
pathname: string;
|
||||
filePath: string;
|
||||
hash: string | null;
|
||||
}
|
||||
|
||||
export async function generateSnapshotServer(
|
||||
options: {
|
||||
outDir: string;
|
||||
buildId: string;
|
||||
clientEntry: string;
|
||||
islands: IslandModChunk[];
|
||||
// deno-lint-ignore no-explicit-any
|
||||
fsRoutesFiles: FsRouteFileNoMod<any>[];
|
||||
staticFiles: PendingStaticFile[];
|
||||
writeSpecifier: (filePath: string) => string;
|
||||
},
|
||||
): Promise<string> {
|
||||
const {
|
||||
islands,
|
||||
writeSpecifier,
|
||||
fsRoutesFiles,
|
||||
outDir,
|
||||
} = options;
|
||||
|
||||
const islandImports = islands
|
||||
.map((item) => {
|
||||
const spec = writeSpecifier(item.server);
|
||||
return `import * as ${item.name} from "${spec}";`;
|
||||
})
|
||||
.join("\n");
|
||||
|
||||
const fsRouteImports = fsRoutesFiles
|
||||
.map((item, i) => {
|
||||
if (item.lazy) return null;
|
||||
const spec = writeSpecifier(item.filePath);
|
||||
return `import * as fsRoute_${i} from "${spec}"`;
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
|
||||
const islandMarkers = islands.map((item) => {
|
||||
const browser = JSON.stringify(item.browser);
|
||||
const name = JSON.stringify(item.name);
|
||||
return `islandPreparer.prepare(islands, ${item.name}, ${browser}, ${name});`;
|
||||
}).join("\n");
|
||||
|
||||
const serializedFsRoutes = fsRoutesFiles
|
||||
.map((item, i) => {
|
||||
const id = JSON.stringify(item.id);
|
||||
const pattern = JSON.stringify(item.pattern);
|
||||
const type = JSON.stringify(item.type);
|
||||
const routePattern = JSON.stringify(item.routePattern);
|
||||
|
||||
let mod = "";
|
||||
if (item.lazy) {
|
||||
const spec = writeSpecifier(item.filePath);
|
||||
mod = `() => import(${JSON.stringify(spec)})`;
|
||||
} else {
|
||||
mod = `fsRoute_${i}`;
|
||||
}
|
||||
|
||||
return ` { id: ${id}, mod: ${mod}, type: ${type}, pattern: ${pattern}, routePattern: ${routePattern} },`;
|
||||
})
|
||||
.join("\n");
|
||||
|
||||
const staticFiles = await Promise.all(
|
||||
options.staticFiles.map(async (item) => {
|
||||
const file = await Deno.open(item.filePath);
|
||||
const hash = item.hash ? item.hash : await hashContent(file.readable);
|
||||
const url = new URL(item.pathname, "http://localhost");
|
||||
|
||||
return {
|
||||
name: url.pathname,
|
||||
hash,
|
||||
filePath: path.isAbsolute(item.filePath)
|
||||
? path.relative(outDir, item.filePath)
|
||||
: item.filePath,
|
||||
contentType: getContentType(item.filePath),
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
return `${EDIT_WARNING}
|
||||
import { IslandPreparer } from "fresh/internal";
|
||||
${islandImports}
|
||||
${fsRouteImports}
|
||||
|
||||
export const clientEntry = ${JSON.stringify(options.clientEntry)}
|
||||
export const version = ${JSON.stringify(options.buildId)}
|
||||
|
||||
export const islands = new Map();
|
||||
const islandPreparer = new IslandPreparer();
|
||||
${islandMarkers}
|
||||
|
||||
export const staticFiles = new Map([
|
||||
${
|
||||
staticFiles.map((def) =>
|
||||
` [${JSON.stringify(def.name)}, ${JSON.stringify(def)}]`
|
||||
).join(",\n")
|
||||
}
|
||||
]);
|
||||
|
||||
export const fsRoutes = [
|
||||
${serializedFsRoutes}
|
||||
];
|
||||
`.replaceAll(/\n[\n]+/g, "\n\n");
|
||||
}
|
||||
|
||||
export function generateServerEntry(
|
||||
options: {
|
||||
root: string;
|
||||
serverEntry: string;
|
||||
snapshotSpecifier: string;
|
||||
},
|
||||
): string {
|
||||
return `${EDIT_WARNING}
|
||||
import { setBuildCache, ProdBuildCache, path } from "fresh/internal";
|
||||
import * as snapshot from "${options.snapshotSpecifier}";
|
||||
import { app } from "${options.serverEntry}";
|
||||
|
||||
const root = "";
|
||||
setBuildCache(app, new ProdBuildCache(root, snapshot), "production");
|
||||
|
||||
export default {
|
||||
fetch: app.handler()
|
||||
};
|
||||
`;
|
||||
}
|
||||
|
||||
function getClientEntry(buildId: string) {
|
||||
return `/_fresh/js/${buildId}/fresh-runtime.js`;
|
||||
}
|
||||
|
||||
+2
-2
@@ -166,14 +166,14 @@ function buildIdPlugin(buildId: string): EsbuildPlugin {
|
||||
return {
|
||||
name: "fresh-build-id",
|
||||
setup(build) {
|
||||
build.onResolve({ filter: /^fresh\/build-id$/ }, (args) => {
|
||||
build.onResolve({ filter: /[/\\]+build_id\.ts$/ }, (args) => {
|
||||
return {
|
||||
path: args.path,
|
||||
namespace: "fresh-internal",
|
||||
};
|
||||
});
|
||||
build.onLoad({
|
||||
filter: /^fresh\/build-id$/,
|
||||
filter: /[/\\]build_id\.ts$/,
|
||||
namespace: "fresh-internal",
|
||||
}, () => {
|
||||
return {
|
||||
|
||||
+79
-102
@@ -1,4 +1,4 @@
|
||||
import { type FsAdapter, fsAdapter } from "../fs.ts";
|
||||
import type { FsAdapter } from "../fs.ts";
|
||||
import type { WalkEntry } from "@std/fs/walk";
|
||||
import type { FsRouteFileNoMod } from "./dev_build_cache.ts";
|
||||
import * as path from "@std/path";
|
||||
@@ -14,90 +14,92 @@ export async function crawlRouteDir<State>(
|
||||
routeDir: string,
|
||||
ignore: RegExp[],
|
||||
onIslandSpecifier: (spec: string) => void,
|
||||
): Promise<FsRouteFileNoMod<State>[]> {
|
||||
const files: FsRouteFileNoMod<State>[] = [];
|
||||
|
||||
await walkDir(fs, routeDir, async (entry) => {
|
||||
// A `(_islands)` path segment is a local island folder.
|
||||
// Any route path segment wrapped in `(_...)` is ignored
|
||||
// during route collection.
|
||||
const match = entry.path.match(GROUP_REG);
|
||||
if (match !== null) {
|
||||
if (match[1] === "_islands") {
|
||||
onIslandSpecifier(entry.path);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let lazy = false;
|
||||
const relative = path.relative(routeDir, entry.path);
|
||||
const url = new URL(relative, "http://localhost/");
|
||||
const id = url.pathname.slice(0, url.pathname.lastIndexOf("."));
|
||||
|
||||
let overrideConfig: RouteConfig | undefined;
|
||||
let pattern = "*";
|
||||
let routePattern = pattern;
|
||||
let type = CommandType.Route;
|
||||
if (id.endsWith("/_middleware")) {
|
||||
type = CommandType.Middleware;
|
||||
pattern = pathToPattern(
|
||||
id.slice(1, -"/_middleware".length),
|
||||
{ keepGroups: true },
|
||||
);
|
||||
routePattern = pattern;
|
||||
} else if (id.endsWith("/_layout")) {
|
||||
type = CommandType.Layout;
|
||||
pattern = pathToPattern(
|
||||
id.slice(1, -"/_layout".length),
|
||||
{ keepGroups: true },
|
||||
);
|
||||
routePattern = pattern;
|
||||
} else if (id.endsWith("/_app")) {
|
||||
type = CommandType.App;
|
||||
} else if (id.endsWith("/_404")) {
|
||||
type = CommandType.NotFound;
|
||||
} else if (id.endsWith("/_error") || id.endsWith("/_500")) {
|
||||
type = CommandType.Error;
|
||||
pattern = pathToPattern(
|
||||
id.slice(1, -"/_error".length),
|
||||
{ keepGroups: true },
|
||||
);
|
||||
routePattern = pattern;
|
||||
} else {
|
||||
pattern = pathToPattern(id.slice(1), { keepGroups: true });
|
||||
if (id.endsWith("/index")) {
|
||||
if (!pattern.endsWith("/")) {
|
||||
pattern += "/";
|
||||
files: FsRouteFileNoMod<State>[],
|
||||
) {
|
||||
await walkDir(
|
||||
fs,
|
||||
routeDir,
|
||||
async (entry) => {
|
||||
// A `(_islands)` path segment is a local island folder.
|
||||
// Any route path segment wrapped in `(_...)` is ignored
|
||||
// during route collection.
|
||||
const match = entry.path.match(GROUP_REG);
|
||||
if (match !== null) {
|
||||
if (match[1] === "_islands") {
|
||||
onIslandSpecifier(entry.path);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
routePattern = pathToPattern(id.slice(1));
|
||||
let lazy = false;
|
||||
const relative = path.relative(routeDir, entry.path);
|
||||
const url = new URL(relative, "http://localhost/");
|
||||
const id = url.pathname.slice(0, url.pathname.lastIndexOf("."));
|
||||
|
||||
const code = await fs.readTextFile(entry.path);
|
||||
lazy = !code.includes("routeOverride");
|
||||
let overrideConfig: RouteConfig | undefined;
|
||||
let pattern = "*";
|
||||
let routePattern = pattern;
|
||||
let type = CommandType.Route;
|
||||
if (id.endsWith("/_middleware")) {
|
||||
type = CommandType.Middleware;
|
||||
pattern = pathToPattern(
|
||||
id.slice(1, -"/_middleware".length),
|
||||
{ keepGroups: true },
|
||||
);
|
||||
routePattern = pattern;
|
||||
} else if (id.endsWith("/_layout")) {
|
||||
type = CommandType.Layout;
|
||||
pattern = pathToPattern(
|
||||
id.slice(1, -"/_layout".length),
|
||||
{ keepGroups: true },
|
||||
);
|
||||
routePattern = pattern;
|
||||
} else if (id.endsWith("/_app")) {
|
||||
type = CommandType.App;
|
||||
} else if (id.endsWith("/_404")) {
|
||||
type = CommandType.NotFound;
|
||||
} else if (id.endsWith("/_error") || id.endsWith("/_500")) {
|
||||
type = CommandType.Error;
|
||||
pattern = pathToPattern(
|
||||
id.slice(1, -"/_error".length),
|
||||
{ keepGroups: true },
|
||||
);
|
||||
routePattern = pattern;
|
||||
} else {
|
||||
pattern = pathToPattern(id.slice(1), { keepGroups: true });
|
||||
if (id.endsWith("/index")) {
|
||||
if (!pattern.endsWith("/")) {
|
||||
pattern += "/";
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: We could do an AST parse here to detect the
|
||||
// kind of handler that's used to get a more accurate
|
||||
// list of methods this route supports.
|
||||
overrideConfig = {
|
||||
methods: "ALL",
|
||||
};
|
||||
}
|
||||
routePattern = pathToPattern(id.slice(1));
|
||||
|
||||
files.push({
|
||||
id,
|
||||
filePath: entry.path,
|
||||
type,
|
||||
pattern,
|
||||
routePattern,
|
||||
lazy,
|
||||
overrideConfig,
|
||||
});
|
||||
}, ignore);
|
||||
const code = await fs.readTextFile(entry.path);
|
||||
lazy = !code.includes("routeOverride");
|
||||
|
||||
// TODO: We could do an AST parse here to detect the
|
||||
// kind of handler that's used to get a more accurate
|
||||
// list of methods this route supports.
|
||||
overrideConfig = {
|
||||
methods: "ALL",
|
||||
};
|
||||
}
|
||||
|
||||
files.push({
|
||||
id,
|
||||
filePath: entry.path,
|
||||
type,
|
||||
pattern,
|
||||
routePattern,
|
||||
lazy,
|
||||
overrideConfig,
|
||||
});
|
||||
},
|
||||
ignore,
|
||||
);
|
||||
|
||||
files.sort((a, b) => sortRoutePaths(a.id, b.id));
|
||||
|
||||
return files;
|
||||
}
|
||||
|
||||
export async function walkDir(
|
||||
@@ -119,28 +121,3 @@ export async function walkDir(
|
||||
await callback(entry);
|
||||
}
|
||||
}
|
||||
|
||||
export async function crawlFsItem(
|
||||
options: { islandDir: string; routeDir: string; ignore: RegExp[] },
|
||||
): Promise<{ islands: string[]; routes: FsRouteFileNoMod<unknown>[] }> {
|
||||
const islands: string[] = [];
|
||||
|
||||
const [, routes] = await Promise.all([
|
||||
walkDir(
|
||||
fsAdapter,
|
||||
options.islandDir,
|
||||
(entry) => {
|
||||
islands.push(entry.path);
|
||||
},
|
||||
options.ignore,
|
||||
),
|
||||
crawlRouteDir(
|
||||
fsAdapter,
|
||||
options.routeDir,
|
||||
options.ignore,
|
||||
(entry) => islands.push(entry),
|
||||
),
|
||||
]);
|
||||
|
||||
return { islands, routes };
|
||||
}
|
||||
|
||||
@@ -89,7 +89,7 @@ function getFirstUserFile(
|
||||
const lines = stack.split("\n");
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const match = lines[i].match(STACK_FRAME);
|
||||
if (match) {
|
||||
if (match && match) {
|
||||
const fnName = match[1] ?? "";
|
||||
const file = match[2];
|
||||
const line = +match[3];
|
||||
|
||||
@@ -86,8 +86,9 @@ Deno.test(
|
||||
);
|
||||
|
||||
Deno.test("error overlay - should not be visible in prod", async () => {
|
||||
const app = new App({ mode: "production" });
|
||||
const app = new App();
|
||||
app.use(devErrorOverlay());
|
||||
app.config.mode = "production";
|
||||
|
||||
app.get("/", () => {
|
||||
throw new HttpError(500);
|
||||
|
||||
@@ -9,6 +9,7 @@ import type { Method } from "./router.ts";
|
||||
import { parseHtml } from "../tests/test_utils.tsx";
|
||||
import type { Context } from "./context.ts";
|
||||
import { HttpError } from "./error.ts";
|
||||
import type { FsRouteFileNoMod } from "./dev/dev_build_cache.ts";
|
||||
import { crawlRouteDir } from "./dev/fs_crawl.ts";
|
||||
import * as path from "@std/path";
|
||||
|
||||
@@ -18,7 +19,8 @@ async function createServer<T>(
|
||||
const fs = createFakeFs(files);
|
||||
|
||||
const routeDir = path.join(fs.cwd(), "routes");
|
||||
const rawFiles = await crawlRouteDir(fs, routeDir, [], () => {});
|
||||
const rawFiles: FsRouteFileNoMod<T>[] = [];
|
||||
await crawlRouteDir(fs, routeDir, [], () => {}, rawFiles);
|
||||
|
||||
const fsFiles = rawFiles.map((file) => {
|
||||
// deno-lint-ignore no-explicit-any
|
||||
@@ -28,8 +30,8 @@ async function createServer<T>(
|
||||
const app = new App<T>()
|
||||
.fsRoutes();
|
||||
|
||||
const buildCache = new MockBuildCache<T>(fsFiles, "development");
|
||||
setBuildCache<T>(app, buildCache, "development");
|
||||
const buildCache = new MockBuildCache<T>(fsFiles);
|
||||
setBuildCache<T>(app, buildCache);
|
||||
|
||||
return new FakeServer(app.handler());
|
||||
}
|
||||
@@ -227,9 +229,7 @@ Deno.test("fsRoutes - middleware array", async () => {
|
||||
return ctx.next();
|
||||
},
|
||||
},
|
||||
"routes/foo/index.ts": {
|
||||
default: (ctx) => <div class="full-">{ctx.state.text}</div>,
|
||||
},
|
||||
"routes/foo/index.ts": { default: (ctx) => <div>{ctx.state.text}</div> },
|
||||
});
|
||||
|
||||
const res = await server.get("/foo");
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
export { crawlFsItem } from "./dev/fs_crawl.ts";
|
||||
export { type FsAdapter, fsAdapter } from "./fs.ts";
|
||||
export {
|
||||
type FsRouteFileNoMod,
|
||||
generateServerEntry,
|
||||
generateSnapshotServer,
|
||||
type IslandModChunk,
|
||||
type PendingStaticFile,
|
||||
} from "./dev/dev_build_cache.ts";
|
||||
export { specToName } from "./dev/builder.ts";
|
||||
export { pathToSpec, UniqueNamer } from "./utils.ts";
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { Middleware } from "./mod.ts";
|
||||
import { ASSET_CACHE_BUST_KEY } from "../runtime/shared_internal.tsx";
|
||||
import { BUILD_ID } from "fresh/build-id";
|
||||
import { BUILD_ID } from "../runtime/build_id.ts";
|
||||
import { tracer } from "../otel.ts";
|
||||
import { getBuildCache } from "../context.ts";
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import { serveMiddleware } from "../test_utils.ts";
|
||||
import type { BuildCache, StaticFile } from "../build_cache.ts";
|
||||
import { expect } from "@std/expect";
|
||||
import { ASSET_CACHE_BUST_KEY } from "../runtime/shared_internal.tsx";
|
||||
import { BUILD_ID } from "fresh/build-id";
|
||||
import { BUILD_ID } from "../runtime/build_id.ts";
|
||||
import type { Command } from "../commands.ts";
|
||||
import type { ServerIslandRegistry } from "../context.ts";
|
||||
import { getContentType } from "../dev/dev_build_cache.ts";
|
||||
@@ -13,8 +13,6 @@ class MockBuildCache implements BuildCache {
|
||||
buildId = "MockId";
|
||||
files = new Map<string, StaticFile>();
|
||||
islandRegistry: ServerIslandRegistry = new Map();
|
||||
clientEntry = "";
|
||||
features = { errorOverlay: false };
|
||||
|
||||
constructor(files: Record<string, { hash: string | null; content: string }>) {
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
+6
-10
@@ -14,6 +14,7 @@ import type { Context } from "./context.ts";
|
||||
import { recordSpanError, tracer } from "./otel.ts";
|
||||
import { DEV_ERROR_OVERLAY_URL } from "./constants.ts";
|
||||
import { renderToString } from "preact-render-to-string";
|
||||
import { BUILD_ID } from "./runtime/build_id.ts";
|
||||
|
||||
export type AsyncAnyComponent<P> = {
|
||||
(
|
||||
@@ -84,17 +85,12 @@ export function preactRender<State, Data>(
|
||||
} finally {
|
||||
// Add preload headers
|
||||
const basePath = ctx.config.basePath;
|
||||
const runtimeUrl = state.buildCache.clientEntry.startsWith(".")
|
||||
? state.buildCache.clientEntry.slice(1)
|
||||
: state.buildCache.clientEntry;
|
||||
let link = `<${
|
||||
encodeURI(`${basePath}${runtimeUrl}`)
|
||||
}>; rel="modulepreload"; as="script"`;
|
||||
const runtimeUrl = `${basePath}/_fresh/js/${BUILD_ID}/fresh-runtime.js`;
|
||||
let link = `<${encodeURI(runtimeUrl)}>; rel="modulepreload"; as="script"`;
|
||||
state.islands.forEach((island) => {
|
||||
const specifier = `${basePath}${
|
||||
island.file.startsWith(".") ? island.file.slice(1) : island.file
|
||||
}`;
|
||||
link += `, <${encodeURI(specifier)}>; rel="modulepreload"; as="script"`;
|
||||
link += `, <${
|
||||
encodeURI(`${basePath}${island.file}`)
|
||||
}>; rel="modulepreload"; as="script"`;
|
||||
});
|
||||
|
||||
if (link !== "") {
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import { encodeHex } from "@std/encoding/hex";
|
||||
|
||||
export const DENO_DEPLOYMENT_ID: string | undefined = Deno.env.get(
|
||||
"DENO_DEPLOYMENT_ID",
|
||||
);
|
||||
export const DENO_DEPLOYMENT_ID = Deno.env.get("DENO_DEPLOYMENT_ID");
|
||||
const deploymentId = DENO_DEPLOYMENT_ID ||
|
||||
// For CI
|
||||
Deno.env.get("GITHUB_SHA") ||
|
||||
@@ -12,8 +10,8 @@ const buildIdHash = await crypto.subtle.digest(
|
||||
new TextEncoder().encode(deploymentId),
|
||||
);
|
||||
|
||||
export let BUILD_ID: string = encodeHex(buildIdHash);
|
||||
export let BUILD_ID = encodeHex(buildIdHash);
|
||||
|
||||
export function setBuildId(buildId: string): void {
|
||||
export function setBuildId(buildId: string) {
|
||||
BUILD_ID = buildId;
|
||||
}
|
||||
|
||||
@@ -329,7 +329,7 @@ export async function applyPartials(res: Response): Promise<void> {
|
||||
for (let i = 0; i < json.islands.length; i++) {
|
||||
const island = json.islands[i];
|
||||
promises.push(
|
||||
import(/* @vite-ignore */ island.chunk).then((mod) => {
|
||||
import(island.chunk).then((mod) => {
|
||||
ISLAND_REGISTRY.set(island.name, mod[island.exportName]);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { options } from "preact";
|
||||
import { assetHashingHook, CLIENT_NAV_ATTR } from "../shared_internal.tsx";
|
||||
import { BUILD_ID } from "fresh/build-id";
|
||||
import { BUILD_ID } from "../build_id.ts";
|
||||
|
||||
const oldVNodeHook = options.vnode;
|
||||
options.vnode = (vnode) => {
|
||||
|
||||
@@ -23,7 +23,7 @@ import {
|
||||
setActiveUrl,
|
||||
} from "../shared_internal.tsx";
|
||||
import type { BuildCache } from "../../build_cache.ts";
|
||||
import { BUILD_ID } from "fresh/build-id";
|
||||
import { BUILD_ID } from "../build_id.ts";
|
||||
import {
|
||||
DEV_ERROR_OVERLAY_URL,
|
||||
PARTIAL_SEARCH_PARAM,
|
||||
@@ -433,8 +433,7 @@ export interface PartialStateJson {
|
||||
}
|
||||
|
||||
function FreshRuntimeScript() {
|
||||
const { islands, nonce, ctx, islandProps, partialId, buildCache } =
|
||||
RENDER_STATE!;
|
||||
const { islands, nonce, ctx, islandProps, partialId } = RENDER_STATE!;
|
||||
const basePath = ctx.config.basePath;
|
||||
|
||||
const islandArr = Array.from(islands);
|
||||
@@ -471,11 +470,7 @@ function FreshRuntimeScript() {
|
||||
: island.exportName === island.name
|
||||
? `{ ${island.exportName} }`
|
||||
: `{ ${island.exportName} as ${island.name} }`;
|
||||
|
||||
const islandSpec = island.file.startsWith(".")
|
||||
? island.file.slice(1)
|
||||
: island.file;
|
||||
return `import ${named} from "${basePath}${islandSpec}";`;
|
||||
return `import ${named} from "${`${basePath}${island.file}`}";`;
|
||||
}).join("");
|
||||
|
||||
const islandObj = "{" + islandArr.map((island) => island.name)
|
||||
@@ -487,12 +482,9 @@ function FreshRuntimeScript() {
|
||||
{ json: true },
|
||||
);
|
||||
|
||||
// const runtimeUrl = `${basePath}/_fresh/js/${BUILD_ID}/fresh-runtime.js`;
|
||||
const runtimeUrl = buildCache.clientEntry.startsWith(".")
|
||||
? buildCache.clientEntry.slice(1)
|
||||
: buildCache.clientEntry;
|
||||
const runtimeUrl = `${basePath}/_fresh/js/${BUILD_ID}/fresh-runtime.js`;
|
||||
const scriptContent =
|
||||
`import { boot } from "${basePath}${runtimeUrl}";${islandImports}boot(${islandObj},${serializedProps});`;
|
||||
`import { boot } from "${runtimeUrl}";${islandImports}boot(${islandObj},${serializedProps});`;
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -504,7 +496,7 @@ function FreshRuntimeScript() {
|
||||
__html: scriptContent,
|
||||
}}
|
||||
/>
|
||||
{buildCache.features.errorOverlay ? <ShowErrorOverlay /> : null}
|
||||
{ctx.config.mode === "development" ? <ShowErrorOverlay /> : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { ComponentChildren, VNode } from "preact";
|
||||
import { BUILD_ID } from "fresh/build-id";
|
||||
import { BUILD_ID } from "./build_id.ts";
|
||||
import { assetInternal, assetSrcSetInternal } from "./shared_internal.tsx";
|
||||
|
||||
/**
|
||||
|
||||
+2
-5
@@ -83,7 +83,7 @@ export function serveMiddleware<T>(
|
||||
(() => new Response("not found", { status: 404 }));
|
||||
const config = options.config ?? DEFAULT_CONFIG;
|
||||
const buildCache = options.buildCache ??
|
||||
new MockBuildCache<T>([], options.config?.mode ?? "production");
|
||||
new MockBuildCache<T>([]);
|
||||
|
||||
const ctx = new Context<T>(
|
||||
req,
|
||||
@@ -149,12 +149,9 @@ export async function withTmpDir(
|
||||
export class MockBuildCache<State> implements BuildCache<State> {
|
||||
#files: FsRouteFile<State>[];
|
||||
root = "";
|
||||
clientEntry = "";
|
||||
islandRegistry: ServerIslandRegistry = new Map();
|
||||
features = { errorOverlay: false };
|
||||
|
||||
constructor(files: FsRouteFile<State>[], mode: "development" | "production") {
|
||||
this.features.errorOverlay = mode === "development";
|
||||
constructor(files: FsRouteFile<State>[]) {
|
||||
this.#files = files;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user