chore: restructure repository into packages/ folder (#3197)

We're having a growing number of packages in this repository. This PR
moves them into a `packages/` directory like it's commonly done in other
projects.
This commit is contained in:
Marvin Hagemeister
2025-08-06 15:52:45 +02:00
committed by GitHub
parent 27e407a1e3
commit 815b1940e3
184 changed files with 94 additions and 82 deletions
+400
View File
@@ -0,0 +1,400 @@
import { App, type ListenOptions, setBuildCache } from "../app.ts";
import { fsAdapter } from "../fs.ts";
import * as path from "@std/path";
import * as colors from "@std/fmt/colors";
import { bundleJs, type FreshBundleOptions } from "./esbuild.ts";
import { liveReload } from "./middlewares/live_reload.ts";
import {
cssAssetHash,
FileTransformer,
type OnTransformOptions,
} from "./file_transformer.ts";
import type { TransformFn } from "./file_transformer.ts";
import {
type DevBuildCache,
DiskBuildCache,
type FsRoute,
MemoryBuildCache,
} from "./dev_build_cache.ts";
import { BUILD_ID } from "@fresh/build-id";
import { updateCheck } from "./update_check.ts";
import { devErrorOverlay } from "./middlewares/error_overlay/middleware.tsx";
import { automaticWorkspaceFolders } from "./middlewares/automatic_workspace_folders.ts";
import { parseDirPath } from "../config.ts";
import { pathToExportName, UniqueNamer } from "../utils.ts";
import { checkDenoCompilerOptions } from "./check.ts";
import { crawlFsItem } from "./fs_crawl.ts";
import { DAY } from "../constants.ts";
export interface BuildOptions {
/**
* This sets the target environment for the generated code. Newer
* language constructs will be transformed to match the specified
* support range. See https://esbuild.github.io/api/#target
* @default {"es2022"}
*/
target?: string | string[];
/**
* The root directory of the Fresh project.
*
* Other paths, such as `build.outDir`, `staticDir`, and `fsRoutes()`
* are resolved relative to this directory.
* @default Deno.cwd()
*/
root?: string;
/**
* 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.
* Relative paths are resolved against the `root` option.
* @default "_fresh"
*/
outDir?: string;
/**
* The directory to serve static files from.
*
* This can be an absolute path, a file URL or a relative path.
* Relative paths are resolved against the `root` option.
* @default "static"
*/
staticDir?: string;
/**
* The directory which contains islands.
*
* This can be an absolute path, a file URL or a relative path.
* Relative paths are resolved against the `root` option.
* @default "islands"
*/
islandDir?: string;
/**
* The directory which contains routes.
*
* This can be an absolute path, a file URL or a relative path.
* Relative paths are resolved against the `root` option.
* @default "routes"
*/
routeDir?: string;
/**
* File paths which should be ignored when crawling the file system.
*/
ignore?: RegExp[];
/**
* Control if/how production source maps should be handled.
* See https://esbuild.github.io/api/#source-maps for more information.
*/
sourceMap?: FreshBundleOptions["sourceMap"];
}
/**
* The final resolved Builder configuration.
*/
export type ResolvedBuildConfig = Required<Omit<BuildOptions, "sourceMap">> & {
mode: "development" | "production";
buildId: string;
sourceMap?: FreshBundleOptions["sourceMap"];
};
const TEST_FILE_PATTERN = /[._]test\.(?:[tj]sx?|[mc][tj]s)$/;
// deno-lint-ignore no-explicit-any
export class Builder<State = any> {
#transformer: FileTransformer;
#addedInternalTransforms = false;
config: ResolvedBuildConfig;
#islandSpecifiers = new Set<string>();
#fsRoutes: FsRoute<State>;
#ready = Promise.withResolvers<void>();
constructor(options?: BuildOptions) {
const root = parseDirPath(options?.root ?? ".", Deno.cwd());
const outDir = parseDirPath(options?.outDir ?? "_fresh", root);
const staticDir = parseDirPath(options?.staticDir ?? "static", root);
const islandDir = parseDirPath(options?.islandDir ?? "islands", root);
const routeDir = parseDirPath(options?.routeDir ?? "routes", root);
this.#fsRoutes = { dir: routeDir, files: [], id: "default" };
this.#transformer = new FileTransformer(fsAdapter, root);
this.config = {
target: options?.target ?? ["chrome99", "firefox99", "safari15"],
root,
outDir,
staticDir,
islandDir,
routeDir,
ignore: options?.ignore ?? [TEST_FILE_PATTERN],
mode: "production",
buildId: BUILD_ID,
sourceMap: options?.sourceMap,
};
}
registerIsland(specifier: string): void {
this.#islandSpecifiers.add(specifier);
}
onTransformStaticFile(
options: OnTransformOptions,
callback: TransformFn,
): void {
this.#transformer.onTransform(options, callback);
}
async listen(
importApp: () => Promise<{ app: App<State> } | App<State>>,
options: ListenOptions = {},
): Promise<void> {
// Run update check in background
updateCheck(DAY).catch(() => {});
this.config.mode = "development";
await this.#crawlFsItems();
let app = await importApp();
if (!(app instanceof App) && "app" in app) {
app = app.app;
}
const buildCache = new MemoryBuildCache<State>(
this.config,
this.#fsRoutes,
this.#transformer,
);
await buildCache.prepare();
app.config.root = this.config.root;
app.config.mode = "development";
setBuildCache(app, buildCache, "development");
const appHandler = app.handler();
const devApp = new App<State>(app.config)
.use(liveReload())
.use(devErrorOverlay())
.use(automaticWorkspaceFolders(this.config.root))
// Wait for islands to be ready
.use(async (ctx) => {
await this.#ready.promise;
return ctx.next();
})
.all("*", (ctx) => appHandler(ctx.req, ctx.info));
devApp.config.root = this.config.root;
devApp.config.mode = "development";
setBuildCache(devApp, buildCache, "development");
// Boot in parallel to spin up the server quicker. We'll hold
// requests until the required assets are processed.
await Promise.all([
devApp.listen(options),
this.#build(buildCache, true),
]);
return;
}
/**
* Build optimized assets for your app. By default this will create
* a production build.
*
* This can also be used for testing to apply a snapshot to a particular
* {@linkcode App} instance.
*
* @example
* ```ts
* const builder = new Builder();
* const applySnapshot = await builder.build({ snapshot: "memory" });
*
* Deno.test("My Test", () => {
* const app = new App()
* .get("/", () => new Response("hello"))
*
* applySnapshot(app)
*
* // ... your usual testing
* })
* ```
* @param options
* @returns Apply a snapshot to a particular {@linkcode App} instance.
*/
async build(
options?: {
mode?: ResolvedBuildConfig["mode"];
snapshot?: "disk" | "memory";
},
): Promise<(app: App<State>) => void> {
this.config.mode = options?.mode ?? "production";
await this.#crawlFsItems();
const buildCache = options?.snapshot === "memory"
? new MemoryBuildCache(
this.config,
this.#fsRoutes,
this.#transformer,
)
: new DiskBuildCache(
this.config,
this.#fsRoutes,
this.#transformer,
);
await this.#build(buildCache, this.config.mode === "development");
await buildCache.prepare();
return (app) => {
setBuildCache(app, buildCache, app.config.mode);
};
}
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;
}
async #build<T>(buildCache: DevBuildCache<T>, dev: boolean): Promise<void> {
const { target, outDir, root } = this.config;
const staticOutDir = path.join(outDir, "static");
const { denoJson, jsxImportSource } = await checkDenoCompilerOptions(root);
if (!this.#addedInternalTransforms) {
this.#addedInternalTransforms = true;
cssAssetHash(this.#transformer);
}
try {
await Deno.remove(staticOutDir);
} catch {
// Ignore
}
const runtimePath = dev
? "../runtime/client/dev.ts"
: "../runtime/client/mod.tsx";
const entryPoints: Record<string, string> = {
"fresh-runtime": new URL(runtimePath, import.meta.url).href,
};
const namer = new UniqueNamer();
for (const spec of this.#islandSpecifiers) {
const specName = specToName(spec);
const name = namer.getUniqueName(specName);
entryPoints[name] = spec;
buildCache.islandModNameToChunk.set(name, {
name,
server: spec,
browser: null,
});
}
const output = await bundleJs({
cwd: root,
outDir: staticOutDir,
dev: dev ?? false,
target,
buildId: BUILD_ID,
entryPoints,
jsxImportSource,
denoJsonPath: denoJson,
sourceMap: this.config.sourceMap,
});
const prefix = `/_fresh/js/${BUILD_ID}/`;
for (const name of buildCache.islandModNameToChunk.keys()) {
const chunkName = output.entryToChunk.get(name);
if (chunkName === undefined) {
throw new Error(`Could not find chunk for island ${name}`);
}
const pathname = `${prefix}${chunkName}`;
buildCache.islandModNameToChunk.get(name)!.browser = pathname;
}
for (let i = 0; i < output.files.length; i++) {
const file = output.files[i];
const pathname = `${prefix}${file.path}`;
await buildCache.addProcessedFile(pathname, file.contents, file.hash);
}
await buildCache.flush();
if (!dev) {
// deno-lint-ignore no-console
console.log(
`Assets written to: ${colors.cyan(outDir)}`,
);
}
this.#ready.resolve();
}
}
export function specToName(spec: string): string {
if (/^(https?:|file:)/.test(spec)) {
const url = new URL(spec);
if (url.pathname === "/") {
return pathToExportName(url.hostname);
}
const idx = spec.lastIndexOf("/");
return pathToExportName(spec.slice(idx + 1));
} else if (spec.startsWith("jsr:")) {
const match = spec.match(
/jsr:@([^/]+)\/([^@/]+)(@[\^~]?\d+\.\d+\.\d+([^/]+)?)?(\/.*)?$/,
)!;
if (match[5] === undefined) {
return pathToExportName(`${match[1]}_${match[2]}`);
}
return pathToExportName(match[5]);
} else if (spec.startsWith("npm:")) {
const match = spec.match(
/npm:(@([^/]+)\/([^@/]+)|[^@/]+)(@[\^~]?\d+\.\d+\.\d+([^/]+)?)?(\/.*)?$/,
)!;
if (match[6] === undefined) {
if (match[2] === undefined) {
return pathToExportName(match[1]);
}
return pathToExportName(`${match[2]}_${match[3]}`);
}
return pathToExportName(match[6]);
}
const match = spec.match(/^(@([^/]+)\/([^@/]+)|[^@/]+)(\/.*)?$/);
if (match !== null) {
if (match[4] === undefined) {
if (match[2] !== undefined) {
return pathToExportName(`${match[2]}_${match[3]}`);
}
return pathToExportName(match[1]);
}
return pathToExportName(match[4]);
}
return pathToExportName(spec);
}
+777
View File
@@ -0,0 +1,777 @@
import { expect, fn } from "@std/expect";
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 { withTmpDir, writeFiles } from "../test_utils.ts";
import {
getStdOutput,
withChildProcessServer,
} from "../../tests/test_utils.tsx";
import { staticFiles } from "../middlewares/static_files.ts";
Deno.test({
name: "Builder - chain onTransformStaticFile",
fn: async () => {
await using _tmp = await withTmpDir();
const tmp = _tmp.dir;
const logs: string[] = [];
const builder = new Builder({
outDir: path.join(tmp, "dist"),
staticDir: tmp,
});
builder.onTransformStaticFile(
{ pluginName: "A", filter: /\.css$/ },
() => {
logs.push("A");
},
);
builder.onTransformStaticFile(
{ pluginName: "B", filter: /\.css$/ },
() => {
logs.push("B");
},
);
builder.onTransformStaticFile(
{ pluginName: "C", filter: /\.css$/ },
() => {
logs.push("C");
},
);
await Deno.writeTextFile(path.join(tmp, "foo.css"), "body { color: red; }");
await builder.build();
expect(logs).toEqual(["A", "B", "C"]);
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "Builder - handles Windows paths",
fn: async () => {
await using _tmp = await withTmpDir();
const tmp = _tmp.dir;
const builder = new Builder({
outDir: path.join(tmp, "dist"),
staticDir: tmp,
});
await Deno.mkdir(path.join(tmp, "images"));
await Deno.writeTextFile(
path.join(tmp, "images", "batman.svg"),
"<svg></svg>",
);
await builder.build();
const snapshotJson = await Deno.readTextFile(
path.join(tmp, "dist", "snapshot.js"),
);
expect(snapshotJson).toContain("/images/batman.svg");
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "Builder - hashes CSS urls by default",
fn: async () => {
await using _tmp = await withTmpDir();
const tmp = _tmp.dir;
const builder = new Builder({
outDir: path.join(tmp, "dist"),
staticDir: tmp,
});
await Deno.writeTextFile(
path.join(tmp, "foo.css"),
"body { background: url('/foo.jpg'); }",
);
await builder.build();
const css = await Deno.readTextFile(
path.join(tmp, "dist", "static", "foo.css"),
);
expect(css).toContain('body { background: url("/foo.jpg?__frsh_c=');
},
sanitizeOps: false,
sanitizeResources: false,
});
// Issue https://github.com/denoland/fresh/issues/2599
Deno.test({
name: "Builder - hashes CSS urls by default",
fn: async () => {
await using _tmp = await withTmpDir();
const tmp = _tmp.dir;
const builder = new Builder({
outDir: path.join(tmp, "dist"),
staticDir: tmp,
});
await Deno.writeTextFile(
path.join(tmp, "foo.css"),
`:root { --icon: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(76, 154.5, 137.5)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='20 6 9 17 4 12'%3E%3C/polyline%3E%3C/svg%3E"); }`,
);
await builder.build();
const css = await Deno.readTextFile(
path.join(tmp, "dist", "static", "foo.css"),
);
expect(css).toEqual(
`:root { --icon: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(76, 154.5, 137.5)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='20 6 9 17 4 12'%3E%3C/polyline%3E%3C/svg%3E"); }`,
);
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "Builder - can bundle islands from JSR",
fn: async () => {
await using _tmp = await withTmpDir();
const tmp = _tmp.dir;
const outDir = path.join(tmp, "dist");
const builder = new Builder({ outDir });
const specifier = "jsr:@marvinh-test/fresh-island";
builder.registerIsland(specifier);
await builder.build();
const name = specToName(specifier);
const code = await Deno.readTextFile(
path.join(
tmp,
"dist",
"static",
"_fresh",
"js",
BUILD_ID,
`${name}.js`,
),
);
expect(code).toContain('"remote-island"');
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "Builder - can bundle islands with import.meta.resolve()",
fn: async () => {
await using _tmp = await withTmpDir();
const tmp = _tmp.dir;
const outDir = path.join(tmp, "dist");
const builder = new Builder({ outDir });
const specifier = import.meta.resolve(
"../../tests/fixtures_islands/Counter.tsx",
);
builder.registerIsland(specifier);
await builder.build({ mode: "production", snapshot: "disk" });
const name = specToName(specifier);
const code = await Deno.readTextFile(
path.join(
tmp,
"dist",
"static",
"_fresh",
"js",
BUILD_ID,
`${name}.js`,
),
);
expect(code).toContain('"decrement"');
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "Builder - exclude files",
fn: async () => {
await using _tmp = await withTmpDir();
const tmp = _tmp.dir;
const logs: string[] = [];
const builder = new Builder({
outDir: path.join(tmp, "dist"),
staticDir: tmp,
});
// String
builder.onTransformStaticFile(
{ pluginName: "A", filter: /\.css$/, exclude: ["foo.css"] },
(args) => {
logs.push(`A: ${path.basename(args.path)}`);
},
);
// Regex
builder.onTransformStaticFile(
{ pluginName: "B", filter: /\.css$/, exclude: [/foo\.css$/] },
(args) => {
logs.push(`B: ${path.basename(args.path)}`);
},
);
// Glob
builder.onTransformStaticFile(
{ pluginName: "C", filter: /\.css$/, exclude: ["**/foo.css"] },
(args) => {
logs.push(`C: ${path.basename(args.path)}`);
},
);
await Deno.writeTextFile(path.join(tmp, "foo.css"), "body { color: red; }");
await Deno.writeTextFile(
path.join(tmp, "bar.css"),
"body { color: blue; }",
);
await builder.build();
expect(logs).toEqual(["A: bar.css", "B: bar.css", "C: bar.css"]);
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "Builder - workspace folder middleware on listen",
fn: async () => {
await using _tmp = await withTmpDir();
const tmp = _tmp.dir;
const builder = new Builder({
outDir: path.join(tmp, "dist"),
staticDir: tmp,
});
const app = new App();
const abort = new AbortController();
const port = 8011;
await builder.listen(() => Promise.resolve(app), {
port,
signal: abort.signal,
});
const res = await fetch(
`http://localhost:${port}/.well-known/appspecific/com.chrome.devtools.json`,
);
const json = await res.json();
await abort.abort();
expect(res.ok).toBe(true);
expect(res.status).toBe(200);
expect(res.headers.get("etag")).toEqual(expect.any(String));
expect(json).toEqual({
workspace: {
root: builder.config.root,
uuid: expect.any(String),
},
});
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "Builder - write prod routePattern",
fn: async () => {
const root = path.join(import.meta.dirname!, "..", "..");
await using _tmp = await withTmpDir({ dir: root, prefix: "tmp_builder_" });
const tmp = _tmp.dir;
await writeFiles(tmp, {
"routes/foo/index.ts": `export const handler = () => new Response("ok")`,
"main.ts": `import { App } from "fresh";
export const app = new App().fsRoutes()`,
});
const builder = new Builder({
root: tmp,
outDir: path.join(tmp, "dist"),
});
await builder.build();
let text = "fail";
await withChildProcessServer(
{ cwd: tmp, args: ["serve", "-A", "dist/server.js"] },
async (address) => {
const res = await fetch(`${address}/foo`);
text = await res.text();
},
);
expect(text).toEqual("ok");
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "Builder - file:// islands",
fn: async () => {
const root = path.join(import.meta.dirname!, "..", "..");
await using _tmp = await withTmpDir({ dir: root, prefix: "tmp_builder_" });
const tmp = _tmp.dir;
await writeFiles(tmp, {
"other/Foo.tsx": `export default () => <h1>ok</h1>;`,
"routes/index.tsx": `import Foo from "../other/Foo.tsx";
export default () => <Foo />;`,
"main.ts": `import { App } from "fresh";
export const app = new App().fsRoutes()`,
});
const builder = new Builder({
root: tmp,
outDir: path.join(tmp, "dist"),
});
const islandPath = path.join(tmp, "other", "Foo.tsx");
builder.registerIsland(path.toFileUrl(islandPath).href);
await builder.build();
let text = "fail";
await withChildProcessServer(
{ cwd: tmp, args: ["serve", "-A", "dist/server.js"] },
async (address) => {
const res = await fetch(address);
text = await res.text();
},
);
expect(text).toContain("<h1>ok</h1>");
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "Builder - dev server doesn't overtake _error handler",
fn: async () => {
const root = path.join(import.meta.dirname!, "..", "..");
await using _tmp = await withTmpDir({ dir: root, prefix: "tmp_builder_" });
const tmp = _tmp.dir;
const app = new App()
.onError("*", () => new Response("it works"))
.get("/", () => new Response("no"));
const builder = new Builder({
root: tmp,
outDir: path.join(tmp, "dist"),
});
const controller = new AbortController();
await builder.listen(() => Promise.resolve<App<unknown>>(app), {
signal: controller.signal,
async onListen(addr) {
const res = await fetch(`http://localhost:${addr.port}/invalid`);
const text = await res.text();
expect(text).toEqual("it works");
controller.abort();
},
});
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "Builder - serves static files in subdir",
fn: async () => {
const root = path.join(import.meta.dirname!, "..", "..");
await using _tmp = await withTmpDir({ dir: root, prefix: "tmp_builder_" });
const tmp = _tmp.dir;
const app = new App()
.use(staticFiles())
.get("/", () => new Response("no"));
await writeFiles(tmp, {
"static/foo.txt": "ok",
"static/test/foo.txt": "ok",
});
const builder = new Builder({
root: tmp,
});
const controller = new AbortController();
const waiter = Promise.withResolvers<void>();
await builder.listen(() => Promise.resolve<App<unknown>>(app), {
signal: controller.signal,
async onListen(addr) {
try {
let res = await fetch(`http://localhost:${addr.port}/foo.txt`);
expect(await res.text()).toEqual("ok");
res = await fetch(`http://localhost:${addr.port}/test/foo.txt`);
expect(await res.text()).toEqual("ok");
controller.abort();
waiter.resolve();
} catch (err) {
waiter.reject(err);
}
},
});
await waiter.promise;
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "Builder - serves static files in subdir in prod",
fn: async () => {
const root = path.join(import.meta.dirname!, "..", "..");
await using _tmp = await withTmpDir({ dir: root, prefix: "tmp_builder_" });
const tmp = _tmp.dir;
await writeFiles(tmp, {
"main.ts": `import { App, staticFiles } from "fresh";
export const app = new App()
.use(staticFiles());`,
"static/foo.txt": "ok",
"static/test/foo.txt": "ok",
});
await new Builder({ root: tmp }).build();
await withChildProcessServer(
{ cwd: tmp, args: ["serve", "-A", "_fresh/server.js"] },
async (address) => {
let res = await fetch(`${address}/foo.txt`);
expect(await res.text()).toEqual("ok");
res = await fetch(`${address}/test/foo.txt`);
expect(await res.text()).toEqual("ok");
},
);
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "Builder - dev server error_overlay ignores _app and _layout",
fn: async () => {
const root = path.join(import.meta.dirname!, "..", "..");
await using _tmp = await withTmpDir({ dir: root, prefix: "tmp_builder_" });
const tmp = _tmp.dir;
const appLayoutSpy = fn(() => "app or layout") as () => string;
const app = new App()
.appWrapper(appLayoutSpy)
.layout("/", appLayoutSpy);
const builder = new Builder({
root: tmp,
outDir: path.join(tmp, "dist"),
});
const controller = new AbortController();
await builder.listen(() => Promise.resolve<App<unknown>>(app), {
signal: controller.signal,
async onListen(addr) {
const res = await fetch(
`http://localhost:${addr.port}/${DEV_ERROR_OVERLAY_URL}?message=__ok__`,
);
const text = await res.text();
expect(text).toMatch(/__ok__/);
expect(appLayoutSpy).toHaveBeenCalledTimes(0);
controller.abort();
},
});
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
// Currently waiting on bug fixes in @deno/loader
// to support resolving without passing entry points
ignore: true,
name: "Builder - mapped islands",
fn: async () => {
const root = path.join(import.meta.dirname!, "..", "..");
await using _tmp = await withTmpDir({ dir: root, prefix: "tmp_builder_" });
const tmp = _tmp.dir;
await writeFiles(tmp, {
"other/Foo.tsx": `export default () => <h1>ok</h1>;`,
"routes/index.tsx": `import Foo from "foo-island";
export default () => <Foo />;`,
"main.ts": `import { App } from "fresh";
export const app = new App().fsRoutes()`,
"deno.json": JSON.stringify({
imports: { "foo-island": "other/Foo.tsx" },
}),
});
const builder = new Builder({
root: tmp,
outDir: path.join(tmp, "dist"),
});
builder.registerIsland("foo-island");
await builder.build();
let text = "fail";
await withChildProcessServer(
{ cwd: tmp, args: ["serve", "-A", "dist/server.js"] },
async (address) => {
const res = await fetch(address);
text = await res.text();
},
);
expect(text).toContain("<h1>ok</h1>");
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "Builder - source maps",
fn: async () => {
const root = path.join(import.meta.dirname!, "..", "..");
await using _tmp = await withTmpDir({ dir: root, prefix: "tmp_builder_" });
const tmp = _tmp.dir;
await writeFiles(tmp, {
"islands/Foo.tsx": `export const Foo = () => <h1>hello</h1>`,
"routes/index.ts": `export const handler = () => new Response("ok")`,
"main.ts": `import { App } from "fresh";
export const app = new App().fsRoutes()`,
});
const builder = new Builder({
root: tmp,
outDir: path.join(tmp, "dist"),
sourceMap: {
kind: "external",
sourceRoot: "foo",
sourcesContent: true,
},
});
await builder.build();
const assetDir = path.join(
builder.config.outDir,
"static",
"_fresh",
"js",
builder.config.buildId,
);
const entries = await Array.fromAsync(Deno.readDir(assetDir));
const map = entries.find((entry) =>
entry.isFile && entry.name.endsWith(".js.map")
);
if (!map) throw new Error(`Sourcemap not found`);
const content = await Deno.readTextFile(path.join(assetDir, map.name));
const json = JSON.parse(content) as {
version: 3;
sources: string[];
sourceRoot?: string;
sourcesContent: string[];
mappings: string;
names?: string[];
};
expect(json.sourcesContent.length).toBeGreaterThan(0);
expect(json.sourcesContent.length).toBeGreaterThan(0);
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "Builder - compile entry",
fn: async () => {
const root = path.join(import.meta.dirname!, "..", "..");
await using _tmp = await withTmpDir({ dir: root, prefix: "tmp_builder_" });
await using _outDir = await withTmpDir();
const tmp = _tmp.dir;
await writeFiles(tmp, {
"deno.json": JSON.stringify({
links: [path.relative(tmp, root)],
workspace: [],
compilerOptions: {
jsx: "react-jsx",
jsxImportSource: "preact",
},
imports: {
"fresh": "jsr:@fresh/core@*",
"preact": "npm:preact@*",
"@preact/signals": "npm:@preact/signals@*",
},
}),
"islands/Foo.tsx": `export const Foo = () => <h1>hello</h1>`,
"routes/index.ts": `export const handler = () => new Response("ok")`,
"static/foo.txt": "ok",
"main.ts": `import { App, staticFiles } from "fresh";
export const app = new App()
.use(staticFiles())
.fsRoutes();`,
});
const builder = new Builder({
root: tmp,
});
await builder.build();
const outBin = path.join(_outDir.dir, "fresh-compiled");
const bin = Deno.build.os === "windows" ? "deno.exe" : "deno";
const cp = await new Deno.Command(bin, {
args: [
"compile",
"-A",
"--include",
"static/",
"--include",
"_fresh",
"--output",
outBin,
path.join("_fresh", "compiled-entry.js"),
],
cwd: tmp,
}).output();
const { stderr, stdout } = getStdOutput(cp);
// deno-lint-ignore no-console
console.log(stdout);
// deno-lint-ignore no-console
console.log(stderr);
await withChildProcessServer({
bin: outBin,
cwd: _outDir.dir,
args: [],
env: {
PORT: "0",
HOSTNAME: "127.0.0.1",
},
}, async (address) => {
let res = await fetch(address);
expect(await res.text()).toEqual("ok");
res = await fetch(`${address}/foo.txt`);
expect(await res.text()).toEqual("ok");
});
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "Builder - island that imports json entry",
fn: async () => {
const root = path.join(import.meta.dirname!, "..", "..");
await using _tmp = await withTmpDir({ dir: root, prefix: "tmp_builder_" });
await using _outDir = await withTmpDir();
const tmp = _tmp.dir;
await writeFiles(tmp, {
"deno.json": JSON.stringify({
links: [path.relative(tmp, root)],
workspace: [],
compilerOptions: {
jsx: "react-jsx",
jsxImportSource: "preact",
},
imports: {
"fresh": "jsr:@fresh/core@*",
"preact": "npm:preact@*",
"@preact/signals": "npm:@preact/signals@*",
"mime-db": "npm:mime-db@*",
},
}),
"islands/Foo.tsx": `import * as mime from "mime-db"
export const Foo = () => {
console.log(mime);
return <h1>ok</h1>
}`,
"routes/index.ts": `export default () => <Foo />`,
"main.ts": `import { App, staticFiles } from "fresh";
export const app = new App()
.use(staticFiles())
.fsRoutes();`,
});
const builder = new Builder({
root: tmp,
});
await builder.build();
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test("specToName", () => {
// HTTP
expect(specToName("http://example.com")).toEqual("example");
expect(specToName("http://example.com:8000")).toEqual("example");
expect(specToName("http://example.com:8000/foo/bar")).toEqual(
"bar",
);
// HTTPS
expect(specToName("https://example.com")).toEqual("example");
expect(specToName("https://example.com:8000")).toEqual("example");
expect(specToName("https://example.com:8000/foo/bar")).toEqual(
"bar",
);
// JSR
expect(specToName("jsr:@foo/bar")).toEqual("foo_bar");
expect(specToName("jsr:@foo/bar@1.0.0")).toEqual("foo_bar");
expect(specToName("jsr:@foo/bar@^1.0.0")).toEqual("foo_bar");
expect(specToName("jsr:@foo/bar@~1.0.0")).toEqual("foo_bar");
expect(specToName("jsr:@foo/bar@~1.0.0-alpha.32")).toEqual("foo_bar");
expect(specToName("jsr:@foo/bar@~1.0.0-alpha.32/asdf")).toEqual("asdf");
expect(specToName("jsr:@foo/bar/asdf")).toEqual("asdf");
// npm
expect(specToName("npm:foo")).toEqual("foo");
expect(specToName("npm:foo/bar")).toEqual("bar");
expect(specToName("npm:foo@1.0.0")).toEqual("foo");
expect(specToName("npm:foo@^1.0.0")).toEqual("foo");
expect(specToName("npm:foo@~1.0.0-alpha.32")).toEqual("foo");
expect(specToName("npm:@foo/bar")).toEqual("foo_bar");
expect(specToName("npm:@foo/bar/asdf")).toEqual("asdf");
expect(specToName("npm:@foo/bar@1.0.0")).toEqual("foo_bar");
expect(specToName("npm:@foo/bar@^1.0.0")).toEqual("foo_bar");
expect(specToName("npm:@foo/bar@~1.0.0-alpha.32")).toEqual("foo_bar");
// other
expect(specToName("foo")).toEqual("foo");
expect(specToName("@foo/bar")).toEqual("foo_bar");
expect(specToName("foo/bar")).toEqual("bar");
expect(specToName("@foo/bar/asdf")).toEqual("asdf");
expect(specToName("islands/foo.v2.tsx")).toEqual("foo_v2");
expect(specToName("/islands/_bar-baz-...-$.tsx")).toEqual("_bar_baz_$");
expect(specToName("/islands/1_hello.tsx")).toEqual("_hello");
});
+73
View File
@@ -0,0 +1,73 @@
import * as JSONC from "@std/jsonc";
import * as path from "@std/path";
export interface DenoConfig {
workspace?: string[];
compilerOptions?: {
jsx?: string;
jsxImportSource?: string;
jsxPrecompileSkipElements?: string[];
};
}
export async function checkDenoCompilerOptions(root: string) {
const denoJson = await findNearestDenoConfigWithCompilerOptions(
root,
);
const jsxImportSource = denoJson.config.compilerOptions?.jsxImportSource;
if (jsxImportSource === undefined) {
throw new Error(
`Option compilerOptions > jsxImportSource not set in: ${denoJson.filePath}`,
);
}
// Check precompile option
if (denoJson.config.compilerOptions?.jsx === "precompile") {
const expected = ["a", "img", "source", "body", "html", "head"];
const skipped = denoJson.config.compilerOptions.jsxPrecompileSkipElements;
if (!skipped || expected.some((name) => !skipped.includes(name))) {
throw new Error(
`Expected option compilerOptions > jsxPrecompileSkipElements to contain ${
expected.map((name) => `"${name}"`).join(", ")
}`,
);
}
}
return { jsxImportSource, denoJson: denoJson.filePath };
}
export async function findNearestDenoConfigWithCompilerOptions(
directory: string,
): Promise<{ config: DenoConfig; filePath: string }> {
let dir = directory;
while (true) {
for (const name of ["deno.json", "deno.jsonc"]) {
const filePath = path.join(dir, name);
try {
const file = await Deno.readTextFile(filePath);
let config;
if (name.endsWith(".jsonc")) {
config = JSONC.parse(file);
} else {
config = JSON.parse(file);
}
if (config.compilerOptions) return { config, filePath };
if (config.workspace) break;
break;
} catch (err) {
if (!(err instanceof Deno.errors.NotFound)) {
throw err;
}
}
}
const parent = path.dirname(dir);
if (parent === dir) break;
dir = parent;
}
throw new Error(
`Could not find a deno.json or deno.jsonc file in the current directory or any parent directory that contains a 'compilerOptions' field.`,
);
}
+556
View File
@@ -0,0 +1,556 @@
import {
type BuildCache,
IslandPreparer,
type StaticFile,
} from "../build_cache.ts";
import * as path from "@std/path";
import * as pathWin32 from "@std/path/windows";
import { encodeHex } from "@std/encoding/hex";
import { fsAdapter } from "../fs.ts";
import type { FileTransformer } from "./file_transformer.ts";
import { assertInDir, pathToSpec } from "../utils.ts";
import type { ResolvedBuildConfig } from "./builder.ts";
import { fsItemsToCommands, type FsRouteFile } from "../fs_routes.ts";
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;
content: Uint8Array;
}
export interface IslandModChunk {
name: string;
server: string;
browser: string | null;
}
export type FsRouteFileNoMod<State> = Omit<FsRouteFile<State>, "mod"> & {
lazy: boolean;
};
export interface FsRoute<State> {
id: string;
dir: string;
files: FsRouteFileNoMod<State>[];
}
export interface DevBuildCache<State> extends BuildCache<State> {
islandModNameToChunk: Map<string, IslandModChunk>;
addUnprocessedFile(pathname: string, dir: string): void;
addProcessedFile(
pathname: string,
content: Uint8Array,
hash: string | null,
): Promise<void>;
flush(): Promise<void>;
prepare(): Promise<void>;
}
export class MemoryBuildCache<State> implements DevBuildCache<State> {
#processedFiles = new Map<string, MemoryFile>();
#unprocessedFiles = new Map<string, string>();
#config: ResolvedBuildConfig;
#transformer: FileTransformer;
islandModNameToChunk = new Map<string, IslandModChunk>();
#fsRoutes: FsRoute<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>[] {
return this.#commands;
}
async readFile(pathname: string): Promise<StaticFile | null> {
const processed = this.#processedFiles.get(pathname);
if (processed !== undefined) {
return {
hash: processed.hash,
readable: processed.content,
size: processed.content.byteLength,
contentType: processed.contentType,
close: () => {},
};
}
const unprocessed = this.#unprocessedFiles.get(pathname);
if (unprocessed !== undefined) {
try {
const [stat, file] = await Promise.all([
Deno.stat(unprocessed),
Deno.open(unprocessed, { read: true }),
]);
return {
hash: null,
size: stat.size,
readable: file.readable,
contentType: getContentType(unprocessed),
close: () => file.close(),
};
} catch {
return null;
}
}
let entry = pathname.startsWith("/") ? pathname.slice(1) : pathname;
entry = path.join(this.#config.staticDir, entry);
const relative = path.relative(this.#config.staticDir, entry);
if (relative.startsWith("..")) {
throw new Error(
`Processed file resolved outside of static dir ${entry}`,
);
}
// Might be a file that we still need to process
const transformed = await this.#transformer.process(
entry,
"development",
this.#config.target,
);
if (transformed !== null) {
for (let i = 0; i < transformed.length; i++) {
const file = transformed[i];
const relative = path.relative(this.#config.staticDir, file.path);
if (relative.startsWith(".")) {
throw new Error(
`Processed file resolved outside of static dir ${file.path}`,
);
}
const pathname = new URL(relative, "http://localhost").pathname;
this.addProcessedFile(pathname, file.content, null);
}
if (this.#processedFiles.has(pathname)) {
return this.readFile(pathname);
}
} else {
try {
const filePath = path.join(this.#config.staticDir, pathname);
const relative = path.relative(this.#config.staticDir, filePath);
if (!relative.startsWith(".") && (await Deno.stat(filePath)).isFile) {
const pathname = new URL(relative, "http://localhost").pathname;
this.addUnprocessedFile(pathname, this.#config.staticDir);
return this.readFile(pathname);
}
} catch (err) {
if (!(err instanceof Deno.errors.NotFound)) {
throw err;
}
}
}
return null;
}
addUnprocessedFile(pathname: string, dir: string): void {
this.#unprocessedFiles.set(
pathname,
path.join(dir, pathname),
);
}
// deno-lint-ignore require-await
async addProcessedFile(
pathname: string,
content: Uint8Array,
hash: string | null,
): Promise<void> {
this.#processedFiles.set(pathname, {
content,
hash,
contentType: getContentType(pathname),
});
}
async flush(): Promise<void> {
const preparer = new IslandPreparer();
// Load islands
await Promise.all(
Array.from(this.islandModNameToChunk.entries()).map(
async ([name, chunk]) => {
const fileUrl = maybeToFileUrl(chunk.server);
const mod = await import(fileUrl);
if (chunk.browser === null) {
throw new Error(`Unexpected missing browser chunk`);
}
preparer.prepare(this.islandRegistry, mod, chunk.browser, name);
},
),
);
}
async prepare(): Promise<void> {
// Load FS routes
const files = await Promise.all(this.#fsRoutes.files.map(async (file) => {
const fileUrl = maybeToFileUrl(file.filePath);
return {
...file,
mod: file.lazy ? () => import(fileUrl) : await import(fileUrl),
};
}));
this.#commands = fsItemsToCommands(files);
}
}
export class DiskBuildCache<State> implements DevBuildCache<State> {
#processedFiles = new Map<string, string | null>();
#unprocessedFiles = new Map<string, string>();
#transformer: FileTransformer;
#config: ResolvedBuildConfig;
islandModNameToChunk = new Map<string, IslandModChunk>();
#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;
this.root = config.root;
}
getFsRoutes(): Command<State>[] {
return [];
}
addUnprocessedFile(pathname: string, dir: string): void {
this.#unprocessedFiles.set(
pathname.replaceAll(WINDOWS_SEPARATOR, "/"),
path.join(dir, pathname),
);
}
async addProcessedFile(
pathname: string,
content: Uint8Array,
hash: string | null,
) {
this.#processedFiles.set(pathname, hash);
const outDir = pathname === "/metafile.json"
? this.#config.outDir
: path.join(this.#config.outDir, "static");
const filePath = path.join(outDir, pathname);
assertInDir(filePath, outDir);
await fsAdapter.mkdirp(path.dirname(filePath));
await Deno.writeFile(filePath, content);
}
// deno-lint-ignore require-await
async readFile(_pathname: string): Promise<StaticFile | null> {
throw new Error("Not implemented in build mode");
}
async prepare(): Promise<void> {
// not needed
}
async flush(): Promise<void> {
const { staticDir, outDir, target, root } = this.#config;
if (await fsAdapter.isDirectory(staticDir)) {
const entries = fsAdapter.walk(staticDir, {
includeDirs: false,
includeFiles: true,
followSymlinks: false,
// Skip any folder or file starting with a "."
skip: [/\/\.[^/]+(\/|$)/],
});
for await (const entry of entries) {
// OutDir might be inside static dir
if (!path.relative(outDir, entry.path).startsWith("..")) {
continue;
}
const result = await this.#transformer.process(
entry.path,
"production",
target,
);
if (result !== null) {
for (let i = 0; i < result.length; i++) {
const file = result[i];
assertInDir(file.path, staticDir);
const pathname = `/${path.relative(staticDir, file.path)}`;
await this.addProcessedFile(pathname, file.content, null);
}
} else {
const relative = path.relative(staticDir, entry.path);
const pathname = `/${relative}`;
this.addUnprocessedFile(pathname, staticDir);
}
}
}
const staticFiles: PendingStaticFile[] = [];
for (const [name, filePath] of this.#unprocessedFiles.entries()) {
staticFiles.push({ filePath, pathname: name, hash: null });
}
for (const [name, maybeHash] of this.#processedFiles.entries()) {
// 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 });
}
const islandSpecifiers: string[] = [];
for (const spec of this.islandModNameToChunk.keys()) {
islandSpecifiers.push(spec);
}
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,
}),
);
// 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",
}),
);
await Deno.writeTextFile(
path.join(outDir, "compiled-entry.js"),
`import fetcher from "./server.js";
Deno.serve(
{ port: Deno.env.get("PORT"), hostname: Deno.env.get("HOSTNAME") },
fetcher.fetch
);`,
);
}
}
const EDIT_WARNING =
`// WARNING: DO NOT EDIT THIS FILE. It is autogenerated by Fresh.`;
export async function hashContent(
content: Uint8Array | ReadableStream<Uint8Array>,
): Promise<string> {
const buffer = await new Response(content).arrayBuffer();
const hashBuf = await crypto.subtle.digest(
"SHA-256",
buffer,
);
return encodeHex(hashBuf);
}
export function getContentType(filePath: string): string {
const ext = path.extname(filePath);
return getStdContentType(ext) ?? "text/plain";
}
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 {
let rootPath = `path.join(import.meta.dirname, ${
JSON.stringify(options.root)
})`;
if (path.isAbsolute(options.root)) {
// deno-lint-ignore no-console
console.warn(
`WARN: using absolute root path in snapshot: "${options.root}"`,
);
rootPath = JSON.stringify(options.root);
}
return `${EDIT_WARNING}
import { setBuildCache, ProdBuildCache, path } from "fresh/internal";
import * as snapshot from "${options.snapshotSpecifier}";
import { app } from "${options.serverEntry}";
const root = ${rootPath};
setBuildCache(app, new ProdBuildCache(root, snapshot), "production");
export default {
fetch: app.handler()
};
`;
}
function getClientEntry(buildId: string) {
return `/_fresh/js/${buildId}/fresh-runtime.js`;
}
@@ -0,0 +1,46 @@
import { expect } from "@std/expect";
import { MemoryBuildCache } from "./dev_build_cache.ts";
import { FileTransformer } from "./file_transformer.ts";
import { createFakeFs, withTmpDir } from "../test_utils.ts";
import type { ResolvedBuildConfig } from "./builder.ts";
Deno.test({
name: "MemoryBuildCache - should error if reading outside of staticDir",
fn: async () => {
await using _tmp = await withTmpDir();
const tmp = _tmp.dir;
const config: ResolvedBuildConfig = {
root: tmp,
mode: "development",
buildId: "",
ignore: [],
islandDir: "",
outDir: "",
routeDir: "",
staticDir: "",
target: "latest",
};
const fileTransformer = new FileTransformer(createFakeFs({}), tmp);
const buildCache = new MemoryBuildCache(
config,
{ dir: "", files: [], id: "" },
fileTransformer,
);
const thrown = buildCache.readFile("../SECRETS.txt");
const thrown2 = buildCache.readFile("./../../SECRETS.txt");
const noThrown = buildCache.readFile("styles.css");
const noThrown2 = buildCache.readFile(".well-known/foo.txt");
const noThrown3 = buildCache.readFile("./styles.css");
const noThrown4 = buildCache.readFile("./.well-known/foo.txt");
await buildCache.flush();
const err = "Processed file resolved outside of static dir";
await expect(thrown).rejects.toThrow(err);
await expect(thrown2).rejects.toThrow(err);
await expect(noThrown).resolves.toBe(null);
await expect(noThrown2).resolves.toBe(null);
await expect(noThrown3).resolves.toBe(null);
await expect(noThrown4).resolves.toBe(null);
},
});
+236
View File
@@ -0,0 +1,236 @@
import { denoPlugin } from "@deno/esbuild-plugin";
import type { BuildOptions, Plugin as EsbuildPlugin } from "esbuild";
import * as path from "@std/path";
export interface FreshBundleOptions {
dev: boolean;
cwd: string;
buildId: string;
outDir: string;
denoJsonPath: string;
entryPoints: Record<string, string>;
target: string | string[];
jsxImportSource?: string;
sourceMap?: {
/** Documentation: https://esbuild.github.io/api/#sourcemap */
kind: BuildOptions["sourcemap"];
/** Documentation: https://esbuild.github.io/api/#source-root */
sourceRoot?: BuildOptions["sourceRoot"];
/** Documentation: https://esbuild.github.io/api/#sources-content */
sourcesContent?: BuildOptions["sourcesContent"];
};
}
export interface BuildOutput {
entryToChunk: Map<string, string>;
dependencies: Map<string, string[]>;
files: Array<{ hash: string | null; contents: Uint8Array; path: string }>;
}
let esbuild: null | typeof import("esbuild") = null;
const PREACT_ENV = Deno.env.get("PREACT_PATH");
export async function bundleJs(
options: FreshBundleOptions,
): Promise<BuildOutput> {
if (esbuild === null) {
await startEsbuild();
}
try {
await Deno.mkdir(options.cwd, { recursive: true });
} catch (err) {
if (!(err instanceof Deno.errors.AlreadyExists)) {
throw err;
}
}
const bundle = await esbuild!.build({
entryPoints: options.entryPoints,
platform: "browser",
target: options.target,
format: "esm",
bundle: true,
splitting: true,
treeShaking: true,
sourcemap: options.dev ? "linked" : options.sourceMap?.kind,
sourceRoot: options.dev ? undefined : options.sourceMap?.sourceRoot,
sourcesContent: options.dev ? undefined : options.sourceMap?.sourcesContent,
minify: !options.dev,
logOverride: {
"suspicious-nullish-coalescing": "silent",
"unsupported-jsx-comment": "silent",
},
jsxDev: options.dev,
jsx: "automatic",
jsxImportSource: options.jsxImportSource ?? "preact",
absWorkingDir: options.cwd,
outdir: ".",
write: false,
metafile: true,
define: {
"process.env.NODE_ENV": JSON.stringify(
options.dev ? "development" : "production",
),
},
plugins: [
preactDebugger(PREACT_ENV),
buildIdPlugin(options.buildId),
windowsPathFixer(),
denoPlugin({ preserveJsx: true, debug: false }),
],
});
const files: BuildOutput["files"] = [];
for (let i = 0; i < bundle.outputFiles.length; i++) {
const outputFile = bundle.outputFiles[i];
const relative = path.relative(options.cwd, outputFile.path);
files.push({
path: relative,
contents: outputFile.contents,
hash: outputFile.hash,
});
}
files.push({
path: "metafile.json",
contents: new TextEncoder().encode(JSON.stringify(bundle.metafile)),
hash: null,
});
const entryToChunk = new Map<string, string>();
const dependencies = new Map<string, string[]>();
const entryToName = new Map(
Array.from(Object.entries(options.entryPoints)).map(
(entry) => [entry[1], entry[0]],
),
);
if (bundle.metafile) {
const metaOutputs = new Map(Object.entries(bundle.metafile.outputs));
for (const [entryPath, entry] of metaOutputs.entries()) {
const imports = entry.imports
.filter(({ kind }) => kind === "import-statement")
.map(({ path }) => path);
dependencies.set(entryPath, imports);
// Map entries to chunks
if (entryPath !== "fresh-runtime.js" && entry.entryPoint !== undefined) {
const basename = path.basename(
entryPath,
path.extname(entryPath),
);
const filePath = options.entryPoints[basename];
const name = entryToName.get(filePath)!;
entryToChunk.set(name, entryPath);
}
}
}
if (!options.dev) {
esbuild = null;
}
return {
files,
entryToChunk,
dependencies,
};
}
let initialized = false;
export async function startEsbuild() {
esbuild = Deno.env.get("FRESH_ESBUILD_LOADER") === "portable"
? await import("esbuild-wasm")
: await import("esbuild");
if (!initialized) {
await esbuild.initialize({});
initialized = true;
}
}
function buildIdPlugin(buildId: string): EsbuildPlugin {
return {
name: "fresh-build-id",
setup(build) {
build.onResolve({ filter: /^(jsr:)?@fresh\/build-id(@.*)?$/ }, (args) => {
return {
path: args.path,
namespace: "fresh-internal",
};
});
build.onLoad({
filter: /^(jsr:)?@fresh\/build-id$/,
namespace: "fresh-internal",
}, () => {
return {
contents: `export const BUILD_ID = "${buildId}";`,
};
});
},
};
}
function toPreactModPath(mod: string): string {
if (mod === "preact/debug") {
return path.join("debug", "dist", "debug.module.js");
} else if (mod === "preact/hooks") {
return path.join("hooks", "dist", "hooks.module.js");
} else if (mod === "preact/devtools") {
return path.join("devtools", "dist", "devtools.module.js");
} else if (mod === "preact/compat") {
return path.join("compat", "dist", "compat.module.js");
} else if (mod === "preact/jsx-runtime" || mod === "preact/jsx-dev-runtime") {
return path.join("jsx-runtime", "dist", "jsxRuntime.module.js");
} else {
return path.join("dist", "preact.module.js");
}
}
function preactDebugger(preactPath: string | undefined): EsbuildPlugin {
return {
name: "fresh-preact-debugger",
setup(build) {
if (preactPath === undefined) return;
build.onResolve({ filter: /^preact/ }, (args) => {
const resolved = path.resolve(preactPath, toPreactModPath(args.path));
return {
path: resolved,
};
});
},
};
}
function windowsPathFixer(): EsbuildPlugin {
return {
name: "fresh-fix-windows",
setup(build) {
if (Deno.build.os === "windows") {
build.onResolve({ filter: /\.*/ }, (args) => {
if (args.path.startsWith("\\")) {
const normalized = path.resolve(args.path);
return {
path: normalized,
};
}
});
}
},
};
}
+272
View File
@@ -0,0 +1,272 @@
import { globToRegExp, isGlob } from "@std/path";
import type { FsAdapter } from "../fs.ts";
import { BUILD_ID } from "@fresh/build-id";
import { assetInternal } from "../runtime/shared_internal.tsx";
export type TransformMode = "development" | "production";
export interface OnTransformOptions {
pluginName: string;
filter: RegExp;
exclude?: Array<string | RegExp>;
}
export interface OnTransformResult {
content: string | Uint8Array;
path?: string;
map?: string | Uint8Array;
}
export interface OnTransformArgs {
path: string;
target: string | string[];
text: string;
content: Uint8Array;
mode: TransformMode;
root: string;
}
export type TransformFn = (
args: OnTransformArgs,
) =>
| void
| OnTransformResult
| Array<{ path: string } & Omit<OnTransformResult, "path">>
| Promise<
| void
| OnTransformResult
| Array<{ path: string } & Omit<OnTransformResult, "path">>
>;
export interface Transformer {
options: OnTransformOptions;
fn: TransformFn;
}
export interface ProcessedFile {
path: string;
content: Uint8Array;
map: Uint8Array | null;
inputFiles: string[];
}
interface TransformReq {
newFile: boolean;
filePath: string;
content: Uint8Array;
map: null | Uint8Array;
inputFiles: string[];
}
export class FileTransformer {
#transformers: Transformer[] = [];
#fs: FsAdapter;
#root: string;
constructor(fs: FsAdapter, root: string) {
this.#fs = fs;
this.#root = root;
}
onTransform(options: OnTransformOptions, callback: TransformFn): void {
this.#transformers.push({ options, fn: callback });
}
async process(
filePath: string,
mode: TransformMode,
target: string | string[],
): Promise<ProcessedFile[] | null> {
// Pre-check if we have any transformer for this file at all
let hasTransformer = false;
for (let i = 0; i < this.#transformers.length; i++) {
if (this.#transformers[i].options.filter.test(filePath)) {
hasTransformer = true;
break;
}
}
if (!hasTransformer) {
return null;
}
let content: Uint8Array;
try {
content = await this.#fs.readFile(filePath);
} catch (err) {
if (err instanceof Deno.errors.NotFound) {
return null;
}
throw err;
}
const queue: TransformReq[] = [{
newFile: false,
content,
filePath,
map: null,
inputFiles: [filePath],
}];
const outFiles: ProcessedFile[] = [];
const seen = new Set<string>();
let req: TransformReq | undefined = undefined;
while ((req = queue.pop()) !== undefined) {
if (seen.has(req.filePath)) continue;
seen.add(req.filePath);
let transformed = false;
outer: for (let i = 0; i < this.#transformers.length; i++) {
const transformer = this.#transformers[i];
const { options, fn } = transformer;
options.filter.lastIndex = 0;
if (!options.filter.test(req.filePath)) {
continue;
}
// Check if file is excluded
if (options.exclude !== undefined) {
for (let j = 0; j < options.exclude.length; j++) {
const exclude = options.exclude[j];
if (exclude instanceof RegExp) {
if (exclude.test(filePath)) {
continue outer;
}
} else if (isGlob(exclude)) {
const regex = globToRegExp(exclude);
if (regex.test(filePath)) {
continue outer;
}
} else if (filePath.includes(exclude)) {
continue outer;
}
}
}
const result = await fn({
path: req.filePath,
mode,
target,
content: req!.content,
root: this.#root,
get text() {
return new TextDecoder().decode(req!.content);
},
});
if (result !== undefined) {
if (Array.isArray(result)) {
for (let i = 0; i < result.length; i++) {
const item = result[i];
if (item.path === undefined) {
throw new Error(
`The ".path" property must be set when returning multiple files in a transformer. [${transformer.options.pluginName}]`,
);
}
const outContent = typeof item.content === "string"
? new TextEncoder().encode(item.content)
: item.content;
const outMap = item.map !== undefined
? typeof item.map === "string"
? new TextEncoder().encode(item.map)
: item.map
: null;
if (req.filePath === item.path) {
if (req.content === outContent && req.map === outMap) {
continue;
}
transformed = true;
req.content = outContent;
req.map = outMap;
} else {
let found = false;
for (let i = 0; i < queue.length; i++) {
const req = queue[i];
if (req.filePath === item.path) {
found = true;
transformed = true;
req.content = outContent;
req.map = outMap;
}
}
if (!found) {
queue.push({
newFile: true,
filePath: item.path,
content: outContent,
map: outMap,
inputFiles: req.inputFiles.slice(),
});
}
}
}
} else {
const outContent = typeof result.content === "string"
? new TextEncoder().encode(result.content)
: result.content;
const outMap = result.map !== undefined
? typeof result.map === "string"
? new TextEncoder().encode(result.map)
: result.map
: null;
if (req.content === outContent && req.map === outMap) {
continue;
}
transformed = true;
req.content = outContent;
req.map = outMap;
req.filePath = result.path ?? req.filePath;
}
}
}
// TODO: Keep transforming until no one processes anymore
if (transformed || req.newFile) {
outFiles.push({
content: req.content,
map: req.map,
path: req.filePath,
inputFiles: req.inputFiles,
});
}
}
return outFiles.length > 0 ? outFiles : null;
}
}
const CSS_URL_REGEX = /url\(("[^"]+"|'[^']+'|[^)]+)\)/g;
export function cssAssetHash(transformer: FileTransformer) {
transformer.onTransform({
pluginName: "fresh-css",
filter: /\.css$/,
}, (args) => {
const replaced = args.text.replaceAll(CSS_URL_REGEX, (_, str) => {
let rawUrl = str;
if (str[0] === "'" || str[0] === '"') {
rawUrl = str.slice(1, -1);
}
if (rawUrl.length === 0) {
return str;
}
return `url(${JSON.stringify(assetInternal(rawUrl, BUILD_ID))})`;
});
return {
content: replaced,
};
});
}
@@ -0,0 +1,247 @@
import { expect } from "@std/expect";
import type { FsAdapter } from "../fs.ts";
import { FileTransformer, type ProcessedFile } from "./file_transformer.ts";
import { delay } from "../test_utils.ts";
function testTransformer(files: Record<string, string>, root = "/") {
const mockFs: FsAdapter = {
cwd: () => root,
isDirectory: () => Promise.resolve(false),
mkdirp: () => Promise.resolve(),
walk: async function* foo() {
},
readFile: (file) => {
if (file instanceof URL) throw new Error("Not supported");
// deno-lint-ignore no-explicit-any
const content = (files as any)[file];
const buf = new TextEncoder().encode(content);
return Promise.resolve(buf);
},
readTextFile: (file) => {
if (file instanceof URL) throw new Error("Not supported");
// deno-lint-ignore no-explicit-any
const content = (files as any)[file];
return Promise.resolve(content);
},
};
return new FileTransformer(mockFs, root);
}
function consumeResult(result: ProcessedFile[]) {
const out: {
path: string;
content: string;
map: string | null;
inputFiles: string[];
}[] = [];
for (let i = 0; i < result.length; i++) {
const file = result[i];
out.push({
path: file.path,
content: typeof file.content === "string"
? file.content
: new TextDecoder().decode(file.content),
map: file.map !== null
? typeof file.map === "string"
? file.map
: new TextDecoder().decode(file.map)
: null,
inputFiles: file.inputFiles,
});
}
return out.sort((a, b) => a.path.localeCompare(b.path));
}
Deno.test("FileTransformer - transform sync", async () => {
const transformer = testTransformer({
"foo.txt": "foo",
});
transformer.onTransform({ pluginName: "foo", filter: /.*/ }, (args) => {
return {
content: args.text + "bar",
};
});
const result = await transformer.process("foo.txt", "development", "");
const files = await consumeResult(result!);
expect(files).toEqual([
{ content: "foobar", map: null, path: "foo.txt", inputFiles: ["foo.txt"] },
]);
});
Deno.test("FileTransformer - transform async", async () => {
const transformer = testTransformer({
"foo.txt": "foo",
});
transformer.onTransform({ pluginName: "foo", filter: /.*/ }, async (args) => {
await delay(1);
return {
content: args.text + "bar",
};
});
const result = await transformer.process("foo.txt", "development", "");
const files = await consumeResult(result!);
expect(files).toEqual([
{ content: "foobar", map: null, path: "foo.txt", inputFiles: ["foo.txt"] },
]);
});
Deno.test("FileTransformer - transform return Uint8Array", async () => {
const transformer = testTransformer({
"foo.txt": "foo",
});
transformer.onTransform({ pluginName: "foo", filter: /.*/ }, () => {
return {
content: new TextEncoder().encode("foobar"),
};
});
const result = await transformer.process("foo.txt", "development", "");
const files = await consumeResult(result!);
expect(files).toEqual([
{ content: "foobar", map: null, path: "foo.txt", inputFiles: ["foo.txt"] },
]);
});
Deno.test("FileTransformer - pass transformed content", async () => {
const transformer = testTransformer({
"input.txt": "input",
});
transformer.onTransform({ pluginName: "A", filter: /.*/ }, (args) => {
return {
content: args.text + " -> A",
};
});
transformer.onTransform({ pluginName: "B", filter: /.*/ }, (args) => {
return {
content: args.text + " -> B",
};
});
const result = await transformer.process("input.txt", "development", "");
const files = await consumeResult(result!);
expect(files).toEqual([
{
content: "input -> A -> B",
map: null,
path: "input.txt",
inputFiles: ["input.txt"],
},
]);
});
Deno.test(
"FileTransformer - pass transformed content with multiple",
async () => {
const transformer = testTransformer({
"input.txt": "input",
});
transformer.onTransform({ pluginName: "A", filter: /.*/ }, (args) => {
return [{
path: args.path,
content: args.text + " -> A",
}];
});
transformer.onTransform({ pluginName: "B", filter: /.*/ }, (args) => {
return {
content: args.text + " -> B",
};
});
const result = await transformer.process("input.txt", "development", "");
const files = await consumeResult(result!);
expect(files).toEqual([
{
content: "input -> A -> B",
map: null,
path: "input.txt",
inputFiles: ["input.txt"],
},
]);
},
);
Deno.test("FileTransformer - return multiple results", async () => {
const transformer = testTransformer({
"foo.txt": "foo",
});
const received: string[] = [];
transformer.onTransform({ pluginName: "A", filter: /foo\.txt$/ }, () => {
return [{
path: "a.txt",
content: "A",
}, {
path: "b.txt",
content: "B",
}];
});
transformer.onTransform({ pluginName: "B", filter: /.*/ }, (args) => {
received.push(args.path);
});
const result = await transformer.process("foo.txt", "development", "");
const files = await consumeResult(result!);
expect(files).toEqual([
{ content: "A", map: null, path: "a.txt", inputFiles: ["foo.txt"] },
{ content: "B", map: null, path: "b.txt", inputFiles: ["foo.txt"] },
]);
expect(received).toEqual(["foo.txt", "b.txt", "a.txt"]);
});
Deno.test(
"FileTransformer - track input files through temporary results",
async () => {
const transformer = testTransformer({
"foo.txt": "foo",
});
transformer.onTransform({ pluginName: "A", filter: /foo\.txt$/ }, () => {
return [{
path: "a.txt",
content: "A",
}, {
path: "b.txt",
content: "B",
}];
});
transformer.onTransform(
{ pluginName: "B", filter: /[ab]\.txt$/ },
(args) => {
return {
path: "c" + args.path,
content: args.text + "C",
};
},
);
const result = await transformer.process("foo.txt", "development", "");
const files = await consumeResult(result!);
expect(files).toEqual([
{ content: "AC", map: null, path: "ca.txt", inputFiles: ["foo.txt"] },
{ content: "BC", map: null, path: "cb.txt", inputFiles: ["foo.txt"] },
]);
},
);
Deno.test("FileTransformer - pass root to args", async () => {
const transformer = testTransformer({ "foo.txt": "foo" }, "/<root>/");
let root = "";
transformer.onTransform({ pluginName: "A", filter: /.*/ }, (args) => {
root = args.root;
return undefined;
});
await transformer.process("foo.txt", "development", "");
expect(root).toEqual("/<root>/");
});
+146
View File
@@ -0,0 +1,146 @@
import { type FsAdapter, 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";
import { pathToPattern } from "../router.ts";
import { CommandType } from "../commands.ts";
import { sortRoutePaths } from "../fs_routes.ts";
import type { RouteConfig } from "../types.ts";
const GROUP_REG = /[/\\\\]\((_[^/\\\\]+)\)[/\\\\]/;
export async function crawlRouteDir<State>(
fs: FsAdapter,
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 += "/";
}
}
routePattern = pathToPattern(id.slice(1));
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(
fs: FsAdapter,
dir: string,
callback: (entry: WalkEntry) => void | Promise<void>,
ignore: RegExp[],
) {
if (!await fs.isDirectory(dir)) return;
const entries = fs.walk(dir, {
includeDirs: false,
includeFiles: true,
exts: ["tsx", "jsx", "ts", "js"],
skip: ignore,
});
for await (const entry of entries) {
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 };
}
+20
View File
@@ -0,0 +1,20 @@
import { expect } from "@std/expect/expect";
import { createFakeFs } from "../test_utils.ts";
import { walkDir } from "./fs_crawl.ts";
Deno.test("walkDir - ", async () => {
const fs = createFakeFs({
"foo/bar/baz.txt": "foo",
"foo/bar.txt": "foo",
});
const files: string[] = [];
await walkDir(fs, "foo", async (entry) => {
// Purposely delay
await new Promise((r) => setTimeout(r, 100));
files.push(entry.path);
}, []);
expect(files).toEqual(["foo/bar/baz.txt", "foo/bar.txt"]);
});
@@ -0,0 +1,49 @@
import { eTag, ifNoneMatch } from "@std/http/etag";
import { generate } from "@std/uuid/v5";
import { NAMESPACE_URL } from "@std/uuid/constants";
import type { Middleware } from "../../middlewares/mod.ts";
/**
* Automatically detects workspace folders for DevTools in Chromium browsers.
*
* Without this middleware, if the feature is enabled and devTools is opened
* there will be 404 errors in the console. This can be annoying for developers,
* especially if there is logging for incoming requests.
*
* Enabling this feature can be helpful to make edits in DevTools change source
* files directly, for a small amount of code.
*
* The UUID is generated with a UUIDv5, so that the same directory should
* always generate the same UUID. This way, we can preserve the connected
* workspace across reloads without writing anything to disk.
*
* @see https://chromium.googlesource.com/devtools/devtools-frontend/+/main/docs/ecosystem/automatic_workspace_folders.md
*/
export function automaticWorkspaceFolders<T>(root: string): Middleware<T> {
let uuid: string | undefined;
let etag: string | undefined;
let content: string | undefined;
return async (ctx) => {
const { pathname } = ctx.url;
if (pathname !== "/.well-known/appspecific/com.chrome.devtools.json") {
return ctx.next();
}
uuid ??= await generate(
NAMESPACE_URL,
new TextEncoder().encode(
`https://fresh.deno.dev?root=${encodeURIComponent(root)}&v=${0}`,
),
);
content ??= JSON.stringify({ workspace: { root, uuid } }, undefined, 2);
etag ??= await eTag(content);
const noneMatchValue = ctx.req.headers.get("if-none-match");
if (!ifNoneMatch(noneMatchValue, etag)) {
return new Response(undefined, { status: 304, headers: { etag } });
}
return new Response(content, { status: 200, headers: { etag } });
};
}
@@ -0,0 +1,130 @@
import * as path from "@std/path";
function tabs2Spaces(str: string) {
return str.replace(/^\t+/, (tabs) => " ".repeat(tabs.length));
}
/**
* Generate an excerpt of the location in the source around the
* specified position.
*/
export function createCodeFrame(
text: string,
lineNum: number,
columnNum: number,
): string | undefined {
// Default settings
const before = 2;
const after = 3;
const lines = text.split("\n");
// Check if specified range is valid
if (lines.length <= lineNum || lines[lineNum].length < columnNum) {
return;
}
const start = Math.max(0, lineNum - before);
const end = Math.min(lines.length, lineNum + after + 1);
// Maximum space needed for line numbering in the current range.
// Necessary when the amount of digits of the line numbering grows:
// 999 | asdf
// 1000 | asdjadfjsa
const maxLineNum = String(end).length;
const padding = " ".repeat(maxLineNum);
// Normalize all indentation (=tabs) to use 2 spaces. We need to
// apply the difference to the marker position to move it back in
// place.
const spaceLines: string[] = [];
let maxLineLen = 0;
for (let i = start; i < end; i++) {
const line = tabs2Spaces(lines[i]);
spaceLines.push(line);
if (line.length > maxLineLen) maxLineLen = line.length;
}
const activeLine = spaceLines[lineNum - start];
// Move marker into correct place by taking the amount of
// normalized tabs into account
const count = Math.max(
0,
activeLine.length - lines[lineNum].length + columnNum,
);
const sep = "|";
let out = "";
for (let i = 0; i < spaceLines.length; i++) {
const line = spaceLines[i];
const currentLine = (padding + (i + start + 1)).slice(-maxLineNum);
// Line where the error occurred
if (i === lineNum - start) {
out += ">" + ` ${currentLine} ${sep} ${line}\n`;
const columnMarker = "^";
out += ` ${padding} ${sep} ${" ".repeat(count)}${columnMarker}\n`;
} else {
out += ` ${currentLine} ${sep} ${line}\n`;
}
}
return out;
}
const STACK_FRAME = /^\s*at\s+(?:(.*)\s+)?\((.*):(\d+):(\d+)\)$/;
export interface StackFrame {
fnName: string;
file: string;
line: number;
column: number;
}
function getFirstUserFile(
stack: string,
rootDir: string,
): StackFrame | undefined {
const lines = stack.split("\n");
for (let i = 0; i < lines.length; i++) {
const match = lines[i].match(STACK_FRAME);
if (match) {
const fnName = match[1] ?? "";
const file = match[2];
const line = +match[3];
const column = +match[4];
if (file.startsWith("file://")) {
const filePath = path.fromFileUrl(file);
if (path.relative(rootDir, filePath).startsWith(".")) {
continue;
}
return {
fnName,
file,
line,
column,
};
}
}
}
}
export function getCodeFrame(stack: string, rootDir: string) {
const file = getFirstUserFile(stack, rootDir);
if (file) {
try {
const filePath = path.fromFileUrl(file.file);
const text = Deno.readTextFileSync(filePath);
return createCodeFrame(
text,
file.line - 1,
file.column - 1,
);
} catch {
// Ignore
}
}
}
@@ -0,0 +1,33 @@
import { DEV_ERROR_OVERLAY_URL } from "../../../constants.ts";
import { HttpError } from "../../../error.ts";
import type { Middleware } from "../../../middlewares/mod.ts";
import { FreshScripts } from "../../../runtime/server/preact_hooks.tsx";
import { ErrorOverlay } from "./overlay.tsx";
export function devErrorOverlay<T>(): Middleware<T> {
return async (ctx) => {
const { config, url } = ctx;
if (url.pathname === config.basePath + DEV_ERROR_OVERLAY_URL) {
return ctx.render(<ErrorOverlay url={url} />);
}
try {
return await ctx.next();
} catch (err) {
if (ctx.req.headers.get("accept")?.includes("text/html")) {
let init: ResponseInit | undefined;
if (err instanceof HttpError) {
if (err.status < 500) throw err;
init = { status: err.status };
}
// At this point we're pretty sure to have a server error
// deno-lint-ignore no-console
console.error(err);
return ctx.render(<FreshScripts />, init);
}
throw err;
}
};
}
@@ -0,0 +1,105 @@
import { expect } from "@std/expect";
import { App } from "../../../app.ts";
import { FakeServer } from "../../../test_utils.ts";
import { devErrorOverlay } from "./middleware.tsx";
import { HttpError } from "../../../error.ts";
Deno.test("error overlay - show when error is thrown", async () => {
const app = new App();
app.use(devErrorOverlay());
app.config.mode = "development";
app.get("/", () => {
throw new Error("fail");
});
const server = new FakeServer(app.handler());
const res = await server.get("/", {
headers: {
accept: "text/html",
},
});
const content = await res.text();
expect(content).toContain("fresh-error-overlay");
});
Deno.test("error overlay - should not be visible for HttpError <500", async () => {
const app = new App();
app.use(devErrorOverlay());
app.config.mode = "development";
app
.get("/", () => {
throw new HttpError(404);
})
.get("/500", () => {
throw new HttpError(500);
});
const server = new FakeServer(app.handler());
let res = await server.get("/", {
headers: {
accept: "text/html",
},
});
let content = await res.text();
expect(content).not.toContain("fresh-error-overlay");
expect(res.status).toEqual(404);
res = await server.get("/500", {
headers: {
accept: "text/html",
},
});
content = await res.text();
expect(content).toContain("fresh-error-overlay");
expect(res.status).toEqual(500);
});
Deno.test(
"error overlay - should not be visible for HttpError <500 #2",
async () => {
const app = new App();
app.use(devErrorOverlay());
app.config.mode = "development";
app
.use(async (ctx) => {
try {
return await ctx.next();
} catch {
return ctx.render(<p>ok</p>);
}
})
.get("/", () => {
throw new HttpError(404);
});
const server = new FakeServer(app.handler());
const res = await server.get("/", {
headers: {
accept: "text/html",
},
});
const content = await res.text();
expect(content).not.toContain("fresh-error-overlay");
},
);
Deno.test("error overlay - should not be visible in prod", async () => {
const app = new App({ mode: "production" });
app.use(devErrorOverlay());
app.get("/", () => {
throw new HttpError(500);
});
const server = new FakeServer(app.handler());
const res = await server.get("/", {
headers: {
accept: "text/html",
},
});
const content = await res.text();
expect(content).not.toContain("fresh-error-overlay");
expect(res.status).toEqual(500);
});
@@ -0,0 +1,177 @@
import type { ComponentChildren } from "preact";
// Just to get some syntax highlighting
const css = (arr: TemplateStringsArray, ...exts: never[]) => {
if (exts.length) throw new Error("Not allowed");
return arr[0];
};
export const errorCss = css`
:root {
--bg: #fff;
--bg-code-frame: rgb(255, 0, 32, 0.1);
--bg-active-line: #fbcecc;
--text: #222;
--text2: #444;
--title: #e84644;
--code: #333;
font-family: sans-serif;
line-height: 1.4;
color: var(--text);
background: var(--bg);
}
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
@media (prefers-color-scheme: dark) {
:root {
--bg-code-frame: rgba(251, 93, 113, 0.2);
--bg-active-line: #4f1919;
--bg: #353535;
--text: #f7f7f7;
--text2: #ddd;
--code: #fdd1d1;
}
}
.inner {
max-width: 48rem;
padding: 4rem 1rem;
margin: 0 auto;
}
.title {
color: var(--title);
font-weight: normal;
font-size: 1.5rem;
margin-bottom: 1rem;
}
.code-frame {
overflow: auto;
padding: 0.5rem;
margin-bottom: 0.5rem;
background: var(--bg-code-frame);
color: var(--code);
}
.line {
padding: 0.25rem 0.5rem;
}
.active-line {
display: inline-block;
width: 100%;
background: var(--bg-active-line);
}
.stack {
overflow-x: auto;
}
.close-btn {
position: absolute;
top: 1rem;
right: 1rem;
color: var(--title);
display: block;
width: 3rem;
height: 3rem;
background: none;
border: none;
transform: translate3d(0, 0, 0);
}
.close-btn:active {
transform: translate3d(0, 2px, 0);
}
.close-btn:hover {
cursor: pointer;
filter: drop-shadow(0 0 0.75rem crimson);
}
`;
function CodeFrame(props: { codeFrame: string }) {
const lines: ComponentChildren[] = [];
props.codeFrame.trimEnd().split("\n").forEach(
(line, i, arr) => {
const vnode = (
<span
class={"line" + (line.startsWith(">") ? " active-line" : "")}
>
{line}
</span>
);
lines.push(vnode);
if (i < arr.length - 1) lines.push("\n");
},
);
return (
<pre class="code-frame">
<code>{lines}</code>
</pre>
);
}
const DEFAULT_MESSAGE = "Internal Server Error";
export function ErrorOverlay(props: { url: URL }) {
const url = props.url;
const title = url.searchParams.get("message") || DEFAULT_MESSAGE;
const stack = url.searchParams.get("stack");
const codeFrame = url.searchParams.get("code-frame");
if (title === DEFAULT_MESSAGE && !stack && !codeFrame) {
return null;
}
return (
<>
<div class="frsh-error-page">
<style
// deno-lint-ignore react-no-danger
dangerouslySetInnerHTML={{ __html: errorCss }}
/>
<div class="inner">
<div class="header">
<button
type="button"
class="close-btn"
aria-label="close"
id="close-btn"
>
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
strokeWidth={1.5}
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M9.75 9.75l4.5 4.5m0-4.5l-4.5 4.5M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg>
</button>
</div>
<div>
<h1 class="title">{title}</h1>
{codeFrame ? <CodeFrame codeFrame={codeFrame} /> : null}
{stack ? <pre class="stack">{stack}</pre> : null}
</div>
</div>
</div>
<script
// deno-lint-ignore react-no-danger
dangerouslySetInnerHTML={{
__html:
`document.querySelector("#close-btn").addEventListener("click", () => parent.postMessage("close-error-overlay"));`,
}}
/>
</>
);
}
@@ -0,0 +1,39 @@
import type { Middleware } from "../../middlewares/mod.ts";
import { ALIVE_URL } from "../../constants.ts";
// Live reload: Send updates to browser
export function liveReload<T>(): Middleware<T> {
const revision = Date.now();
return (ctx) => {
const { config, req, url } = ctx;
const aliveUrl = config.basePath + ALIVE_URL;
if (url.pathname === aliveUrl) {
if (req.headers.get("upgrade") !== "websocket") {
return new Response(null, { status: 501 });
}
// TODO: When a change is made the Deno server restarts,
// so for now the WebSocket connection is only used for
// the client to know when the server is back up. Once we
// have HMR we'll actively start sending messages back
// and forth.
const { response, socket } = Deno.upgradeWebSocket(req);
socket.addEventListener("open", () => {
socket.send(
JSON.stringify({
type: "initial-state",
revision,
}),
);
});
return response;
}
return ctx.next();
};
}
+10
View File
@@ -0,0 +1,10 @@
export {
Builder,
type BuildOptions,
type ResolvedBuildConfig,
} from "./builder.ts";
export {
type OnTransformArgs,
type OnTransformOptions,
type TransformFn,
} from "./file_transformer.ts";
+148
View File
@@ -0,0 +1,148 @@
import * as semver from "@std/semver";
import * as colors from "@std/fmt/colors";
import * as path from "@std/path";
import { CURRENT_FRESH_VERSION } from "../otel.ts";
export interface CheckFile {
last_checked: string;
last_shown?: string;
latest_version: string;
current_version: string;
}
function getHomeDir(): string | null {
switch (Deno.build.os) {
case "linux": {
const xdg = Deno.env.get("XDG_CACHE_HOME");
if (xdg) return xdg;
const home = Deno.env.get("HOME");
if (home) return `${home}/.cache`;
break;
}
case "darwin": {
const home = Deno.env.get("HOME");
if (home) return `${home}/Library/Caches`;
break;
}
case "windows":
return Deno.env.get("LOCALAPPDATA") ?? null;
}
return null;
}
function getFreshCacheDir(): string | null {
const home = getHomeDir();
if (home) return path.join(home, "fresh");
return null;
}
async function fetchLatestVersion() {
const res = await fetch("https://dl.deno.land/fresh/release-latest.txt");
if (res.ok) {
return (await res.text()).trim().replace(/^v/, "");
}
throw new Error(`Could not fetch latest version.`);
}
function readCurrentVersion() {
return CURRENT_FRESH_VERSION;
}
export async function updateCheck(
interval: number,
getCacheDir = getFreshCacheDir,
getLatestVersion = fetchLatestVersion,
getCurrentVersion = readCurrentVersion,
) {
// Skip update checks on CI or Deno Deploy
if (
Deno.env.get("CI") === "true" ||
Deno.env.get("FRESH_NO_UPDATE_CHECK") === "true" ||
Deno.env.get("DENO_DEPLOYMENT_ID")
) {
return;
}
const home = getCacheDir();
if (!home) return;
const filePath = path.join(home, "latest.json");
try {
await Deno.mkdir(home, { recursive: true });
} catch (err) {
if (!(err instanceof Deno.errors.AlreadyExists)) {
throw err;
}
}
const version = await getCurrentVersion();
let checkFile: CheckFile = {
current_version: version,
latest_version: version,
last_checked: new Date(0).toISOString(),
};
try {
const text = await Deno.readTextFile(filePath);
checkFile = JSON.parse(text);
} catch (err) {
if (!(err instanceof Deno.errors.NotFound)) {
throw err;
}
}
// Update current version
checkFile.current_version = version;
// Only check in the specified interval
if (Date.now() >= new Date(checkFile.last_checked).getTime() + interval) {
try {
checkFile.latest_version = await getLatestVersion();
checkFile.last_checked = new Date().toISOString();
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
// Update check is optional and shouldn't abort the program.
// deno-lint-ignore no-console
console.error(
colors.red(` Update check failed: `) + message,
);
return;
}
}
// Only show update message if current version is smaller than latest
const currentVersion = semver.parse(checkFile.current_version);
const latestVersion = semver.parse(checkFile.latest_version);
if (
(!checkFile.last_shown ||
Date.now() >= new Date(checkFile.last_shown).getTime() + interval) &&
semver.lessThan(currentVersion, latestVersion)
) {
checkFile.last_shown = new Date().toISOString();
const current = colors.bold(colors.rgb8(checkFile.current_version, 208));
const latest = colors.bold(colors.rgb8(checkFile.latest_version, 121));
// deno-lint-ignore no-console
console.log(
` Fresh ${latest} is available. You're on ${current}`,
);
// deno-lint-ignore no-console
console.log(
` To upgrade, run: deno run -A -r https://fresh.deno.dev/update`,
);
// deno-lint-ignore no-console
console.log();
}
// Migrate old format to current
if (!checkFile.last_shown) {
checkFile.last_shown = new Date().toISOString();
}
const raw = JSON.stringify(checkFile, null, 2);
await Deno.writeTextFile(filePath, raw);
}
+377
View File
@@ -0,0 +1,377 @@
import * as path from "@std/path";
import denoJson from "../../deno.json" with { type: "json" };
import { getStdOutput } from "../../tests/test_utils.tsx";
import { expect } from "@std/expect";
import { withTmpDir } from "../test_utils.ts";
import type { CheckFile } from "./update_check.ts";
import { WEEK } from "../constants.ts";
const CURRENT_VERSION = denoJson.version;
const cwd = import.meta.dirname!;
Deno.test("stores update check file in $HOME/fresh", async () => {
await using tmp = await withTmpDir();
const filePath = path.join(tmp.dir, "latest.json");
await new Deno.Command(Deno.execPath(), {
args: [
"run",
"-A",
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
],
cwd,
env: {
CI: "false",
TEST_HOME: tmp.dir,
},
}).output();
const text = JSON.parse(await Deno.readTextFile(filePath));
expect(text).toEqual({
current_version: CURRENT_VERSION,
latest_version: "99.99.999",
last_checked: text.last_checked,
last_shown: text.last_shown,
});
});
Deno.test("skips update check on specific environment variables", async (t) => {
const envs = ["FRESH_NO_UPDATE_CHECK", "CI", "DENO_DEPLOYMENT_ID"];
for (const env of envs) {
await t.step(`checking ${env}`, async () => {
await using tmp = await withTmpDir();
const out = await new Deno.Command(Deno.execPath(), {
args: [
"run",
"-A",
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
],
cwd,
env: {
[env]: "true",
TEST_HOME: tmp.dir,
LATEST_VERSION: "1.30.0",
},
stderr: "piped",
stdout: "piped",
}).output();
const { stdout } = getStdOutput(out);
expect(stdout).not.toMatch(/Fresh 1\.30\.0 is available/);
});
}
});
Deno.test("shows update message on version mismatch", async () => {
await using tmp = await withTmpDir();
const filePath = path.join(tmp.dir, "latest.json");
await Deno.writeTextFile(
filePath,
JSON.stringify({
current_version: "1.1.0",
latest_version: "1.1.0",
last_checked: new Date(0).toISOString(),
}),
);
const out = await new Deno.Command(Deno.execPath(), {
args: [
"run",
"-A",
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
],
cwd,
env: {
CI: "false",
TEST_HOME: tmp.dir,
LATEST_VERSION: "999.999.0",
},
stderr: "piped",
stdout: "piped",
}).output();
const { stdout } = getStdOutput(out);
expect(stdout).toMatch(/Fresh 999\.999\.0 is available/);
// Updates check file
const text = JSON.parse(await Deno.readTextFile(filePath));
expect(text).toEqual({
current_version: CURRENT_VERSION,
latest_version: "999.999.0",
last_checked: text.last_checked,
last_shown: text.last_shown,
});
});
Deno.test("only fetch new version defined by interval", async (t) => {
await using tmp = await withTmpDir();
await t.step("fetches latest version initially", async () => {
const out = await new Deno.Command(Deno.execPath(), {
args: [
"run",
"-A",
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
],
cwd,
env: {
CI: "false",
UPDATE_INTERVAL: "100000",
TEST_HOME: tmp.dir,
LATEST_VERSION: "1.30.0",
},
stderr: "piped",
stdout: "piped",
}).output();
const { stdout } = getStdOutput(out);
expect(stdout).toMatch(/fetching latest version/);
});
await t.step("should not fetch if interval has not passed", async () => {
const out = await new Deno.Command(Deno.execPath(), {
args: [
"run",
"-A",
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
],
cwd,
env: {
CI: "false",
UPDATE_INTERVAL: "100000",
TEST_HOME: tmp.dir,
LATEST_VERSION: "1.30.0",
},
stderr: "piped",
stdout: "piped",
}).output();
const { stdout } = getStdOutput(out);
expect(stdout).not.toMatch(/fetching latest version/);
});
await t.step("fetches if interval has passed", async () => {
const out = await new Deno.Command(Deno.execPath(), {
args: [
"run",
"-A",
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
],
cwd,
env: {
CI: "false",
UPDATE_INTERVAL: "1 ",
TEST_HOME: tmp.dir,
LATEST_VERSION: "1.30.0",
},
}).output();
const { stdout } = getStdOutput(out);
expect(stdout).toMatch(/fetching latest version/);
});
});
Deno.test("updates current version in cache file", async () => {
await using tmp = await withTmpDir();
const checkFile: CheckFile = {
current_version: "1.2.0",
latest_version: "1.2.0",
last_checked: new Date(Date.now() - WEEK).toISOString(),
};
await Deno.writeTextFile(
path.join(tmp.dir, "latest.json"),
JSON.stringify(checkFile, null, 2),
);
const out = await new Deno.Command(Deno.execPath(), {
args: [
"run",
"-A",
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
],
cwd,
env: {
CI: "false",
TEST_HOME: tmp.dir,
LATEST_VERSION: CURRENT_VERSION,
},
stderr: "piped",
stdout: "piped",
}).output();
const { stdout } = getStdOutput(out);
expect(stdout).not.toMatch(/Fresh .* is available/);
});
Deno.test("only shows update message when current < latest", async () => {
await using tmp = await withTmpDir();
const checkFile: CheckFile = {
current_version: "9999.999.0",
latest_version: "1.2.0",
last_checked: new Date().toISOString(),
};
await Deno.writeTextFile(
path.join(tmp.dir, "latest.json"),
JSON.stringify(checkFile, null, 2),
);
const out = await new Deno.Command(Deno.execPath(), {
args: [
"run",
"-A",
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
],
cwd,
env: {
CI: "false",
TEST_HOME: tmp.dir,
LATEST_VERSION: CURRENT_VERSION,
CURRENT_VERSION: "99999.9999.0",
},
stderr: "piped",
stdout: "piped",
}).output();
const { stdout } = getStdOutput(out);
expect(stdout).not.toMatch(/Fresh .* is available/);
});
Deno.test("migrates to last_shown property", async () => {
await using tmp = await withTmpDir();
const checkFile: CheckFile = {
latest_version: "1.4.0",
current_version: "1.2.0",
last_checked: new Date().toISOString(),
};
await Deno.writeTextFile(
path.join(tmp.dir, "latest.json"),
JSON.stringify(checkFile, null, 2),
);
const out = await new Deno.Command(Deno.execPath(), {
args: [
"run",
"-A",
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
],
cwd,
env: {
CI: "false",
TEST_HOME: tmp.dir,
CURRENT_VERSION: "1.2.0",
LATEST_VERSION: "99999.9999.0",
},
stderr: "piped",
stdout: "piped",
}).output();
const { stdout } = getStdOutput(out);
expect(stdout).toMatch(/Fresh .* is available/);
const checkFileAfter = JSON.parse(
await Deno.readTextFile(
path.join(tmp.dir, "latest.json"),
),
);
// Check if last version was written
expect(typeof checkFileAfter.last_shown).toEqual("string");
});
Deno.test("doesn't show update if last_shown + interval >= today", async () => {
await using tmp = await withTmpDir();
const todayMinus1Hour = new Date();
todayMinus1Hour.setHours(todayMinus1Hour.getHours() - 1);
const checkFile: CheckFile = {
current_version: "1.2.0",
latest_version: "1.6.0",
last_checked: new Date().toISOString(),
last_shown: todayMinus1Hour.toISOString(),
};
await Deno.writeTextFile(
path.join(tmp.dir, "latest.json"),
JSON.stringify(checkFile, null, 2),
);
const out = await new Deno.Command(Deno.execPath(), {
args: [
"run",
"-A",
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
],
cwd,
env: {
CI: "false",
TEST_HOME: tmp.dir,
CURRENT_VERSION: "1.2.0",
LATEST_VERSION: "99999.9999.0",
},
stderr: "piped",
stdout: "piped",
}).output();
const { stdout } = getStdOutput(out);
expect(stdout).not.toMatch(/Fresh .* is available/);
});
Deno.test(
"shows update if last_shown + interval < today",
async () => {
await using tmp = await withTmpDir();
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
const checkFile: CheckFile = {
current_version: "1.2.0",
latest_version: "99.999.99",
last_checked: new Date().toISOString(),
last_shown: yesterday.toISOString(),
};
await Deno.writeTextFile(
path.join(tmp.dir, "latest.json"),
JSON.stringify(checkFile, null, 2),
);
const out = await new Deno.Command(Deno.execPath(), {
args: [
"run",
"-A",
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
],
cwd,
env: {
CI: "false",
TEST_HOME: tmp.dir,
CURRENT_VERSION: CURRENT_VERSION,
LATEST_VERSION: "99999.9999.0",
},
stderr: "piped",
stdout: "piped",
}).output();
const { stdout } = getStdOutput(out);
expect(stdout).toMatch(/Fresh .* is available/);
const checkFileAfter = JSON.parse(
await Deno.readTextFile(
path.join(tmp.dir, "latest.json"),
),
);
expect(checkFileAfter.last_shown).not.toEqual(yesterday.toISOString());
},
);