This reverts commit a1571b76ed.
It broke fresh.deno.dev :S
This commit is contained in:
@@ -42,10 +42,6 @@ jobs:
|
|||||||
working-directory: ./update
|
working-directory: ./update
|
||||||
run: deno publish
|
run: deno publish
|
||||||
|
|
||||||
- name: Publish @fresh/plugin-vite
|
|
||||||
working-directory: ./plugin-vite
|
|
||||||
run: deno publish
|
|
||||||
|
|
||||||
- name: Publish @fresh/examples
|
- name: Publish @fresh/examples
|
||||||
working-directory: ./examples
|
working-directory: ./examples
|
||||||
run: deno publish
|
run: deno publish
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
_fresh/
|
_fresh/
|
||||||
.vite/
|
|
||||||
vendor/
|
vendor/
|
||||||
node_modules/
|
node_modules/
|
||||||
.docs/
|
.docs/
|
||||||
|
|||||||
@@ -5,7 +5,6 @@
|
|||||||
"./init",
|
"./init",
|
||||||
"./plugin-tailwindcss",
|
"./plugin-tailwindcss",
|
||||||
"./plugin-tailwindcss-v3",
|
"./plugin-tailwindcss-v3",
|
||||||
"./plugin-vite",
|
|
||||||
"./update",
|
"./update",
|
||||||
"./www"
|
"./www"
|
||||||
],
|
],
|
||||||
@@ -15,12 +14,9 @@
|
|||||||
"exports": {
|
"exports": {
|
||||||
".": "./src/mod.ts",
|
".": "./src/mod.ts",
|
||||||
"./runtime": "./src/runtime/shared.ts",
|
"./runtime": "./src/runtime/shared.ts",
|
||||||
"./runtime-client": "./src/runtime/client/mod.tsx",
|
|
||||||
"./dev": "./src/dev/mod.ts",
|
"./dev": "./src/dev/mod.ts",
|
||||||
"./compat": "./src/compat.ts",
|
"./compat": "./src/compat.ts",
|
||||||
"./internal": "./src/internals.ts",
|
"./do-not-use": "./src/internals.ts"
|
||||||
"./internal-dev": "./src/internals_dev.ts",
|
|
||||||
"./build-id": "./src/runtime/build_id.ts"
|
|
||||||
},
|
},
|
||||||
"tasks": {
|
"tasks": {
|
||||||
"test": "deno test -A --parallel",
|
"test": "deno test -A --parallel",
|
||||||
@@ -34,14 +30,7 @@
|
|||||||
"test:www": "deno test -A www/main_test.*",
|
"test:www": "deno test -A www/main_test.*",
|
||||||
"release": "deno run -A tools/release.ts"
|
"release": "deno run -A tools/release.ts"
|
||||||
},
|
},
|
||||||
"exclude": [
|
"exclude": ["**/_fresh/*", "**/tmp/*", "*/tests_OLD/**"],
|
||||||
"**/_fresh/*",
|
|
||||||
"**/tmp/*",
|
|
||||||
"*/tests_OLD/**",
|
|
||||||
"**/vite.config.ts.*",
|
|
||||||
"*/vite.config.ts.*",
|
|
||||||
"vite.config.ts.*"
|
|
||||||
],
|
|
||||||
"publish": {
|
"publish": {
|
||||||
"include": [
|
"include": [
|
||||||
"src/**",
|
"src/**",
|
||||||
|
|||||||
@@ -1,35 +0,0 @@
|
|||||||
# EXPERIMENTAL: vite plugin for Fresh
|
|
||||||
|
|
||||||
> **Warning** This package is experimental. Please report bugs to
|
|
||||||
> https://github.com/denoland/fresh/issues
|
|
||||||
|
|
||||||
## Usage
|
|
||||||
|
|
||||||
1. Run `deno install jsr:@fresh/plugin-vite npm:vite`
|
|
||||||
2. Ensure that your `deno.json` has the `fresh` import mapping:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"imports": {
|
|
||||||
"fresh": "jsr:@fresh/core"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
3. Update your `vite.config.ts` file:
|
|
||||||
|
|
||||||
```diff
|
|
||||||
import { defineConfig } from "vite";
|
|
||||||
+ import { fresh } from "@fresh/plugin-vite";
|
|
||||||
|
|
||||||
export default defineConfig({
|
|
||||||
plugins: [
|
|
||||||
+ fresh(),
|
|
||||||
],
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
4. Update your deno tasks respectively:
|
|
||||||
|
|
||||||
- Dev: `vite`
|
|
||||||
- Build: `vite build`
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
import { useState } from "preact/hooks";
|
|
||||||
|
|
||||||
export function Bar() {
|
|
||||||
const [count, set] = useState(0);
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
<h1>island asdf</h1>
|
|
||||||
<button type="button" onClick={() => set((v) => v + 1)}>
|
|
||||||
update {count}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
import { useSignal } from "@preact/signals";
|
|
||||||
|
|
||||||
export function Foo() {
|
|
||||||
const count = useSignal(0);
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
<h1>island</h1>
|
|
||||||
<button type="button" onClick={() => count.value++}>
|
|
||||||
update {count}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
import { useState } from "preact/hooks";
|
|
||||||
|
|
||||||
export function CounterHooks() {
|
|
||||||
const [count, set] = useState(0);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div class="counter-hooks">
|
|
||||||
<button type="button" onClick={() => set((v) => v + 1)}>
|
|
||||||
count: {count}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
import { App, staticFiles, trailingSlashes } from "fresh";
|
|
||||||
|
|
||||||
export const app = new App()
|
|
||||||
.use(staticFiles())
|
|
||||||
.use(trailingSlashes("never"))
|
|
||||||
.get("/", () => new Response("it works"))
|
|
||||||
.fsRoutes();
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
import { Bar } from "../islands/Bar.tsx";
|
|
||||||
import { Foo } from "../islands/Foo.tsx";
|
|
||||||
|
|
||||||
export const handler = () => {
|
|
||||||
return { data: {} };
|
|
||||||
};
|
|
||||||
|
|
||||||
export default function About() {
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
<h1>Hello from Vite</h1>
|
|
||||||
<p>This page is the prod Fresh build and served by vite</p>
|
|
||||||
<Foo />
|
|
||||||
<Bar />
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
export default function Index() {
|
|
||||||
return <h1>index page2</h1>;
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
import { CounterHooks } from "../../islands/tests/CounterHooks.tsx";
|
|
||||||
|
|
||||||
export default function Page() {
|
|
||||||
return <CounterHooks />;
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
export default function Page() {
|
|
||||||
return <h1>it works</h1>;
|
|
||||||
}
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
foo
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
it works
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
import { defineConfig } from "vite";
|
|
||||||
import { fresh } from "@fresh/plugin-vite";
|
|
||||||
import inspect from "vite-plugin-inspect";
|
|
||||||
|
|
||||||
export default defineConfig({
|
|
||||||
plugins: [
|
|
||||||
inspect(),
|
|
||||||
fresh(),
|
|
||||||
],
|
|
||||||
});
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "@fresh/plugin-vite",
|
|
||||||
"version": "0.0.1",
|
|
||||||
"license": "MIT",
|
|
||||||
"exports": {
|
|
||||||
".": "./src/mod.ts"
|
|
||||||
},
|
|
||||||
"compilerOptions": {
|
|
||||||
"jsx": "precompile",
|
|
||||||
"jsxImportSource": "preact"
|
|
||||||
},
|
|
||||||
"tasks": {
|
|
||||||
"demo": "vite demo",
|
|
||||||
"debug": "deno run -A --inspect-brk npm:vite demo",
|
|
||||||
"demo:build": "vite build demo",
|
|
||||||
"demo:start": "cd demo && deno serve -A _fresh/server/server-entry.mjs"
|
|
||||||
},
|
|
||||||
"imports": {
|
|
||||||
"@deno/loader": "jsr:@deno/loader@^0.3.2",
|
|
||||||
"@prefresh/vite": "npm:@prefresh/vite@^2.4.8",
|
|
||||||
"@types/node": "npm:@types/node@^24.1.0",
|
|
||||||
"preact": "npm:preact@^10.26.9",
|
|
||||||
"vite": "npm:vite@^7.0.6",
|
|
||||||
"vite-plugin-inspect": "npm:vite-plugin-inspect@^11.3.2"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,128 +0,0 @@
|
|||||||
import type { Plugin } from "vite";
|
|
||||||
import {
|
|
||||||
type FreshViteConfig,
|
|
||||||
pathWithRoot,
|
|
||||||
type ResolvedFreshViteConfig,
|
|
||||||
} from "./utils.ts";
|
|
||||||
import { deno } from "./plugins/deno.ts";
|
|
||||||
import prefresh from "@prefresh/vite";
|
|
||||||
import { serverEntryPlugin } from "./plugins/server_entry.ts";
|
|
||||||
import { clientEntryPlugin } from "./plugins/client_entry.ts";
|
|
||||||
import { devServer } from "./plugins/dev_server.ts";
|
|
||||||
import { buildIdPlugin } from "./plugins/build_id.ts";
|
|
||||||
import { clientSnapshot } from "./plugins/client_snapshot.ts";
|
|
||||||
import { serverSnapshot } from "./plugins/server_snapshot.ts";
|
|
||||||
|
|
||||||
export function fresh(config?: FreshViteConfig): Plugin[] {
|
|
||||||
const fConfig: ResolvedFreshViteConfig = {
|
|
||||||
serverEntry: config?.serverEntry ?? "main.ts",
|
|
||||||
islandsDir: config?.islandsDir ?? "islands",
|
|
||||||
routeDir: config?.routeDir ?? "routes",
|
|
||||||
ignore: config?.ignore ?? [],
|
|
||||||
};
|
|
||||||
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
name: "fresh",
|
|
||||||
config(config, env) {
|
|
||||||
return {
|
|
||||||
esbuild: {
|
|
||||||
jsx: "automatic",
|
|
||||||
jsxImportSource: "preact",
|
|
||||||
jsxDev: env.command === "serve",
|
|
||||||
},
|
|
||||||
resolve: {
|
|
||||||
alias: {
|
|
||||||
"react-dom/test-utils": "preact/test-utils",
|
|
||||||
"react-dom": "preact/compat",
|
|
||||||
react: "preact/compat",
|
|
||||||
},
|
|
||||||
noExternal: true,
|
|
||||||
},
|
|
||||||
optimizeDeps: {
|
|
||||||
include: [
|
|
||||||
"preact",
|
|
||||||
"preact/compat",
|
|
||||||
"preact/debug",
|
|
||||||
"preact/devtools",
|
|
||||||
"preact/hooks",
|
|
||||||
"preact/jsx-runtime",
|
|
||||||
"preact/jsx-dev-runtime",
|
|
||||||
"@preact/signals",
|
|
||||||
],
|
|
||||||
},
|
|
||||||
|
|
||||||
publicDir: pathWithRoot("static", config.root),
|
|
||||||
|
|
||||||
builder: {
|
|
||||||
async buildApp(builder) {
|
|
||||||
// Build client env first
|
|
||||||
const clientEnv = builder.environments.client;
|
|
||||||
if (clientEnv !== undefined) {
|
|
||||||
await builder.build(clientEnv);
|
|
||||||
}
|
|
||||||
|
|
||||||
await Promise.all(
|
|
||||||
Object.values(builder.environments).filter((env) =>
|
|
||||||
env !== clientEnv
|
|
||||||
).map((env) => builder.build(env)),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
},
|
|
||||||
environments: {
|
|
||||||
client: {
|
|
||||||
build: {
|
|
||||||
copyPublicDir: false,
|
|
||||||
manifest: true,
|
|
||||||
|
|
||||||
outDir: config.environments?.client?.build?.outDir ??
|
|
||||||
"_fresh/client",
|
|
||||||
rollupOptions: {
|
|
||||||
preserveEntrySignatures: "strict",
|
|
||||||
input: {
|
|
||||||
"client-entry": "fresh:client-entry",
|
|
||||||
"client-snapshot": "fresh:client-snapshot",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
ssr: {
|
|
||||||
build: {
|
|
||||||
manifest: false,
|
|
||||||
copyPublicDir: false,
|
|
||||||
|
|
||||||
outDir: config.environments?.ssr?.build?.outDir ??
|
|
||||||
"_fresh/server",
|
|
||||||
rollupOptions: {
|
|
||||||
input: {
|
|
||||||
"server-entry": "fresh:server_entry",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
},
|
|
||||||
configResolved(config) {
|
|
||||||
fConfig.islandsDir = pathWithRoot(fConfig.islandsDir, config.root);
|
|
||||||
fConfig.routeDir = pathWithRoot(fConfig.routeDir, config.root);
|
|
||||||
},
|
|
||||||
},
|
|
||||||
serverEntryPlugin(fConfig),
|
|
||||||
...serverSnapshot(fConfig),
|
|
||||||
clientEntryPlugin(),
|
|
||||||
clientSnapshot(fConfig),
|
|
||||||
buildIdPlugin(),
|
|
||||||
...devServer(),
|
|
||||||
prefresh({
|
|
||||||
include: [/\.[cm]?[tj]sx?$/],
|
|
||||||
exclude: [/node_modules/],
|
|
||||||
parserPlugins: [
|
|
||||||
"importMeta",
|
|
||||||
"explicitResourceManagement",
|
|
||||||
"topLevelAwait",
|
|
||||||
],
|
|
||||||
}),
|
|
||||||
deno(),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
import type { Plugin } from "vite";
|
|
||||||
|
|
||||||
export function buildIdPlugin(): Plugin {
|
|
||||||
let buildId = "";
|
|
||||||
|
|
||||||
return {
|
|
||||||
name: "fresh:build-id",
|
|
||||||
async config(_, env) {
|
|
||||||
const isDev = env.command === "serve";
|
|
||||||
|
|
||||||
buildId = await getBuildId(isDev);
|
|
||||||
|
|
||||||
return {
|
|
||||||
define: {
|
|
||||||
BUILD_ID: JSON.stringify(buildId),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
},
|
|
||||||
applyToEnvironment() {
|
|
||||||
return true;
|
|
||||||
},
|
|
||||||
resolveId(id) {
|
|
||||||
if (id === "fresh/build-id") {
|
|
||||||
return `\0fresh/build-id`;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
load(id) {
|
|
||||||
if (id !== `\0fresh/build-id`) return;
|
|
||||||
|
|
||||||
return `export let BUILD_ID = ${JSON.stringify(buildId)};
|
|
||||||
export const DENO_DEPLOYMENT_ID = undefined;
|
|
||||||
export function setBuildId(id) {
|
|
||||||
BUILD_ID = id;
|
|
||||||
}`;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getBuildId(dev: boolean): Promise<string> {
|
|
||||||
if (!dev) {
|
|
||||||
const bin = Deno.build.os === "windows" ? "git.exe" : "git";
|
|
||||||
const res = await new Deno.Command(bin, { args: ["rev-parse", "HEAD"] })
|
|
||||||
.output();
|
|
||||||
|
|
||||||
return new TextDecoder().decode(res.stdout);
|
|
||||||
}
|
|
||||||
|
|
||||||
const arr = new Uint32Array(1);
|
|
||||||
crypto.getRandomValues(arr);
|
|
||||||
return String(arr[0]);
|
|
||||||
}
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
import type { Plugin } from "vite";
|
|
||||||
|
|
||||||
export function clientEntryPlugin(): Plugin {
|
|
||||||
const modName = "fresh:client-entry";
|
|
||||||
|
|
||||||
return {
|
|
||||||
name: "fresh:client-entry",
|
|
||||||
applyToEnvironment(env) {
|
|
||||||
return env.name === "client";
|
|
||||||
},
|
|
||||||
resolveId(id) {
|
|
||||||
if (id === modName) {
|
|
||||||
return `\0${modName}`;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
load(id) {
|
|
||||||
if (id !== `\0${modName}`) return;
|
|
||||||
|
|
||||||
return `export * from "fresh/runtime-client";
|
|
||||||
|
|
||||||
if (import.meta.hot) {
|
|
||||||
import.meta.hot.accept(() => {
|
|
||||||
console.log("accepting")
|
|
||||||
});
|
|
||||||
import.meta.hot.on("fresh:reload", ev => {
|
|
||||||
console.log(ev)
|
|
||||||
window.location.reload();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
`;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,79 +0,0 @@
|
|||||||
import type { Plugin, ViteDevServer } from "vite";
|
|
||||||
import type { ResolvedFreshViteConfig } from "../utils.ts";
|
|
||||||
import { crawlFsItem } from "fresh/internal-dev";
|
|
||||||
|
|
||||||
export function clientSnapshot(options: ResolvedFreshViteConfig): Plugin {
|
|
||||||
const modName = "fresh:client-snapshot";
|
|
||||||
|
|
||||||
const islands = new Set<string>();
|
|
||||||
let server: ViteDevServer | undefined;
|
|
||||||
let isDev = false;
|
|
||||||
|
|
||||||
return {
|
|
||||||
name: "fresh:client-snapshot",
|
|
||||||
applyToEnvironment(env) {
|
|
||||||
return env.name === "client";
|
|
||||||
},
|
|
||||||
config(_, env) {
|
|
||||||
isDev = env.command === "serve";
|
|
||||||
|
|
||||||
return {
|
|
||||||
environments: {
|
|
||||||
client: {
|
|
||||||
build: {
|
|
||||||
rollupOptions: {
|
|
||||||
input: {
|
|
||||||
"client-snapshot": "fresh:client-snapshot",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
},
|
|
||||||
async buildStart() {
|
|
||||||
const result = await crawlFsItem({
|
|
||||||
islandDir: options.islandsDir,
|
|
||||||
routeDir: options.routeDir,
|
|
||||||
ignore: options.ignore,
|
|
||||||
});
|
|
||||||
|
|
||||||
for (let i = 0; i < result.islands.length; i++) {
|
|
||||||
const filePath = result.islands[i];
|
|
||||||
islands.add(filePath);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
resolveId(id) {
|
|
||||||
if (id === modName) {
|
|
||||||
return `\0${modName}`;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
configureServer(devServer) {
|
|
||||||
server = devServer;
|
|
||||||
},
|
|
||||||
load(id) {
|
|
||||||
if (id !== `\0${modName}`) return;
|
|
||||||
|
|
||||||
const imports = Array.from(islands.keys()).map((file, i) => {
|
|
||||||
return `export const mod_${i} = await import(${JSON.stringify(file)});`;
|
|
||||||
}).join("\n");
|
|
||||||
|
|
||||||
if (isDev && server !== undefined) {
|
|
||||||
const mod = server.environments.ssr.moduleGraph.getModuleById(
|
|
||||||
"\0fresh:server-snapshot",
|
|
||||||
);
|
|
||||||
if (mod) {
|
|
||||||
server.environments.ssr.moduleGraph.invalidateModule(mod);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return `${imports}
|
|
||||||
if (import.meta.hot) {
|
|
||||||
import.meta.hot.accept(() => {
|
|
||||||
console.log("accepting client-snapshot")
|
|
||||||
});
|
|
||||||
}
|
|
||||||
`;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,187 +0,0 @@
|
|||||||
import type { Plugin } from "vite";
|
|
||||||
import {
|
|
||||||
type Loader,
|
|
||||||
RequestedModuleType,
|
|
||||||
ResolutionMode,
|
|
||||||
Workspace,
|
|
||||||
} from "@deno/loader";
|
|
||||||
import * as path from "@std/path";
|
|
||||||
|
|
||||||
interface DenoState {
|
|
||||||
type: RequestedModuleType;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function deno(): Plugin {
|
|
||||||
let loader: Loader;
|
|
||||||
|
|
||||||
return {
|
|
||||||
name: "deno",
|
|
||||||
async configResolved() {
|
|
||||||
// TODO: Pass conditions
|
|
||||||
loader = await new Workspace({}).createLoader();
|
|
||||||
},
|
|
||||||
applyToEnvironment() {
|
|
||||||
return true;
|
|
||||||
},
|
|
||||||
async resolveId(id, importer, options) {
|
|
||||||
importer = isDenoSpecifier(importer)
|
|
||||||
? parseDenoSpecifier(importer).specifier
|
|
||||||
: importer;
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Ensure we're passing a valid importer that Deno understands
|
|
||||||
const denoImporter = importer && !importer.startsWith("\0")
|
|
||||||
? importer
|
|
||||||
: undefined;
|
|
||||||
|
|
||||||
let resolved = await loader.resolve(
|
|
||||||
id,
|
|
||||||
denoImporter,
|
|
||||||
ResolutionMode.Import,
|
|
||||||
);
|
|
||||||
|
|
||||||
if (id === resolved) {
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
const type = getDenoType(options.attributes.type ?? "default");
|
|
||||||
if (
|
|
||||||
type !== RequestedModuleType.Default ||
|
|
||||||
/^(https?|jsr|npm):/.test(resolved) ||
|
|
||||||
// Vite does weird things to windows file paths
|
|
||||||
Deno.build.os === "windows"
|
|
||||||
) {
|
|
||||||
return toDenoSpecifier(resolved, type);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (resolved.startsWith("file://")) {
|
|
||||||
resolved = path.fromFileUrl(resolved);
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
id: resolved,
|
|
||||||
meta: {
|
|
||||||
deno: {
|
|
||||||
type,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
} catch {
|
|
||||||
// ignore
|
|
||||||
}
|
|
||||||
},
|
|
||||||
async load(id) {
|
|
||||||
if (isDenoSpecifier(id)) {
|
|
||||||
const { type, specifier } = parseDenoSpecifier(id);
|
|
||||||
|
|
||||||
const result = await loader.load(specifier, type);
|
|
||||||
if (result.kind === "external") {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
code: new TextDecoder().decode(result.code),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
if (id.startsWith("\0")) {
|
|
||||||
id = id.slice(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
const meta = this.getModuleInfo(id)?.meta.deno as
|
|
||||||
| DenoState
|
|
||||||
| undefined
|
|
||||||
| null;
|
|
||||||
|
|
||||||
if (meta === null || meta === undefined) return;
|
|
||||||
|
|
||||||
const url = path.toFileUrl(id);
|
|
||||||
|
|
||||||
const result = await loader.load(url.href, meta.type);
|
|
||||||
if (result.kind === "external") {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
code: new TextDecoder().decode(result.code),
|
|
||||||
};
|
|
||||||
},
|
|
||||||
async transform(_, id, options) {
|
|
||||||
// This transform is a hack to be able to re-use Deno's precompile
|
|
||||||
// jsx transform.
|
|
||||||
if (!options?.ssr || !id.endsWith(".tsx") || id.endsWith(".jsx")) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let actualId = id;
|
|
||||||
if (isDenoSpecifier(id)) {
|
|
||||||
const { specifier } = parseDenoSpecifier(id);
|
|
||||||
actualId = specifier;
|
|
||||||
}
|
|
||||||
if (path.isAbsolute(actualId)) {
|
|
||||||
actualId = path.toFileUrl(actualId).href;
|
|
||||||
}
|
|
||||||
|
|
||||||
const resolved = await loader.resolve(
|
|
||||||
actualId,
|
|
||||||
undefined,
|
|
||||||
ResolutionMode.Import,
|
|
||||||
);
|
|
||||||
const result = await loader.load(resolved, RequestedModuleType.Default);
|
|
||||||
if (result.kind === "external") {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const code = new TextDecoder().decode(result.code);
|
|
||||||
|
|
||||||
return {
|
|
||||||
code,
|
|
||||||
};
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export type DenoSpecifier = string & { __deno: string };
|
|
||||||
|
|
||||||
function isDenoSpecifier(str: unknown): str is DenoSpecifier {
|
|
||||||
return typeof str === "string" && str.startsWith("\0deno::");
|
|
||||||
}
|
|
||||||
|
|
||||||
function toDenoSpecifier(spec: string, type: RequestedModuleType) {
|
|
||||||
return `\0deno::${type}::${spec}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseDenoSpecifier(
|
|
||||||
spec: DenoSpecifier,
|
|
||||||
): { type: RequestedModuleType; specifier: string } {
|
|
||||||
const match = spec.match(/^\0deno::([^:]+)::(.*)$/)!;
|
|
||||||
|
|
||||||
let specifier = match[2];
|
|
||||||
|
|
||||||
const specMatch = specifier.match(/^(\w+):\/([^/].*)$/);
|
|
||||||
if (specMatch !== null) {
|
|
||||||
const protocol = specMatch[1];
|
|
||||||
|
|
||||||
let rest = specMatch[2];
|
|
||||||
if (protocol === "file") {
|
|
||||||
rest = "/" + rest;
|
|
||||||
}
|
|
||||||
|
|
||||||
specifier = `${protocol}://${rest}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
return { type: +match[1], specifier };
|
|
||||||
}
|
|
||||||
|
|
||||||
function getDenoType(type: string): RequestedModuleType {
|
|
||||||
switch (type) {
|
|
||||||
case "json":
|
|
||||||
return RequestedModuleType.Json;
|
|
||||||
case "bytes":
|
|
||||||
return RequestedModuleType.Bytes;
|
|
||||||
case "text":
|
|
||||||
return RequestedModuleType.Text;
|
|
||||||
default:
|
|
||||||
return RequestedModuleType.Default;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,79 +0,0 @@
|
|||||||
import type { Plugin } from "vite";
|
|
||||||
import { nodeToRequest, responseToNode } from "../request.ts";
|
|
||||||
import * as path from "@std/path";
|
|
||||||
import { pathWithRoot } from "../utils.ts";
|
|
||||||
|
|
||||||
export function devServer(): Plugin[] {
|
|
||||||
let publicDir = "";
|
|
||||||
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
name: "fresh:dev_server",
|
|
||||||
configResolved(cfg) {
|
|
||||||
publicDir = pathWithRoot(cfg.publicDir, cfg.root);
|
|
||||||
},
|
|
||||||
configureServer(server) {
|
|
||||||
const IGNORE_URLS = /^\/(@(vite|fs|id)|\.vite)\//;
|
|
||||||
|
|
||||||
server.middlewares.use(async (nodeReq, nodeRes, next) => {
|
|
||||||
const serverCfg = server.config.server;
|
|
||||||
|
|
||||||
const protocol = serverCfg.https ? "https" : "http";
|
|
||||||
const host = serverCfg.host ? serverCfg.host : "localhost";
|
|
||||||
const port = serverCfg.port;
|
|
||||||
const url = new URL(
|
|
||||||
`${protocol}://${host}:${port}${nodeReq.url ?? "/"}`,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Check if it's a vite url
|
|
||||||
if (
|
|
||||||
IGNORE_URLS.test(url.pathname) ||
|
|
||||||
server.environments.client.moduleGraph.urlToModuleMap.has(
|
|
||||||
url.pathname,
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
return next();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if it's a static file first
|
|
||||||
// FIXME: Should this still go through fresh?
|
|
||||||
if (url.pathname !== "/") {
|
|
||||||
try {
|
|
||||||
await Deno.stat(path.join(publicDir, url.pathname));
|
|
||||||
return next();
|
|
||||||
} catch (err) {
|
|
||||||
if (!(err instanceof Deno.errors.NotFound)) {
|
|
||||||
return next(err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const mod = await server.ssrLoadModule("fresh:server_entry");
|
|
||||||
|
|
||||||
try {
|
|
||||||
const req = nodeToRequest(nodeReq, url);
|
|
||||||
const res = await mod.default.fetch(req);
|
|
||||||
await responseToNode(res, nodeRes);
|
|
||||||
return nodeRes;
|
|
||||||
} catch (err) {
|
|
||||||
return next(err);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "fresh:server_hmr",
|
|
||||||
applyToEnvironment(env) {
|
|
||||||
return env.name === "ssr";
|
|
||||||
},
|
|
||||||
hotUpdate(options) {
|
|
||||||
const clientMod = options.server.environments.client.moduleGraph
|
|
||||||
.getModulesByFile(options.file);
|
|
||||||
|
|
||||||
if (clientMod === undefined) {
|
|
||||||
options.server.hot.send("fresh:reload");
|
|
||||||
}
|
|
||||||
},
|
|
||||||
},
|
|
||||||
];
|
|
||||||
}
|
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
import type { Plugin } from "vite";
|
|
||||||
import { generateServerEntry } from "fresh/internal-dev";
|
|
||||||
import { pathWithRoot, type ResolvedFreshViteConfig } from "../utils.ts";
|
|
||||||
import * as path from "@std/path";
|
|
||||||
|
|
||||||
export function serverEntryPlugin(
|
|
||||||
options: ResolvedFreshViteConfig,
|
|
||||||
): Plugin {
|
|
||||||
const modName = "fresh:server_entry";
|
|
||||||
|
|
||||||
let serverEntry = "";
|
|
||||||
let serverOutDir = "";
|
|
||||||
let root = "";
|
|
||||||
|
|
||||||
let isDev = false;
|
|
||||||
|
|
||||||
return {
|
|
||||||
name: "fresh:server_entry",
|
|
||||||
applyToEnvironment(env) {
|
|
||||||
return env.name === "ssr";
|
|
||||||
},
|
|
||||||
config(_, env) {
|
|
||||||
isDev = env.command === "serve";
|
|
||||||
},
|
|
||||||
configResolved(config) {
|
|
||||||
root = config.root;
|
|
||||||
serverEntry = pathWithRoot(options.serverEntry, config.root);
|
|
||||||
serverOutDir = pathWithRoot(
|
|
||||||
config.environments.ssr.build.outDir,
|
|
||||||
config.root,
|
|
||||||
);
|
|
||||||
},
|
|
||||||
resolveId(id) {
|
|
||||||
if (id === modName) {
|
|
||||||
return `\0${modName}`;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
load(id) {
|
|
||||||
if (id !== `\0${modName}`) return;
|
|
||||||
|
|
||||||
let code = generateServerEntry({
|
|
||||||
root,
|
|
||||||
serverEntry: path.toFileUrl(serverEntry).href,
|
|
||||||
snapshotSpecifier: "fresh:server-snapshot",
|
|
||||||
});
|
|
||||||
|
|
||||||
if (isDev) {
|
|
||||||
code += `if (import.meta.hot) import.meta.hot.accept();\n`;
|
|
||||||
}
|
|
||||||
|
|
||||||
return code;
|
|
||||||
},
|
|
||||||
async writeBundle() {
|
|
||||||
const outDir = path.dirname(serverOutDir);
|
|
||||||
await Deno.writeTextFile(
|
|
||||||
path.join(outDir, "server.js"),
|
|
||||||
`import server from "./server/server-entry.mjs";
|
|
||||||
export default {
|
|
||||||
fetch: server.fetch
|
|
||||||
};
|
|
||||||
`,
|
|
||||||
);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,189 +0,0 @@
|
|||||||
import type { Manifest, Plugin, ViteDevServer } from "vite";
|
|
||||||
import {
|
|
||||||
crawlFsItem,
|
|
||||||
fsAdapter,
|
|
||||||
generateSnapshotServer,
|
|
||||||
type IslandModChunk,
|
|
||||||
pathToSpec,
|
|
||||||
type PendingStaticFile,
|
|
||||||
specToName,
|
|
||||||
UniqueNamer,
|
|
||||||
} from "fresh/internal-dev";
|
|
||||||
import { pathWithRoot, type ResolvedFreshViteConfig } from "../utils.ts";
|
|
||||||
import * as path from "@std/path";
|
|
||||||
import { getBuildId } from "./build_id.ts";
|
|
||||||
|
|
||||||
export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] {
|
|
||||||
const modName = "fresh:server-snapshot";
|
|
||||||
|
|
||||||
let isDev = false;
|
|
||||||
let server: ViteDevServer | undefined;
|
|
||||||
|
|
||||||
const namer = new UniqueNamer();
|
|
||||||
|
|
||||||
let clientOutDir = "";
|
|
||||||
let root = "";
|
|
||||||
let publicDir = "";
|
|
||||||
|
|
||||||
const islands = new Map<string, { name: string; chunk: string | null }>();
|
|
||||||
const islandSpecByName = new Map<string, string>();
|
|
||||||
|
|
||||||
return [{
|
|
||||||
name: "fresh:server-snapshot",
|
|
||||||
applyToEnvironment(env) {
|
|
||||||
return env.name === "ssr";
|
|
||||||
},
|
|
||||||
config(_, env) {
|
|
||||||
isDev = env.command === "serve";
|
|
||||||
},
|
|
||||||
configResolved(config) {
|
|
||||||
root = config.root;
|
|
||||||
|
|
||||||
publicDir = pathWithRoot(config.publicDir, config.root);
|
|
||||||
clientOutDir = pathWithRoot(
|
|
||||||
config.environments.client.build.outDir,
|
|
||||||
config.root,
|
|
||||||
);
|
|
||||||
},
|
|
||||||
configureServer(viteServer) {
|
|
||||||
server = viteServer;
|
|
||||||
},
|
|
||||||
async buildStart() {
|
|
||||||
},
|
|
||||||
resolveId(id) {
|
|
||||||
if (id === modName) {
|
|
||||||
return `\0${modName}`;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
async load(id) {
|
|
||||||
if (id !== `\0${modName}`) return;
|
|
||||||
|
|
||||||
const result = await crawlFsItem({
|
|
||||||
islandDir: options.islandsDir,
|
|
||||||
routeDir: options.routeDir,
|
|
||||||
ignore: options.ignore,
|
|
||||||
});
|
|
||||||
|
|
||||||
for (let i = 0; i < result.islands.length; i++) {
|
|
||||||
const spec = result.islands[i];
|
|
||||||
const specName = specToName(spec);
|
|
||||||
const name = namer.getUniqueName(specName);
|
|
||||||
|
|
||||||
islands.set(spec, { name, chunk: null });
|
|
||||||
islandSpecByName.set(name, spec);
|
|
||||||
}
|
|
||||||
|
|
||||||
const staticFiles: PendingStaticFile[] = [];
|
|
||||||
let islandMods: IslandModChunk[] = [];
|
|
||||||
let clientEntry = "/@id/fresh:client-entry";
|
|
||||||
let buildId = "";
|
|
||||||
|
|
||||||
if (isDev && server !== undefined) {
|
|
||||||
for (const id of islands.keys()) {
|
|
||||||
const mod = server.environments.client.moduleGraph.getModuleById(
|
|
||||||
id,
|
|
||||||
);
|
|
||||||
if (mod !== undefined) {
|
|
||||||
const def = islands.get(id);
|
|
||||||
if (def !== undefined) def.chunk = mod.url;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
islandMods = Array.from(islands.entries()).map(([id, def]) => {
|
|
||||||
return {
|
|
||||||
name: def.name,
|
|
||||||
server: id,
|
|
||||||
browser: def.chunk ?? `/@id/fresh-island::${def.name}`,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
buildId = await getBuildId(false);
|
|
||||||
const manifest = JSON.parse(
|
|
||||||
await Deno.readTextFile(
|
|
||||||
path.join(clientOutDir, ".vite", "manifest.json"),
|
|
||||||
),
|
|
||||||
) as Manifest;
|
|
||||||
|
|
||||||
for (const chunk of Object.values(manifest)) {
|
|
||||||
if (chunk.name === "client-entry") {
|
|
||||||
clientEntry = pathToSpec(clientOutDir, chunk.file);
|
|
||||||
}
|
|
||||||
|
|
||||||
staticFiles.push({
|
|
||||||
filePath: path.join(clientOutDir, chunk.file),
|
|
||||||
pathname: chunk.file,
|
|
||||||
hash: null,
|
|
||||||
});
|
|
||||||
|
|
||||||
const namer = new UniqueNamer();
|
|
||||||
if (chunk.name === "client-snapshot") {
|
|
||||||
for (const id of chunk.dynamicImports ?? []) {
|
|
||||||
const mod = manifest[id];
|
|
||||||
const serverPath = path.join(root, mod.src ?? id);
|
|
||||||
|
|
||||||
const name = namer.getUniqueName(specToName(id));
|
|
||||||
islandMods.push({
|
|
||||||
name,
|
|
||||||
browser: pathToSpec(clientOutDir, mod.file),
|
|
||||||
server: serverPath,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const entries = await fsAdapter.walk(
|
|
||||||
publicDir,
|
|
||||||
{
|
|
||||||
followSymlinks: false,
|
|
||||||
includeDirs: false,
|
|
||||||
includeFiles: true,
|
|
||||||
skip: options.ignore,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
for await (const entry of entries) {
|
|
||||||
const relative = path.relative(publicDir, entry.path);
|
|
||||||
const filePath = path.join(clientOutDir, relative);
|
|
||||||
|
|
||||||
try {
|
|
||||||
await Deno.mkdir(path.dirname(filePath), { recursive: true });
|
|
||||||
} catch (err) {
|
|
||||||
if (!(err instanceof Deno.errors.AlreadyExists)) {
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
await Deno.copyFile(entry.path, filePath);
|
|
||||||
|
|
||||||
staticFiles.push({
|
|
||||||
filePath,
|
|
||||||
hash: null,
|
|
||||||
pathname: relative,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const code = await generateSnapshotServer({
|
|
||||||
outDir: root,
|
|
||||||
staticFiles,
|
|
||||||
buildId,
|
|
||||||
clientEntry,
|
|
||||||
fsRoutesFiles: result.routes,
|
|
||||||
islands: islandMods,
|
|
||||||
writeSpecifier: (file) => {
|
|
||||||
return path.toFileUrl(file).href;
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
return code;
|
|
||||||
},
|
|
||||||
}, {
|
|
||||||
name: "fresh:island-resolver",
|
|
||||||
resolveId(id) {
|
|
||||||
if (id.startsWith("fresh-island::")) {
|
|
||||||
const name = id.slice("fresh-island::".length);
|
|
||||||
const spec = islandSpecByName.get(name);
|
|
||||||
if (spec !== undefined) return spec;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}];
|
|
||||||
}
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
||||||
|
|
||||||
export function nodeToRequest(node: IncomingMessage, url: URL): Request {
|
|
||||||
const controller = new AbortController();
|
|
||||||
node.once("aborted", () => controller.abort());
|
|
||||||
|
|
||||||
const body = undefined;
|
|
||||||
|
|
||||||
if (
|
|
||||||
node.method !== "HEAD" && node.method !== "GET" && node.method !== "OPTIONS"
|
|
||||||
) {
|
|
||||||
// FIXME
|
|
||||||
}
|
|
||||||
|
|
||||||
return new Request(url, {
|
|
||||||
headers: node.headers as Record<string, string>,
|
|
||||||
method: node.method,
|
|
||||||
body,
|
|
||||||
signal: controller.signal,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function responseToNode(
|
|
||||||
res: Response,
|
|
||||||
node: ServerResponse<IncomingMessage>,
|
|
||||||
): Promise<void> {
|
|
||||||
res.headers.forEach((value, key) => {
|
|
||||||
node.setHeader(key, value);
|
|
||||||
});
|
|
||||||
|
|
||||||
node.writeHead(res.status);
|
|
||||||
|
|
||||||
if (res.body === null) {
|
|
||||||
node.end();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (res.body.locked) {
|
|
||||||
node.end(`Error: Response body is locked.`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const reader = res.body.getReader();
|
|
||||||
|
|
||||||
if (node.destroyed) {
|
|
||||||
await reader.cancel();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const cancel = (error: unknown) => {
|
|
||||||
node.off("close", cancel);
|
|
||||||
node.off("error", cancel);
|
|
||||||
|
|
||||||
// Can't respond anymore with error
|
|
||||||
reader.cancel(error).catch(() => {});
|
|
||||||
|
|
||||||
if (error) {
|
|
||||||
node.destroy(error instanceof Error ? error : new Error(String(error)));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
node.on("close", cancel);
|
|
||||||
node.on("error", cancel);
|
|
||||||
|
|
||||||
async function next() {
|
|
||||||
try {
|
|
||||||
while (true) {
|
|
||||||
const { done, value } = await reader.read();
|
|
||||||
if (done) break;
|
|
||||||
|
|
||||||
if (!node.write(value)) {
|
|
||||||
node.once("drain", next);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
node.end();
|
|
||||||
} catch (error) {
|
|
||||||
cancel(error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
next();
|
|
||||||
}
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
import * as path from "@std/path";
|
|
||||||
import type { FsRouteFileNoMod, UniqueNamer } from "fresh/internal-dev";
|
|
||||||
|
|
||||||
export function pathWithRoot(fileOrDir: string, root?: string): string {
|
|
||||||
if (path.isAbsolute(fileOrDir)) return fileOrDir;
|
|
||||||
|
|
||||||
if (root === undefined) {
|
|
||||||
return path.join(Deno.cwd(), fileOrDir);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (path.isAbsolute(root)) return path.join(root, fileOrDir);
|
|
||||||
|
|
||||||
return path.join(Deno.cwd(), root, fileOrDir);
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface FreshState {
|
|
||||||
namer: UniqueNamer;
|
|
||||||
root: string;
|
|
||||||
serverEntry: string;
|
|
||||||
islandDir: string;
|
|
||||||
routeDir: string;
|
|
||||||
dev: boolean;
|
|
||||||
islands: Map<string, { name: string; chunk: string | null }>;
|
|
||||||
// deno-lint-ignore no-explicit-any
|
|
||||||
routes: FsRouteFileNoMod<any>[];
|
|
||||||
clientOutDir: string;
|
|
||||||
serverOutDir: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ClientSnapshot {
|
|
||||||
entry: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface FreshViteConfig {
|
|
||||||
serverEntry?: string;
|
|
||||||
islandsDir?: string;
|
|
||||||
routeDir?: string;
|
|
||||||
ignore?: RegExp[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export type ResolvedFreshViteConfig = Required<FreshViteConfig>;
|
|
||||||
@@ -1,71 +0,0 @@
|
|||||||
import { expect } from "@std/expect";
|
|
||||||
import {
|
|
||||||
waitForText,
|
|
||||||
withBrowser,
|
|
||||||
withChildProcessServer,
|
|
||||||
} from "../../tests/test_utils.tsx";
|
|
||||||
import { buildVite } from "./test_utils.ts";
|
|
||||||
|
|
||||||
Deno.test({
|
|
||||||
name: "vite build - launches",
|
|
||||||
fn: async () => {
|
|
||||||
await using res = await buildVite();
|
|
||||||
|
|
||||||
await withChildProcessServer(
|
|
||||||
res.tmp,
|
|
||||||
["serve", "-A", "--port", "0", "_fresh/server.js"],
|
|
||||||
async (address) => {
|
|
||||||
const res = await fetch(address);
|
|
||||||
const text = await res.text();
|
|
||||||
expect(text).toEqual("it works");
|
|
||||||
},
|
|
||||||
);
|
|
||||||
},
|
|
||||||
sanitizeOps: false,
|
|
||||||
sanitizeResources: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
Deno.test({
|
|
||||||
name: "vite build - serves static files",
|
|
||||||
fn: async () => {
|
|
||||||
await using res = await buildVite();
|
|
||||||
|
|
||||||
await withChildProcessServer(
|
|
||||||
res.tmp,
|
|
||||||
["serve", "-A", "--port", "0", "_fresh/server.js"],
|
|
||||||
async (address) => {
|
|
||||||
const res = await fetch(`${address}/test_static/foo.txt`);
|
|
||||||
const text = await res.text();
|
|
||||||
expect(text).toEqual("it works");
|
|
||||||
},
|
|
||||||
);
|
|
||||||
},
|
|
||||||
sanitizeOps: false,
|
|
||||||
sanitizeResources: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
Deno.test({
|
|
||||||
name: "vite build - loads islands",
|
|
||||||
fn: async () => {
|
|
||||||
await using res = await buildVite();
|
|
||||||
|
|
||||||
await withChildProcessServer(
|
|
||||||
res.tmp,
|
|
||||||
["serve", "-A", "--port", "0", "_fresh/server.js"],
|
|
||||||
async (address) => {
|
|
||||||
await withBrowser(async (page) => {
|
|
||||||
await page.goto(`${address}/tests/island_hooks`, {
|
|
||||||
waitUntil: "networkidle2",
|
|
||||||
});
|
|
||||||
|
|
||||||
await waitForText(page, "button", "count: 0");
|
|
||||||
|
|
||||||
await page.locator("button").click();
|
|
||||||
await waitForText(page, "button", "count: 1");
|
|
||||||
});
|
|
||||||
},
|
|
||||||
);
|
|
||||||
},
|
|
||||||
sanitizeOps: false,
|
|
||||||
sanitizeResources: false,
|
|
||||||
});
|
|
||||||
@@ -1,83 +0,0 @@
|
|||||||
import * as path from "@std/path";
|
|
||||||
import { expect } from "@std/expect";
|
|
||||||
import { waitForText, withBrowser } from "../../tests/test_utils.tsx";
|
|
||||||
import { updateFile, withDevServer } from "./test_utils.ts";
|
|
||||||
|
|
||||||
Deno.test({
|
|
||||||
name: "vite dev - launches",
|
|
||||||
fn: async () => {
|
|
||||||
await withDevServer(async (address) => {
|
|
||||||
const res = await fetch(`${address}/tests/it_works`);
|
|
||||||
const text = await res.text();
|
|
||||||
expect(text).toContain("it works");
|
|
||||||
});
|
|
||||||
},
|
|
||||||
sanitizeResources: false,
|
|
||||||
sanitizeOps: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
Deno.test({
|
|
||||||
name: "vite dev - serves static files",
|
|
||||||
fn: async () => {
|
|
||||||
await withDevServer(async (address) => {
|
|
||||||
const res = await fetch(`${address}/test_static/foo.txt`);
|
|
||||||
const text = await res.text();
|
|
||||||
expect(text).toContain("it works");
|
|
||||||
});
|
|
||||||
},
|
|
||||||
sanitizeResources: false,
|
|
||||||
sanitizeOps: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
Deno.test({
|
|
||||||
name: "vite dev - loads islands",
|
|
||||||
fn: async () => {
|
|
||||||
await withDevServer(async (address) => {
|
|
||||||
await withBrowser(async (page) => {
|
|
||||||
await page.goto(`${address}/tests/island_hooks`, {
|
|
||||||
waitUntil: "networkidle2",
|
|
||||||
});
|
|
||||||
await waitForText(page, "button", "count: 0");
|
|
||||||
|
|
||||||
await page.locator("button").click();
|
|
||||||
await waitForText(page, "button", "count: 1");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
},
|
|
||||||
sanitizeResources: false,
|
|
||||||
sanitizeOps: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
Deno.test({
|
|
||||||
name: "vite dev - can apply HMR to islands (hooks)",
|
|
||||||
ignore: true, // Test is very flaky
|
|
||||||
fn: async () => {
|
|
||||||
await withDevServer(async (address, dir) => {
|
|
||||||
await withBrowser(async (page) => {
|
|
||||||
await page.goto(`${address}/tests/island_hooks`, {
|
|
||||||
waitUntil: "networkidle2",
|
|
||||||
});
|
|
||||||
await waitForText(page, "button", "count: 0");
|
|
||||||
await page.locator("button").click();
|
|
||||||
await waitForText(page, "button", "count: 1");
|
|
||||||
|
|
||||||
const island = path.join(
|
|
||||||
dir,
|
|
||||||
"islands",
|
|
||||||
"tests",
|
|
||||||
"CounterHooks.tsx",
|
|
||||||
);
|
|
||||||
await using _ = await updateFile(
|
|
||||||
island,
|
|
||||||
(text) => text.replace("count:", "hmr:"),
|
|
||||||
);
|
|
||||||
|
|
||||||
await waitForText(page, "button", "hmr: 1");
|
|
||||||
await page.locator("button").click();
|
|
||||||
await waitForText(page, "button", "hmr: 2");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
},
|
|
||||||
sanitizeResources: false,
|
|
||||||
sanitizeOps: false,
|
|
||||||
});
|
|
||||||
@@ -1,108 +0,0 @@
|
|||||||
import { createBuilder } from "vite";
|
|
||||||
import * as path from "@std/path";
|
|
||||||
import { walk } from "@std/fs/walk";
|
|
||||||
import { withTmpDir } from "../../src/test_utils.ts";
|
|
||||||
import { withChildProcessServer } from "../../tests/test_utils.tsx";
|
|
||||||
|
|
||||||
export const DEMO_DIR = path.join(import.meta.dirname!, "..", "demo");
|
|
||||||
|
|
||||||
export async function updateFile(
|
|
||||||
filePath: string,
|
|
||||||
fn: (text: string) => string | Promise<string>,
|
|
||||||
) {
|
|
||||||
const original = await Deno.readTextFile(filePath);
|
|
||||||
const result = await fn(original);
|
|
||||||
await Deno.writeTextFile(filePath, result);
|
|
||||||
|
|
||||||
return {
|
|
||||||
async [Symbol.asyncDispose]() {
|
|
||||||
await Deno.writeTextFile(filePath, original);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async function copyDir(from: string, to: string) {
|
|
||||||
const entries = walk(from, {
|
|
||||||
includeFiles: true,
|
|
||||||
includeDirs: false,
|
|
||||||
skip: [/([\\/]+(_fresh|node_modules|vendor)[\\/]+|[\\/]+vite\.config\.ts)/],
|
|
||||||
});
|
|
||||||
|
|
||||||
for await (const entry of entries) {
|
|
||||||
if (entry.isFile) {
|
|
||||||
const relative = path.relative(from, entry.path);
|
|
||||||
const target = path.join(to, relative);
|
|
||||||
|
|
||||||
try {
|
|
||||||
await Deno.mkdir(path.dirname(target), { recursive: true });
|
|
||||||
} catch (err) {
|
|
||||||
if (!(err instanceof Deno.errors.NotFound)) {
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
await Deno.copyFile(entry.path, target);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function withDevServer(
|
|
||||||
fn: (address: string, dir: string) => void | Promise<void>,
|
|
||||||
) {
|
|
||||||
await using tmp = await withTmpDir({
|
|
||||||
dir: path.join(import.meta.dirname!, ".."),
|
|
||||||
prefix: "tmp_",
|
|
||||||
});
|
|
||||||
|
|
||||||
await copyDir(DEMO_DIR, tmp.dir);
|
|
||||||
|
|
||||||
await Deno.writeTextFile(
|
|
||||||
path.join(tmp.dir, "vite.config.ts"),
|
|
||||||
`import { defineConfig } from "vite";
|
|
||||||
import { fresh } from "@fresh/plugin-vite";
|
|
||||||
|
|
||||||
export default defineConfig({
|
|
||||||
plugins: [
|
|
||||||
fresh(),
|
|
||||||
],
|
|
||||||
});
|
|
||||||
`,
|
|
||||||
);
|
|
||||||
|
|
||||||
await withChildProcessServer(
|
|
||||||
tmp.dir,
|
|
||||||
["run", "-A", "npm:vite"],
|
|
||||||
(address) => fn(address, tmp.dir),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function buildVite() {
|
|
||||||
const tmp = await withTmpDir();
|
|
||||||
|
|
||||||
const builder = await createBuilder({
|
|
||||||
root: DEMO_DIR,
|
|
||||||
build: {
|
|
||||||
emptyOutDir: true,
|
|
||||||
},
|
|
||||||
environments: {
|
|
||||||
ssr: {
|
|
||||||
build: {
|
|
||||||
outDir: path.join(tmp.dir, "_fresh", "server"),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
client: {
|
|
||||||
build: {
|
|
||||||
outDir: path.join(tmp.dir, "_fresh", "client"),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
await builder.buildApp();
|
|
||||||
|
|
||||||
return {
|
|
||||||
tmp: tmp.dir,
|
|
||||||
async [Symbol.asyncDispose]() {
|
|
||||||
return await tmp[Symbol.asyncDispose]();
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
+4
-6
@@ -1,6 +1,6 @@
|
|||||||
import { trace } from "@opentelemetry/api";
|
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 * as colors from "@std/fmt/colors";
|
||||||
import {
|
import {
|
||||||
type MaybeLazyMiddleware,
|
type MaybeLazyMiddleware,
|
||||||
@@ -152,7 +152,6 @@ export let getBuildCache: <State>(app: App<State>) => BuildCache<State> | null;
|
|||||||
export let setBuildCache: <State>(
|
export let setBuildCache: <State>(
|
||||||
app: App<State>,
|
app: App<State>,
|
||||||
cache: BuildCache<State>,
|
cache: BuildCache<State>,
|
||||||
mode: "development" | "production",
|
|
||||||
) => void;
|
) => void;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -165,9 +164,8 @@ export class App<State> {
|
|||||||
|
|
||||||
static {
|
static {
|
||||||
getBuildCache = (app) => app.#getBuildCache();
|
getBuildCache = (app) => app.#getBuildCache();
|
||||||
setBuildCache = (app, cache, mode: "development" | "production") => {
|
setBuildCache = (app, cache) => {
|
||||||
app.config.root = cache.root;
|
app.config.root = cache.root;
|
||||||
app.config.mode = mode;
|
|
||||||
app.#getBuildCache = () => cache;
|
app.#getBuildCache = () => cache;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -181,7 +179,7 @@ export class App<State> {
|
|||||||
this.config = {
|
this.config = {
|
||||||
root: Deno.cwd(),
|
root: Deno.cwd(),
|
||||||
basePath: config.basePath ?? "",
|
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"?`,
|
`Could not find _fresh directory. Maybe you forgot to run "deno task build"?`,
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
buildCache = new MockBuildCache([], this.config.mode);
|
buildCache = new MockBuildCache([]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-9
@@ -1,10 +1,10 @@
|
|||||||
import * as path from "@std/path";
|
import * as path from "@std/path";
|
||||||
|
import { setBuildId } from "./runtime/build_id.ts";
|
||||||
import type { Command } from "./commands.ts";
|
import type { Command } from "./commands.ts";
|
||||||
import { fsItemsToCommands, type FsRouteFile } from "./fs_routes.ts";
|
import { fsItemsToCommands, type FsRouteFile } from "./fs_routes.ts";
|
||||||
import type { ServerIslandRegistry } from "./context.ts";
|
import type { ServerIslandRegistry } from "./context.ts";
|
||||||
import type { AnyComponent } from "preact";
|
import type { AnyComponent } from "preact";
|
||||||
import { UniqueNamer } from "./utils.ts";
|
import { UniqueNamer } from "./utils.ts";
|
||||||
import { setBuildId } from "fresh/build-id";
|
|
||||||
|
|
||||||
export interface FileSnapshot {
|
export interface FileSnapshot {
|
||||||
name: string;
|
name: string;
|
||||||
@@ -15,7 +15,6 @@ export interface FileSnapshot {
|
|||||||
|
|
||||||
export interface BuildSnapshot<State> {
|
export interface BuildSnapshot<State> {
|
||||||
version: string;
|
version: string;
|
||||||
clientEntry: string;
|
|
||||||
fsRoutes: FsRouteFile<State>[];
|
fsRoutes: FsRouteFile<State>[];
|
||||||
staticFiles: Map<string, FileSnapshot>;
|
staticFiles: Map<string, FileSnapshot>;
|
||||||
islands: ServerIslandRegistry;
|
islands: ServerIslandRegistry;
|
||||||
@@ -33,10 +32,6 @@ export interface StaticFile {
|
|||||||
export interface BuildCache<State = any> {
|
export interface BuildCache<State = any> {
|
||||||
root: string;
|
root: string;
|
||||||
islandRegistry: ServerIslandRegistry;
|
islandRegistry: ServerIslandRegistry;
|
||||||
clientEntry: string;
|
|
||||||
features: {
|
|
||||||
errorOverlay: boolean;
|
|
||||||
};
|
|
||||||
getFsRoutes(): Command<State>[];
|
getFsRoutes(): Command<State>[];
|
||||||
readFile(pathname: string): Promise<StaticFile | null>;
|
readFile(pathname: string): Promise<StaticFile | null>;
|
||||||
}
|
}
|
||||||
@@ -44,14 +39,11 @@ export interface BuildCache<State = any> {
|
|||||||
export class ProdBuildCache<State> implements BuildCache<State> {
|
export class ProdBuildCache<State> implements BuildCache<State> {
|
||||||
#snapshot: BuildSnapshot<State>;
|
#snapshot: BuildSnapshot<State>;
|
||||||
islandRegistry: ServerIslandRegistry;
|
islandRegistry: ServerIslandRegistry;
|
||||||
clientEntry: string;
|
|
||||||
features = { errorOverlay: false };
|
|
||||||
|
|
||||||
constructor(public root: string, snapshot: BuildSnapshot<State>) {
|
constructor(public root: string, snapshot: BuildSnapshot<State>) {
|
||||||
setBuildId(snapshot.version);
|
setBuildId(snapshot.version);
|
||||||
this.#snapshot = snapshot;
|
this.#snapshot = snapshot;
|
||||||
this.islandRegistry = snapshot.islands;
|
this.islandRegistry = snapshot.islands;
|
||||||
this.clientEntry = snapshot.clientEntry;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
getFsRoutes(): Command<State>[] {
|
getFsRoutes(): Command<State>[] {
|
||||||
|
|||||||
@@ -7,10 +7,6 @@ export interface FreshConfig {
|
|||||||
* @default undefined
|
* @default undefined
|
||||||
*/
|
*/
|
||||||
basePath?: string;
|
basePath?: string;
|
||||||
/**
|
|
||||||
* The mode Fresh can run in.
|
|
||||||
*/
|
|
||||||
mode?: "development" | "production";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -296,3 +296,15 @@ export class Context<State> {
|
|||||||
return new Response(html, responseInit);
|
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 { App } from "fresh";
|
||||||
import { asset } from "fresh/runtime";
|
import { asset } from "fresh/runtime";
|
||||||
import { FakeServer } from "./test_utils.ts";
|
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";
|
import { parseHtml } from "../tests/test_utils.tsx";
|
||||||
|
|
||||||
Deno.test("FreshReqContext.prototype.redirect", () => {
|
Deno.test("FreshReqContext.prototype.redirect", () => {
|
||||||
|
|||||||
+19
-17
@@ -24,7 +24,7 @@ import { automaticWorkspaceFolders } from "./middlewares/automatic_workspace_fol
|
|||||||
import { parseDirPath } from "../config.ts";
|
import { parseDirPath } from "../config.ts";
|
||||||
import { pathToExportName, UniqueNamer } from "../utils.ts";
|
import { pathToExportName, UniqueNamer } from "../utils.ts";
|
||||||
import { checkDenoCompilerOptions } from "./check.ts";
|
import { checkDenoCompilerOptions } from "./check.ts";
|
||||||
import { crawlFsItem } from "./fs_crawl.ts";
|
import { crawlRouteDir, walkDir } from "./fs_crawl.ts";
|
||||||
import { DAY } from "../constants.ts";
|
import { DAY } from "../constants.ts";
|
||||||
|
|
||||||
export interface BuildOptions {
|
export interface BuildOptions {
|
||||||
@@ -169,7 +169,7 @@ export class Builder<State = any> {
|
|||||||
|
|
||||||
app.config.root = this.config.root;
|
app.config.root = this.config.root;
|
||||||
app.config.mode = "development";
|
app.config.mode = "development";
|
||||||
setBuildCache(app, buildCache, "development");
|
setBuildCache(app, buildCache);
|
||||||
|
|
||||||
const appHandler = app.handler();
|
const appHandler = app.handler();
|
||||||
|
|
||||||
@@ -187,7 +187,7 @@ export class Builder<State = any> {
|
|||||||
devApp.config.root = this.config.root;
|
devApp.config.root = this.config.root;
|
||||||
devApp.config.mode = "development";
|
devApp.config.mode = "development";
|
||||||
|
|
||||||
setBuildCache(devApp, buildCache, "development");
|
setBuildCache(devApp, buildCache);
|
||||||
|
|
||||||
// Boot in parallel to spin up the server quicker. We'll hold
|
// Boot in parallel to spin up the server quicker. We'll hold
|
||||||
// requests until the required assets are processed.
|
// requests until the required assets are processed.
|
||||||
@@ -248,24 +248,26 @@ export class Builder<State = any> {
|
|||||||
await buildCache.prepare();
|
await buildCache.prepare();
|
||||||
|
|
||||||
return (app) => {
|
return (app) => {
|
||||||
setBuildCache(app, buildCache, app.config.mode);
|
setBuildCache(app, buildCache);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async #crawlFsItems() {
|
async #crawlFsItems() {
|
||||||
const { islands, routes } = await crawlFsItem(
|
await Promise.all([
|
||||||
{
|
walkDir(
|
||||||
islandDir: this.config.islandDir,
|
fsAdapter,
|
||||||
routeDir: this.config.routeDir,
|
this.config.islandDir,
|
||||||
ignore: this.config.ignore,
|
(entry) => this.registerIsland(entry.path),
|
||||||
},
|
this.config.ignore,
|
||||||
);
|
),
|
||||||
|
crawlRouteDir(
|
||||||
for (let i = 0; i < islands.length; i++) {
|
fsAdapter,
|
||||||
this.registerIsland(islands[i]);
|
this.config.routeDir,
|
||||||
}
|
this.config.ignore,
|
||||||
|
(entry) => this.registerIsland(entry),
|
||||||
this.#fsRoutes.files = routes;
|
this.#fsRoutes.files,
|
||||||
|
),
|
||||||
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
async #build<T>(buildCache: DevBuildCache<T>, dev: boolean): Promise<void> {
|
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 { Builder, specToName } from "./builder.ts";
|
||||||
import { App } from "../app.ts";
|
import { App } from "../app.ts";
|
||||||
import { DEV_ERROR_OVERLAY_URL } from "../constants.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 { withTmpDir, writeFiles } from "../test_utils.ts";
|
||||||
import { withChildProcessServer } from "../../tests/test_utils.tsx";
|
import { withChildProcessServer } from "../../tests/test_utils.tsx";
|
||||||
|
|
||||||
@@ -64,7 +64,7 @@ Deno.test({
|
|||||||
await builder.build();
|
await builder.build();
|
||||||
|
|
||||||
const snapshotJson = await Deno.readTextFile(
|
const snapshotJson = await Deno.readTextFile(
|
||||||
path.join(tmp, "dist", "snapshot.js"),
|
path.join(tmp, "dist", "static-files.json"),
|
||||||
);
|
);
|
||||||
expect(snapshotJson).toContain("/images/batman.svg");
|
expect(snapshotJson).toContain("/images/batman.svg");
|
||||||
},
|
},
|
||||||
|
|||||||
+120
-175
@@ -1,10 +1,11 @@
|
|||||||
import {
|
import {
|
||||||
type BuildCache,
|
type BuildCache,
|
||||||
|
type FileSnapshot,
|
||||||
IslandPreparer,
|
IslandPreparer,
|
||||||
type StaticFile,
|
type StaticFile,
|
||||||
} from "../build_cache.ts";
|
} from "../build_cache.ts";
|
||||||
import * as path from "@std/path";
|
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 { encodeHex } from "@std/encoding/hex";
|
||||||
import { fsAdapter } from "../fs.ts";
|
import { fsAdapter } from "../fs.ts";
|
||||||
import type { FileTransformer } from "./file_transformer.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 type { ServerIslandRegistry } from "../context.ts";
|
||||||
import { contentType as getStdContentType } from "@std/media-types/content-type";
|
import { contentType as getStdContentType } from "@std/media-types/content-type";
|
||||||
|
|
||||||
const WINDOWS_SEPARATOR = pathWin32.SEPARATOR;
|
|
||||||
|
|
||||||
export interface MemoryFile {
|
export interface MemoryFile {
|
||||||
hash: string | null;
|
hash: string | null;
|
||||||
contentType: string;
|
contentType: string;
|
||||||
@@ -61,24 +60,16 @@ export class MemoryBuildCache<State> implements DevBuildCache<State> {
|
|||||||
#commands: Command<State>[] = [];
|
#commands: Command<State>[] = [];
|
||||||
root: string;
|
root: string;
|
||||||
islandRegistry: ServerIslandRegistry = new Map();
|
islandRegistry: ServerIslandRegistry = new Map();
|
||||||
clientEntry: string;
|
|
||||||
features = { errorOverlay: false };
|
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
config: ResolvedBuildConfig,
|
config: ResolvedBuildConfig,
|
||||||
fsRoutes: FsRoute<State>,
|
fsRoutes: FsRoute<State>,
|
||||||
transformer: FileTransformer,
|
transformer: FileTransformer,
|
||||||
) {
|
) {
|
||||||
if (config.mode === "development") {
|
|
||||||
this.features.errorOverlay = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.#config = config;
|
this.#config = config;
|
||||||
this.#fsRoutes = fsRoutes;
|
this.#fsRoutes = fsRoutes;
|
||||||
this.#transformer = transformer;
|
this.#transformer = transformer;
|
||||||
this.root = config.root;
|
this.root = config.root;
|
||||||
|
|
||||||
this.clientEntry = getClientEntry(config.buildId);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
getFsRoutes(): Command<State>[] {
|
getFsRoutes(): Command<State>[] {
|
||||||
@@ -229,17 +220,12 @@ export class DiskBuildCache<State> implements DevBuildCache<State> {
|
|||||||
#fsRoutes: FsRoute<State>;
|
#fsRoutes: FsRoute<State>;
|
||||||
root: string;
|
root: string;
|
||||||
islandRegistry: ServerIslandRegistry = new Map();
|
islandRegistry: ServerIslandRegistry = new Map();
|
||||||
clientEntry: string = "";
|
|
||||||
features = { errorOverlay: false };
|
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
config: ResolvedBuildConfig,
|
config: ResolvedBuildConfig,
|
||||||
fsRoutes: FsRoute<State>,
|
fsRoutes: FsRoute<State>,
|
||||||
transformer: FileTransformer,
|
transformer: FileTransformer,
|
||||||
) {
|
) {
|
||||||
if (config.mode === "development") {
|
|
||||||
this.features.errorOverlay = true;
|
|
||||||
}
|
|
||||||
this.#fsRoutes = fsRoutes;
|
this.#fsRoutes = fsRoutes;
|
||||||
this.#transformer = transformer;
|
this.#transformer = transformer;
|
||||||
this.#config = config;
|
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()) {
|
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()) {
|
for (const [name, maybeHash] of this.#processedFiles.entries()) {
|
||||||
|
let hash = maybeHash;
|
||||||
|
|
||||||
// Ignore esbuild meta file. It's not intended for serving
|
// Ignore esbuild meta file. It's not intended for serving
|
||||||
if (name === "/metafile.json") {
|
if (name === "/metafile.json") {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
const filePath = path.join(outDir, "static", name);
|
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[] = [];
|
const islandSpecifiers: string[] = [];
|
||||||
for (const spec of this.islandModNameToChunk.keys()) {
|
for (const spec of this.islandModNameToChunk.keys()) {
|
||||||
islandSpecifiers.push(spec);
|
islandSpecifiers.push(spec);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const editWarning =
|
||||||
|
`// WARNING: DO NOT EDIT THIS FILE. It is autogenerated by Fresh.`;
|
||||||
|
|
||||||
const islands = Array.from(this.islandModNameToChunk.values());
|
const islands = Array.from(this.islandModNameToChunk.values());
|
||||||
|
|
||||||
await Deno.writeTextFile(
|
await Deno.writeTextFile(
|
||||||
path.join(outDir, "snapshot.js"),
|
path.join(outDir, "snapshot.js"),
|
||||||
await generateSnapshotServer({
|
`${editWarning}
|
||||||
buildId: this.#config.buildId,
|
|
||||||
clientEntry: getClientEntry(this.#config.buildId),
|
import { IslandPreparer } from "fresh/do-not-use";
|
||||||
staticFiles,
|
import staticFileData from "./static-files.json" with { type: "json" };
|
||||||
islands,
|
|
||||||
writeSpecifier: (filePath) => {
|
// Import islands
|
||||||
return pathToSpec(outDir, filePath);
|
${
|
||||||
},
|
islands
|
||||||
fsRoutesFiles: this.#fsRoutes.files,
|
.map((item) => {
|
||||||
outDir: root,
|
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
|
// TODO: Make main file configurable
|
||||||
const appPath = path.relative(outDir, root);
|
const appPath = path.relative(outDir, root);
|
||||||
await Deno.writeTextFile(
|
await Deno.writeTextFile(
|
||||||
path.join(outDir, "server.js"),
|
path.join(outDir, "server.js"),
|
||||||
generateServerEntry({
|
`${editWarning}
|
||||||
root: appPath,
|
import { setBuildCache, ProdBuildCache, path } from "fresh/do-not-use";
|
||||||
serverEntry: path
|
import * as snapshot from "./snapshot.js";
|
||||||
.join(appPath, "main.ts")
|
import { app } from "${appPath}/main.ts";
|
||||||
.replaceAll(/[\\/]+/g, "/"),
|
|
||||||
snapshotSpecifier: "./snapshot.js",
|
const root = path.join(import.meta.dirname, ${JSON.stringify(appPath)});
|
||||||
}),
|
setBuildCache(app, new ProdBuildCache(root, snapshot));
|
||||||
|
|
||||||
|
export default {
|
||||||
|
fetch: app.handler()
|
||||||
|
}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const EDIT_WARNING =
|
async function hashContent(
|
||||||
`// WARNING: DO NOT EDIT THIS FILE. It is autogenerated by Fresh.`;
|
|
||||||
|
|
||||||
export async function hashContent(
|
|
||||||
content: Uint8Array | ReadableStream<Uint8Array>,
|
content: Uint8Array | ReadableStream<Uint8Array>,
|
||||||
): Promise<string> {
|
): Promise<string> {
|
||||||
const buffer = await new Response(content).arrayBuffer();
|
const buffer = await new Response(content).arrayBuffer();
|
||||||
@@ -397,137 +476,3 @@ export function getContentType(filePath: string): string {
|
|||||||
function maybeToFileUrl(file: string) {
|
function maybeToFileUrl(file: string) {
|
||||||
return file.startsWith("file://") ? file : path.toFileUrl(file).href;
|
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 {
|
return {
|
||||||
name: "fresh-build-id",
|
name: "fresh-build-id",
|
||||||
setup(build) {
|
setup(build) {
|
||||||
build.onResolve({ filter: /^fresh\/build-id$/ }, (args) => {
|
build.onResolve({ filter: /[/\\]+build_id\.ts$/ }, (args) => {
|
||||||
return {
|
return {
|
||||||
path: args.path,
|
path: args.path,
|
||||||
namespace: "fresh-internal",
|
namespace: "fresh-internal",
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
build.onLoad({
|
build.onLoad({
|
||||||
filter: /^fresh\/build-id$/,
|
filter: /[/\\]build_id\.ts$/,
|
||||||
namespace: "fresh-internal",
|
namespace: "fresh-internal",
|
||||||
}, () => {
|
}, () => {
|
||||||
return {
|
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 { WalkEntry } from "@std/fs/walk";
|
||||||
import type { FsRouteFileNoMod } from "./dev_build_cache.ts";
|
import type { FsRouteFileNoMod } from "./dev_build_cache.ts";
|
||||||
import * as path from "@std/path";
|
import * as path from "@std/path";
|
||||||
@@ -14,90 +14,92 @@ export async function crawlRouteDir<State>(
|
|||||||
routeDir: string,
|
routeDir: string,
|
||||||
ignore: RegExp[],
|
ignore: RegExp[],
|
||||||
onIslandSpecifier: (spec: string) => void,
|
onIslandSpecifier: (spec: string) => void,
|
||||||
): Promise<FsRouteFileNoMod<State>[]> {
|
files: FsRouteFileNoMod<State>[],
|
||||||
const files: FsRouteFileNoMod<State>[] = [];
|
) {
|
||||||
|
await walkDir(
|
||||||
await walkDir(fs, routeDir, async (entry) => {
|
fs,
|
||||||
// A `(_islands)` path segment is a local island folder.
|
routeDir,
|
||||||
// Any route path segment wrapped in `(_...)` is ignored
|
async (entry) => {
|
||||||
// during route collection.
|
// A `(_islands)` path segment is a local island folder.
|
||||||
const match = entry.path.match(GROUP_REG);
|
// Any route path segment wrapped in `(_...)` is ignored
|
||||||
if (match !== null) {
|
// during route collection.
|
||||||
if (match[1] === "_islands") {
|
const match = entry.path.match(GROUP_REG);
|
||||||
onIslandSpecifier(entry.path);
|
if (match !== null) {
|
||||||
}
|
if (match[1] === "_islands") {
|
||||||
return;
|
onIslandSpecifier(entry.path);
|
||||||
}
|
|
||||||
|
|
||||||
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 += "/";
|
|
||||||
}
|
}
|
||||||
|
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);
|
let overrideConfig: RouteConfig | undefined;
|
||||||
lazy = !code.includes("routeOverride");
|
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
|
routePattern = pathToPattern(id.slice(1));
|
||||||
// kind of handler that's used to get a more accurate
|
|
||||||
// list of methods this route supports.
|
|
||||||
overrideConfig = {
|
|
||||||
methods: "ALL",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
files.push({
|
const code = await fs.readTextFile(entry.path);
|
||||||
id,
|
lazy = !code.includes("routeOverride");
|
||||||
filePath: entry.path,
|
|
||||||
type,
|
// TODO: We could do an AST parse here to detect the
|
||||||
pattern,
|
// kind of handler that's used to get a more accurate
|
||||||
routePattern,
|
// list of methods this route supports.
|
||||||
lazy,
|
overrideConfig = {
|
||||||
overrideConfig,
|
methods: "ALL",
|
||||||
});
|
};
|
||||||
}, ignore);
|
}
|
||||||
|
|
||||||
|
files.push({
|
||||||
|
id,
|
||||||
|
filePath: entry.path,
|
||||||
|
type,
|
||||||
|
pattern,
|
||||||
|
routePattern,
|
||||||
|
lazy,
|
||||||
|
overrideConfig,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
ignore,
|
||||||
|
);
|
||||||
|
|
||||||
files.sort((a, b) => sortRoutePaths(a.id, b.id));
|
files.sort((a, b) => sortRoutePaths(a.id, b.id));
|
||||||
|
|
||||||
return files;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function walkDir(
|
export async function walkDir(
|
||||||
@@ -119,28 +121,3 @@ export async function walkDir(
|
|||||||
await callback(entry);
|
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");
|
const lines = stack.split("\n");
|
||||||
for (let i = 0; i < lines.length; i++) {
|
for (let i = 0; i < lines.length; i++) {
|
||||||
const match = lines[i].match(STACK_FRAME);
|
const match = lines[i].match(STACK_FRAME);
|
||||||
if (match) {
|
if (match && match) {
|
||||||
const fnName = match[1] ?? "";
|
const fnName = match[1] ?? "";
|
||||||
const file = match[2];
|
const file = match[2];
|
||||||
const line = +match[3];
|
const line = +match[3];
|
||||||
|
|||||||
@@ -86,8 +86,9 @@ Deno.test(
|
|||||||
);
|
);
|
||||||
|
|
||||||
Deno.test("error overlay - should not be visible in prod", async () => {
|
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.use(devErrorOverlay());
|
||||||
|
app.config.mode = "production";
|
||||||
|
|
||||||
app.get("/", () => {
|
app.get("/", () => {
|
||||||
throw new HttpError(500);
|
throw new HttpError(500);
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import type { Method } from "./router.ts";
|
|||||||
import { parseHtml } from "../tests/test_utils.tsx";
|
import { parseHtml } from "../tests/test_utils.tsx";
|
||||||
import type { Context } from "./context.ts";
|
import type { Context } from "./context.ts";
|
||||||
import { HttpError } from "./error.ts";
|
import { HttpError } from "./error.ts";
|
||||||
|
import type { FsRouteFileNoMod } from "./dev/dev_build_cache.ts";
|
||||||
import { crawlRouteDir } from "./dev/fs_crawl.ts";
|
import { crawlRouteDir } from "./dev/fs_crawl.ts";
|
||||||
import * as path from "@std/path";
|
import * as path from "@std/path";
|
||||||
|
|
||||||
@@ -18,7 +19,8 @@ async function createServer<T>(
|
|||||||
const fs = createFakeFs(files);
|
const fs = createFakeFs(files);
|
||||||
|
|
||||||
const routeDir = path.join(fs.cwd(), "routes");
|
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) => {
|
const fsFiles = rawFiles.map((file) => {
|
||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
@@ -28,8 +30,8 @@ async function createServer<T>(
|
|||||||
const app = new App<T>()
|
const app = new App<T>()
|
||||||
.fsRoutes();
|
.fsRoutes();
|
||||||
|
|
||||||
const buildCache = new MockBuildCache<T>(fsFiles, "development");
|
const buildCache = new MockBuildCache<T>(fsFiles);
|
||||||
setBuildCache<T>(app, buildCache, "development");
|
setBuildCache<T>(app, buildCache);
|
||||||
|
|
||||||
return new FakeServer(app.handler());
|
return new FakeServer(app.handler());
|
||||||
}
|
}
|
||||||
@@ -227,9 +229,7 @@ Deno.test("fsRoutes - middleware array", async () => {
|
|||||||
return ctx.next();
|
return ctx.next();
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"routes/foo/index.ts": {
|
"routes/foo/index.ts": { default: (ctx) => <div>{ctx.state.text}</div> },
|
||||||
default: (ctx) => <div class="full-">{ctx.state.text}</div>,
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const res = await server.get("/foo");
|
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 type { Middleware } from "./mod.ts";
|
||||||
import { ASSET_CACHE_BUST_KEY } from "../runtime/shared_internal.tsx";
|
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 { tracer } from "../otel.ts";
|
||||||
import { getBuildCache } from "../context.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 type { BuildCache, StaticFile } from "../build_cache.ts";
|
||||||
import { expect } from "@std/expect";
|
import { expect } from "@std/expect";
|
||||||
import { ASSET_CACHE_BUST_KEY } from "../runtime/shared_internal.tsx";
|
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 { Command } from "../commands.ts";
|
||||||
import type { ServerIslandRegistry } from "../context.ts";
|
import type { ServerIslandRegistry } from "../context.ts";
|
||||||
import { getContentType } from "../dev/dev_build_cache.ts";
|
import { getContentType } from "../dev/dev_build_cache.ts";
|
||||||
@@ -13,8 +13,6 @@ class MockBuildCache implements BuildCache {
|
|||||||
buildId = "MockId";
|
buildId = "MockId";
|
||||||
files = new Map<string, StaticFile>();
|
files = new Map<string, StaticFile>();
|
||||||
islandRegistry: ServerIslandRegistry = new Map();
|
islandRegistry: ServerIslandRegistry = new Map();
|
||||||
clientEntry = "";
|
|
||||||
features = { errorOverlay: false };
|
|
||||||
|
|
||||||
constructor(files: Record<string, { hash: string | null; content: string }>) {
|
constructor(files: Record<string, { hash: string | null; content: string }>) {
|
||||||
const encoder = new TextEncoder();
|
const encoder = new TextEncoder();
|
||||||
|
|||||||
+6
-10
@@ -14,6 +14,7 @@ import type { Context } from "./context.ts";
|
|||||||
import { recordSpanError, tracer } from "./otel.ts";
|
import { recordSpanError, tracer } from "./otel.ts";
|
||||||
import { DEV_ERROR_OVERLAY_URL } from "./constants.ts";
|
import { DEV_ERROR_OVERLAY_URL } from "./constants.ts";
|
||||||
import { renderToString } from "preact-render-to-string";
|
import { renderToString } from "preact-render-to-string";
|
||||||
|
import { BUILD_ID } from "./runtime/build_id.ts";
|
||||||
|
|
||||||
export type AsyncAnyComponent<P> = {
|
export type AsyncAnyComponent<P> = {
|
||||||
(
|
(
|
||||||
@@ -84,17 +85,12 @@ export function preactRender<State, Data>(
|
|||||||
} finally {
|
} finally {
|
||||||
// Add preload headers
|
// Add preload headers
|
||||||
const basePath = ctx.config.basePath;
|
const basePath = ctx.config.basePath;
|
||||||
const runtimeUrl = state.buildCache.clientEntry.startsWith(".")
|
const runtimeUrl = `${basePath}/_fresh/js/${BUILD_ID}/fresh-runtime.js`;
|
||||||
? state.buildCache.clientEntry.slice(1)
|
let link = `<${encodeURI(runtimeUrl)}>; rel="modulepreload"; as="script"`;
|
||||||
: state.buildCache.clientEntry;
|
|
||||||
let link = `<${
|
|
||||||
encodeURI(`${basePath}${runtimeUrl}`)
|
|
||||||
}>; rel="modulepreload"; as="script"`;
|
|
||||||
state.islands.forEach((island) => {
|
state.islands.forEach((island) => {
|
||||||
const specifier = `${basePath}${
|
link += `, <${
|
||||||
island.file.startsWith(".") ? island.file.slice(1) : island.file
|
encodeURI(`${basePath}${island.file}`)
|
||||||
}`;
|
}>; rel="modulepreload"; as="script"`;
|
||||||
link += `, <${encodeURI(specifier)}>; rel="modulepreload"; as="script"`;
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (link !== "") {
|
if (link !== "") {
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
import { encodeHex } from "@std/encoding/hex";
|
import { encodeHex } from "@std/encoding/hex";
|
||||||
|
|
||||||
export const DENO_DEPLOYMENT_ID: string | undefined = Deno.env.get(
|
export const DENO_DEPLOYMENT_ID = Deno.env.get("DENO_DEPLOYMENT_ID");
|
||||||
"DENO_DEPLOYMENT_ID",
|
|
||||||
);
|
|
||||||
const deploymentId = DENO_DEPLOYMENT_ID ||
|
const deploymentId = DENO_DEPLOYMENT_ID ||
|
||||||
// For CI
|
// For CI
|
||||||
Deno.env.get("GITHUB_SHA") ||
|
Deno.env.get("GITHUB_SHA") ||
|
||||||
@@ -12,8 +10,8 @@ const buildIdHash = await crypto.subtle.digest(
|
|||||||
new TextEncoder().encode(deploymentId),
|
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;
|
BUILD_ID = buildId;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -329,7 +329,7 @@ export async function applyPartials(res: Response): Promise<void> {
|
|||||||
for (let i = 0; i < json.islands.length; i++) {
|
for (let i = 0; i < json.islands.length; i++) {
|
||||||
const island = json.islands[i];
|
const island = json.islands[i];
|
||||||
promises.push(
|
promises.push(
|
||||||
import(/* @vite-ignore */ island.chunk).then((mod) => {
|
import(island.chunk).then((mod) => {
|
||||||
ISLAND_REGISTRY.set(island.name, mod[island.exportName]);
|
ISLAND_REGISTRY.set(island.name, mod[island.exportName]);
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { options } from "preact";
|
import { options } from "preact";
|
||||||
import { assetHashingHook, CLIENT_NAV_ATTR } from "../shared_internal.tsx";
|
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;
|
const oldVNodeHook = options.vnode;
|
||||||
options.vnode = (vnode) => {
|
options.vnode = (vnode) => {
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ import {
|
|||||||
setActiveUrl,
|
setActiveUrl,
|
||||||
} from "../shared_internal.tsx";
|
} from "../shared_internal.tsx";
|
||||||
import type { BuildCache } from "../../build_cache.ts";
|
import type { BuildCache } from "../../build_cache.ts";
|
||||||
import { BUILD_ID } from "fresh/build-id";
|
import { BUILD_ID } from "../build_id.ts";
|
||||||
import {
|
import {
|
||||||
DEV_ERROR_OVERLAY_URL,
|
DEV_ERROR_OVERLAY_URL,
|
||||||
PARTIAL_SEARCH_PARAM,
|
PARTIAL_SEARCH_PARAM,
|
||||||
@@ -433,8 +433,7 @@ export interface PartialStateJson {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function FreshRuntimeScript() {
|
function FreshRuntimeScript() {
|
||||||
const { islands, nonce, ctx, islandProps, partialId, buildCache } =
|
const { islands, nonce, ctx, islandProps, partialId } = RENDER_STATE!;
|
||||||
RENDER_STATE!;
|
|
||||||
const basePath = ctx.config.basePath;
|
const basePath = ctx.config.basePath;
|
||||||
|
|
||||||
const islandArr = Array.from(islands);
|
const islandArr = Array.from(islands);
|
||||||
@@ -471,11 +470,7 @@ function FreshRuntimeScript() {
|
|||||||
: island.exportName === island.name
|
: island.exportName === island.name
|
||||||
? `{ ${island.exportName} }`
|
? `{ ${island.exportName} }`
|
||||||
: `{ ${island.exportName} as ${island.name} }`;
|
: `{ ${island.exportName} as ${island.name} }`;
|
||||||
|
return `import ${named} from "${`${basePath}${island.file}`}";`;
|
||||||
const islandSpec = island.file.startsWith(".")
|
|
||||||
? island.file.slice(1)
|
|
||||||
: island.file;
|
|
||||||
return `import ${named} from "${basePath}${islandSpec}";`;
|
|
||||||
}).join("");
|
}).join("");
|
||||||
|
|
||||||
const islandObj = "{" + islandArr.map((island) => island.name)
|
const islandObj = "{" + islandArr.map((island) => island.name)
|
||||||
@@ -487,12 +482,9 @@ function FreshRuntimeScript() {
|
|||||||
{ json: true },
|
{ json: true },
|
||||||
);
|
);
|
||||||
|
|
||||||
// const runtimeUrl = `${basePath}/_fresh/js/${BUILD_ID}/fresh-runtime.js`;
|
const runtimeUrl = `${basePath}/_fresh/js/${BUILD_ID}/fresh-runtime.js`;
|
||||||
const runtimeUrl = buildCache.clientEntry.startsWith(".")
|
|
||||||
? buildCache.clientEntry.slice(1)
|
|
||||||
: buildCache.clientEntry;
|
|
||||||
const scriptContent =
|
const scriptContent =
|
||||||
`import { boot } from "${basePath}${runtimeUrl}";${islandImports}boot(${islandObj},${serializedProps});`;
|
`import { boot } from "${runtimeUrl}";${islandImports}boot(${islandObj},${serializedProps});`;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -504,7 +496,7 @@ function FreshRuntimeScript() {
|
|||||||
__html: scriptContent,
|
__html: scriptContent,
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
{buildCache.features.errorOverlay ? <ShowErrorOverlay /> : null}
|
{ctx.config.mode === "development" ? <ShowErrorOverlay /> : null}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { ComponentChildren, VNode } from "preact";
|
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";
|
import { assetInternal, assetSrcSetInternal } from "./shared_internal.tsx";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+2
-5
@@ -83,7 +83,7 @@ export function serveMiddleware<T>(
|
|||||||
(() => new Response("not found", { status: 404 }));
|
(() => new Response("not found", { status: 404 }));
|
||||||
const config = options.config ?? DEFAULT_CONFIG;
|
const config = options.config ?? DEFAULT_CONFIG;
|
||||||
const buildCache = options.buildCache ??
|
const buildCache = options.buildCache ??
|
||||||
new MockBuildCache<T>([], options.config?.mode ?? "production");
|
new MockBuildCache<T>([]);
|
||||||
|
|
||||||
const ctx = new Context<T>(
|
const ctx = new Context<T>(
|
||||||
req,
|
req,
|
||||||
@@ -149,12 +149,9 @@ export async function withTmpDir(
|
|||||||
export class MockBuildCache<State> implements BuildCache<State> {
|
export class MockBuildCache<State> implements BuildCache<State> {
|
||||||
#files: FsRouteFile<State>[];
|
#files: FsRouteFile<State>[];
|
||||||
root = "";
|
root = "";
|
||||||
clientEntry = "";
|
|
||||||
islandRegistry: ServerIslandRegistry = new Map();
|
islandRegistry: ServerIslandRegistry = new Map();
|
||||||
features = { errorOverlay: false };
|
|
||||||
|
|
||||||
constructor(files: FsRouteFile<State>[], mode: "development" | "production") {
|
constructor(files: FsRouteFile<State>[]) {
|
||||||
this.features.errorOverlay = mode === "development";
|
|
||||||
this.#files = files;
|
this.#files = files;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -124,8 +124,7 @@ export async function withChildProcessServer(
|
|||||||
let address = "";
|
let address = "";
|
||||||
let found = false;
|
let found = false;
|
||||||
// @ts-ignore yes it does
|
// @ts-ignore yes it does
|
||||||
for await (const raw of lines.values({ preventCancel: true })) {
|
for await (const line of lines.values({ preventCancel: true })) {
|
||||||
const line = colors.stripAnsiCode(raw);
|
|
||||||
output.push(line);
|
output.push(line);
|
||||||
const match = line.match(
|
const match = line.match(
|
||||||
/https?:\/\/[^:]+:\d+(\/\w+[-\w]*)*/g,
|
/https?:\/\/[^:]+:\d+(\/\w+[-\w]*)*/g,
|
||||||
|
|||||||
Reference in New Issue
Block a user