chore: restructure repository into packages/ folder (#3197)
We're having a growing number of packages in this repository. This PR moves them into a `packages/` directory like it's commonly done in other projects.
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
# Fresh build id
|
||||
|
||||
Don't use this package directly. It's considered internal for Fresh.
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "@fresh/build-id",
|
||||
"version": "1.0.0",
|
||||
"license": "MIT",
|
||||
"exports": {
|
||||
".": "./mod.ts"
|
||||
},
|
||||
"imports": {
|
||||
"@std/encoding": "jsr:@std/encoding@^1.0.10"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { encodeHex } from "@std/encoding/hex";
|
||||
|
||||
export const DENO_DEPLOYMENT_ID: string | undefined = Deno.env.get(
|
||||
"DENO_DEPLOYMENT_ID",
|
||||
);
|
||||
const deploymentId = DENO_DEPLOYMENT_ID ||
|
||||
// For CI
|
||||
Deno.env.get("GITHUB_SHA") ||
|
||||
crypto.randomUUID();
|
||||
const buildIdHash = await crypto.subtle.digest(
|
||||
"SHA-1",
|
||||
new TextEncoder().encode(deploymentId),
|
||||
);
|
||||
|
||||
export let BUILD_ID: string = encodeHex(buildIdHash);
|
||||
|
||||
export function setBuildId(buildId: string): void {
|
||||
BUILD_ID = buildId;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021-2024 the Deno authors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the "Software"), to deal in
|
||||
the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -0,0 +1,44 @@
|
||||
# Examples for Fresh
|
||||
|
||||
This package contains examples for using Fresh with [JSR](https://jsr.io/).
|
||||
|
||||
Learn more about the Fresh framework here:
|
||||
[https://fresh.deno.dev/](https://fresh.deno.dev/)
|
||||
|
||||
## Usage: Island example
|
||||
|
||||
```tsx
|
||||
import { App } from "fresh";
|
||||
// Import the island function
|
||||
import { DemoIsland } from "jsr:@fresh/examples/island";
|
||||
|
||||
export const app = new App({ root: import.meta.url })
|
||||
.use(staticFiles());
|
||||
|
||||
// Use the island somewhere in your components
|
||||
app.get("/", (ctx) => ctx.render(<DemoIsland />));
|
||||
|
||||
await app.listen();
|
||||
```
|
||||
|
||||
## Usage: App1 or App2 example
|
||||
|
||||
```tsx
|
||||
import { App } from "fresh";
|
||||
// Import the example apps
|
||||
import { app1 } from "jsr:@fresh/examples/app1";
|
||||
import { app2 } from "jsr:@fresh/examples/app2";
|
||||
|
||||
export const app = new App({ root: import.meta.url })
|
||||
.use(staticFiles());
|
||||
|
||||
// Merge apps from JSR into this one
|
||||
app.mountApp("/app1", app1);
|
||||
app.mountApp("/app2", app1);
|
||||
|
||||
await app.listen();
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
MIT, see the [LICENSE](./LICENSE) file.
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"name": "@fresh/examples",
|
||||
"version": "1.0.1",
|
||||
"license": "MIT",
|
||||
"exports": {
|
||||
"./island": "./src/island.tsx",
|
||||
"./app1": "./src/app1.tsx",
|
||||
"./app2": "./src/app2.tsx"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { App } from "fresh";
|
||||
import { Doc } from "./shared.tsx";
|
||||
|
||||
export const app1: App<unknown> = new App()
|
||||
.get("/", (ctx) =>
|
||||
ctx.render(
|
||||
<Doc>
|
||||
<h1>App1</h1>
|
||||
<p>This app is loaded from JSR</p>
|
||||
</Doc>,
|
||||
));
|
||||
@@ -0,0 +1,11 @@
|
||||
import { App } from "fresh";
|
||||
import { Doc } from "./shared.tsx";
|
||||
|
||||
export const app2: App<unknown> = new App()
|
||||
.get("/", (ctx) =>
|
||||
ctx.render(
|
||||
<Doc>
|
||||
<h1>App2</h1>
|
||||
<p>This app is loaded from JSR</p>
|
||||
</Doc>,
|
||||
));
|
||||
@@ -0,0 +1,14 @@
|
||||
import { useSignal } from "@preact/signals";
|
||||
import type { JSX } from "preact";
|
||||
|
||||
export function DemoIsland(): JSX.Element {
|
||||
const count = useSignal(0);
|
||||
|
||||
return (
|
||||
<div style="display: flex; gap: 1rem; padding: 2rem;">
|
||||
<button type="button" onClick={() => (count.value -= 1)}>-1</button>
|
||||
<p style="font-variant-numeric: tabular-nums;">{count}</p>
|
||||
<button type="button" onClick={() => (count.value += 1)}>+1</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { ComponentChildren } from "preact";
|
||||
|
||||
export function Doc(props: { children?: ComponentChildren }) {
|
||||
return (
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>Fresh Examples</title>
|
||||
</head>
|
||||
<body>{props.children}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
# Fresh
|
||||
|
||||
Fresh is a small, fast and extensible full stack web framework built on Web
|
||||
Standards. It’s designed for building high-quality, performant, and personalized
|
||||
web applications.
|
||||
|
||||
[Learn more about Fresh](https://fresh.deno.dev/)
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"name": "@fresh/core",
|
||||
"version": "2.0.0-alpha.56",
|
||||
"license": "MIT",
|
||||
"exports": {
|
||||
".": "./src/mod.ts",
|
||||
"./runtime": "./src/runtime/shared.ts",
|
||||
"./runtime-client": "./src/runtime/client/mod.tsx",
|
||||
"./dev": "./src/dev/mod.ts",
|
||||
"./compat": "./src/compat.ts",
|
||||
"./internal": "./src/internals.ts",
|
||||
"./internal-dev": "./src/internals_dev.ts"
|
||||
},
|
||||
"imports": {
|
||||
"@std/fmt": "jsr:@std/fmt@^1.0.8"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,460 @@
|
||||
import { trace } from "@opentelemetry/api";
|
||||
|
||||
import { DENO_DEPLOYMENT_ID } from "@fresh/build-id";
|
||||
import * as colors from "@std/fmt/colors";
|
||||
import {
|
||||
type MaybeLazyMiddleware,
|
||||
type Middleware,
|
||||
runMiddlewares,
|
||||
} from "./middlewares/mod.ts";
|
||||
import { Context } from "./context.ts";
|
||||
import { mergePath, type Method, UrlPatternRouter } from "./router.ts";
|
||||
import type { FreshConfig, ResolvedFreshConfig } from "./config.ts";
|
||||
import type { BuildCache } from "./build_cache.ts";
|
||||
import { HttpError } from "./error.ts";
|
||||
import type { LayoutConfig, MaybeLazy, Route, RouteConfig } from "./types.ts";
|
||||
import type { RouteComponent } from "./segments.ts";
|
||||
import {
|
||||
applyCommands,
|
||||
type Command,
|
||||
CommandType,
|
||||
DEFAULT_NOT_ALLOWED_METHOD,
|
||||
DEFAULT_NOT_FOUND,
|
||||
newAppCmd,
|
||||
newErrorCmd,
|
||||
newHandlerCmd,
|
||||
newLayoutCmd,
|
||||
newMiddlewareCmd,
|
||||
newNotFoundCmd,
|
||||
newRouteCmd,
|
||||
} from "./commands.ts";
|
||||
import { MockBuildCache } from "./test_utils.ts";
|
||||
|
||||
// TODO: Completed type clashes in older Deno versions
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export const DEFAULT_CONN_INFO: any = {
|
||||
localAddr: { transport: "tcp", hostname: "localhost", port: 8080 },
|
||||
remoteAddr: { transport: "tcp", hostname: "localhost", port: 1234 },
|
||||
};
|
||||
|
||||
const defaultOptionsHandler = (methods: string[]): () => Promise<Response> => {
|
||||
return () =>
|
||||
Promise.resolve(
|
||||
new Response(null, {
|
||||
status: 204,
|
||||
headers: { Allow: methods.join(", ") },
|
||||
}),
|
||||
);
|
||||
};
|
||||
// deno-lint-ignore require-await
|
||||
const DEFAULT_ERROR_HANDLER = async <State>(ctx: Context<State>) => {
|
||||
const { error } = ctx;
|
||||
|
||||
if (error instanceof HttpError) {
|
||||
if (error.status >= 500) {
|
||||
// deno-lint-ignore no-console
|
||||
console.error(error);
|
||||
}
|
||||
return new Response(error.message, { status: error.status });
|
||||
}
|
||||
|
||||
// deno-lint-ignore no-console
|
||||
console.error(error);
|
||||
return new Response("Internal server error", { status: 500 });
|
||||
};
|
||||
|
||||
export type ListenOptions =
|
||||
& Partial<
|
||||
Deno.ServeTcpOptions & Deno.TlsCertifiedKeyPem
|
||||
>
|
||||
& {
|
||||
remoteAddress?: string;
|
||||
};
|
||||
function createOnListen(
|
||||
basePath: string,
|
||||
options: ListenOptions,
|
||||
): (localAddr: Deno.NetAddr) => void {
|
||||
return (params) => {
|
||||
// Don't spam logs with this on live deployments
|
||||
if (DENO_DEPLOYMENT_ID) return;
|
||||
|
||||
const pathname = basePath + "/";
|
||||
const protocol = "key" in options && options.key && options.cert
|
||||
? "https:"
|
||||
: "http:";
|
||||
|
||||
let hostname = params.hostname;
|
||||
// Windows being windows...
|
||||
if (
|
||||
Deno.build.os === "windows" &&
|
||||
(hostname === "0.0.0.0" || hostname === "::")
|
||||
) {
|
||||
hostname = "localhost";
|
||||
}
|
||||
// Work around https://github.com/denoland/deno/issues/23650
|
||||
hostname = hostname.startsWith("::") ? `[${hostname}]` : hostname;
|
||||
|
||||
// deno-lint-ignore no-console
|
||||
console.log();
|
||||
// deno-lint-ignore no-console
|
||||
console.log(
|
||||
colors.bgRgb8(colors.rgb8(" 🍋 Fresh ready ", 0), 121),
|
||||
);
|
||||
const sep = options.remoteAddress ? "" : "\n";
|
||||
const space = options.remoteAddress ? " " : "";
|
||||
|
||||
const localLabel = colors.bold("Local:");
|
||||
const address = colors.cyan(
|
||||
`${protocol}//${hostname}:${params.port}${pathname}`,
|
||||
);
|
||||
const helper = hostname === "0.0.0.0" || hostname === "::"
|
||||
? colors.cyan(` (${protocol}//localhost:${params.port}${pathname})`)
|
||||
: "";
|
||||
// deno-lint-ignore no-console
|
||||
console.log(` ${localLabel} ${space}${address}${helper}${sep}`);
|
||||
if (options.remoteAddress) {
|
||||
const remoteLabel = colors.bold("Remote:");
|
||||
const remoteAddress = colors.cyan(options.remoteAddress);
|
||||
// deno-lint-ignore no-console
|
||||
console.log(` ${remoteLabel} ${remoteAddress}\n`);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async function listenOnFreePort(
|
||||
options: ListenOptions,
|
||||
handler: (
|
||||
request: Request,
|
||||
info?: Deno.ServeHandlerInfo,
|
||||
) => Promise<Response>,
|
||||
) {
|
||||
// No port specified, check for a free port. Instead of picking just
|
||||
// any port we'll check if the next one is free for UX reasons.
|
||||
// That way the user only needs to increment a number when running
|
||||
// multiple apps vs having to remember completely different ports.
|
||||
let firstError = null;
|
||||
for (let port = 8000; port < 8020; port++) {
|
||||
try {
|
||||
return await Deno.serve({ ...options, port }, handler);
|
||||
} catch (err) {
|
||||
if (err instanceof Deno.errors.AddrInUse) {
|
||||
// Throw first EADDRINUSE error if no port is free
|
||||
if (!firstError) firstError = err;
|
||||
continue;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
throw firstError;
|
||||
}
|
||||
|
||||
export let getBuildCache: <State>(app: App<State>) => BuildCache<State> | null;
|
||||
export let setBuildCache: <State>(
|
||||
app: App<State>,
|
||||
cache: BuildCache<State>,
|
||||
mode: "development" | "production",
|
||||
) => void;
|
||||
|
||||
/**
|
||||
* Create an application instance that passes the incoming `Request`
|
||||
* instance through middlewares and routes.
|
||||
*/
|
||||
export class App<State> {
|
||||
#getBuildCache: () => BuildCache<State> | null = () => null;
|
||||
#commands: Command<State>[] = [];
|
||||
|
||||
static {
|
||||
getBuildCache = (app) => app.#getBuildCache();
|
||||
setBuildCache = (app, cache, mode: "development" | "production") => {
|
||||
app.config.root = cache.root;
|
||||
app.config.mode = mode;
|
||||
app.#getBuildCache = () => cache;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The final resolved Fresh configuration.
|
||||
*/
|
||||
config: ResolvedFreshConfig;
|
||||
|
||||
constructor(config: FreshConfig = {}) {
|
||||
this.config = {
|
||||
root: Deno.cwd(),
|
||||
basePath: config.basePath ?? "",
|
||||
mode: config.mode ?? "production",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Add one or more middlewares at the top or the specified path.
|
||||
*/
|
||||
use(...middleware: MaybeLazyMiddleware<State>[]): this;
|
||||
use(path: string, ...middleware: MaybeLazyMiddleware<State>[]): this;
|
||||
use(
|
||||
pathOrMiddleware: string | MaybeLazyMiddleware<State>,
|
||||
...middlewares: MaybeLazyMiddleware<State>[]
|
||||
): this {
|
||||
let pattern: string;
|
||||
let fns: MaybeLazyMiddleware<State>[];
|
||||
if (typeof pathOrMiddleware === "string") {
|
||||
pattern = pathOrMiddleware;
|
||||
fns = middlewares!;
|
||||
} else {
|
||||
pattern = "*";
|
||||
middlewares.unshift(pathOrMiddleware);
|
||||
fns = middlewares;
|
||||
}
|
||||
|
||||
this.#commands.push(newMiddlewareCmd(pattern, fns, true));
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the app's 404 error handler. Can be a {@linkcode Route} or a {@linkcode Middleware}.
|
||||
*/
|
||||
notFound(routeOrMiddleware: Route<State> | Middleware<State>): this {
|
||||
this.#commands.push(newNotFoundCmd(routeOrMiddleware));
|
||||
return this;
|
||||
}
|
||||
|
||||
onError(
|
||||
path: string,
|
||||
routeOrMiddleware: Route<State> | Middleware<State>,
|
||||
): this {
|
||||
this.#commands.push(newErrorCmd(path, routeOrMiddleware, true));
|
||||
return this;
|
||||
}
|
||||
|
||||
appWrapper(component: RouteComponent<State>): this {
|
||||
this.#commands.push(newAppCmd(component));
|
||||
return this;
|
||||
}
|
||||
|
||||
layout(
|
||||
path: string,
|
||||
component: RouteComponent<State>,
|
||||
config?: LayoutConfig,
|
||||
): this {
|
||||
this.#commands.push(newLayoutCmd(path, component, config, true));
|
||||
return this;
|
||||
}
|
||||
|
||||
route(
|
||||
path: string,
|
||||
route: MaybeLazy<Route<State>>,
|
||||
config?: RouteConfig,
|
||||
): this {
|
||||
this.#commands.push(newRouteCmd(path, route, config, false));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add middlewares for GET requests at the specified path.
|
||||
*/
|
||||
get(path: string, ...middlewares: MaybeLazy<Middleware<State>>[]): this {
|
||||
this.#commands.push(newHandlerCmd("GET", path, middlewares, false));
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Add middlewares for POST requests at the specified path.
|
||||
*/
|
||||
post(path: string, ...middlewares: MaybeLazy<Middleware<State>>[]): this {
|
||||
this.#commands.push(newHandlerCmd("POST", path, middlewares, false));
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Add middlewares for PATCH requests at the specified path.
|
||||
*/
|
||||
patch(path: string, ...middlewares: MaybeLazy<Middleware<State>>[]): this {
|
||||
this.#commands.push(newHandlerCmd("PATCH", path, middlewares, false));
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Add middlewares for PUT requests at the specified path.
|
||||
*/
|
||||
put(path: string, ...middlewares: MaybeLazy<Middleware<State>>[]): this {
|
||||
this.#commands.push(newHandlerCmd("PUT", path, middlewares, false));
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Add middlewares for DELETE requests at the specified path.
|
||||
*/
|
||||
delete(path: string, ...middlewares: MaybeLazy<Middleware<State>>[]): this {
|
||||
this.#commands.push(newHandlerCmd("DELETE", path, middlewares, false));
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Add middlewares for HEAD requests at the specified path.
|
||||
*/
|
||||
head(path: string, ...middlewares: MaybeLazy<Middleware<State>>[]): this {
|
||||
this.#commands.push(newHandlerCmd("HEAD", path, middlewares, false));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add middlewares for all HTTP verbs at the specified path.
|
||||
*/
|
||||
all(path: string, ...middlewares: MaybeLazy<Middleware<State>>[]): this {
|
||||
this.#commands.push(newHandlerCmd("ALL", path, middlewares, false));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert file routes collected in {@linkcode Builder} at this point.
|
||||
* @param pattern Append file routes at this pattern instead of the root
|
||||
* @returns
|
||||
*/
|
||||
fsRoutes(pattern = "*"): this {
|
||||
this.#commands.push({
|
||||
type: CommandType.FsRoute,
|
||||
pattern,
|
||||
getItems: () => {
|
||||
const buildCache = this.#getBuildCache();
|
||||
if (buildCache === null) return [];
|
||||
return buildCache.getFsRoutes();
|
||||
},
|
||||
includeLastSegment: false,
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge another {@linkcode App} instance into this app at the
|
||||
* specified path.
|
||||
*/
|
||||
mountApp(path: string, app: App<State>): this {
|
||||
for (let i = 0; i < app.#commands.length; i++) {
|
||||
const cmd = app.#commands[i];
|
||||
|
||||
if (cmd.type !== CommandType.App && cmd.type !== CommandType.NotFound) {
|
||||
const clone = {
|
||||
...cmd,
|
||||
pattern: mergePath(path, cmd.pattern),
|
||||
includeLastSegment: cmd.pattern === "/" || cmd.includeLastSegment,
|
||||
};
|
||||
this.#commands.push(clone);
|
||||
continue;
|
||||
}
|
||||
|
||||
this.#commands.push(cmd);
|
||||
}
|
||||
|
||||
// deno-lint-ignore no-this-alias
|
||||
const self = this;
|
||||
app.#getBuildCache = () => self.#getBuildCache();
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create handler function for `Deno.serve` or to be used in
|
||||
* testing.
|
||||
*/
|
||||
handler(): (
|
||||
request: Request,
|
||||
info?: Deno.ServeHandlerInfo,
|
||||
) => Promise<Response> {
|
||||
let buildCache = this.#getBuildCache();
|
||||
if (buildCache === null) {
|
||||
if (
|
||||
this.config.mode === "production" &&
|
||||
DENO_DEPLOYMENT_ID !== undefined
|
||||
) {
|
||||
throw new Error(
|
||||
`Could not find _fresh directory. Maybe you forgot to run "deno task build"?`,
|
||||
);
|
||||
} else {
|
||||
buildCache = new MockBuildCache([], this.config.mode);
|
||||
}
|
||||
}
|
||||
|
||||
const router = new UrlPatternRouter<MaybeLazyMiddleware<State>>();
|
||||
|
||||
const { rootMiddlewares } = applyCommands(
|
||||
router,
|
||||
this.#commands,
|
||||
this.config.basePath,
|
||||
);
|
||||
|
||||
return async (
|
||||
req: Request,
|
||||
conn: Deno.ServeHandlerInfo = DEFAULT_CONN_INFO,
|
||||
) => {
|
||||
const url = new URL(req.url);
|
||||
// Prevent open redirect attacks
|
||||
url.pathname = url.pathname.replace(/\/+/g, "/");
|
||||
|
||||
const method = req.method.toUpperCase() as Method;
|
||||
const matched = router.match(method, url);
|
||||
let { params, pattern, handlers, methodMatch } = matched;
|
||||
|
||||
const span = trace.getActiveSpan();
|
||||
if (span && pattern) {
|
||||
span.updateName(`${method} ${pattern}`);
|
||||
span.setAttribute("http.route", pattern);
|
||||
}
|
||||
|
||||
let next: () => Promise<Response>;
|
||||
|
||||
if (pattern === null || !methodMatch) {
|
||||
handlers = rootMiddlewares;
|
||||
}
|
||||
|
||||
if (matched.pattern !== null && !methodMatch) {
|
||||
if (method === "OPTIONS") {
|
||||
const allowed = router.getAllowedMethods(matched.pattern);
|
||||
next = defaultOptionsHandler(allowed);
|
||||
} else {
|
||||
next = DEFAULT_NOT_ALLOWED_METHOD;
|
||||
}
|
||||
} else {
|
||||
next = DEFAULT_NOT_FOUND;
|
||||
}
|
||||
|
||||
const ctx = new Context<State>(
|
||||
req,
|
||||
url,
|
||||
conn,
|
||||
matched.pattern,
|
||||
params,
|
||||
this.config,
|
||||
next,
|
||||
buildCache!,
|
||||
);
|
||||
|
||||
try {
|
||||
if (handlers.length === 0) return await next();
|
||||
|
||||
const result = await runMiddlewares(handlers, ctx);
|
||||
if (!(result instanceof Response)) {
|
||||
throw new Error(
|
||||
`Expected a "Response" instance to be returned, but got: ${result}`,
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (err) {
|
||||
ctx.error = err;
|
||||
return await DEFAULT_ERROR_HANDLER(ctx);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Spawn a server for this app.
|
||||
*/
|
||||
async listen(options: ListenOptions = {}): Promise<void> {
|
||||
if (!options.onListen) {
|
||||
options.onListen = createOnListen(this.config.basePath, options);
|
||||
}
|
||||
|
||||
const handler = this.handler();
|
||||
if (options.port) {
|
||||
await Deno.serve(options, handler);
|
||||
return;
|
||||
}
|
||||
|
||||
await listenOnFreePort(options, handler);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,779 @@
|
||||
import { expect } from "@std/expect";
|
||||
import { App } from "./app.ts";
|
||||
import { FakeServer } from "./test_utils.ts";
|
||||
import { HttpError } from "./error.ts";
|
||||
|
||||
Deno.test("App - .use()", async () => {
|
||||
const app = new App<{ text: string }>()
|
||||
.use((ctx) => {
|
||||
ctx.state.text = "A";
|
||||
return ctx.next();
|
||||
})
|
||||
.use((ctx) => {
|
||||
ctx.state.text += "B";
|
||||
return ctx.next();
|
||||
})
|
||||
.get("/", (ctx) => new Response(ctx.state.text));
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
const res = await server.get("/");
|
||||
expect(await res.text()).toEqual("AB");
|
||||
});
|
||||
|
||||
Deno.test("App - .use() #2", async () => {
|
||||
const app = new App<{ text: string }>()
|
||||
.use(() => new Response("ok #1"))
|
||||
.get("/foo/bar", () => new Response("ok #2"))
|
||||
.get("/", () => new Response("ok #3"));
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
const res = await server.get("/");
|
||||
expect(await res.text()).toEqual("ok #1");
|
||||
});
|
||||
|
||||
Deno.test("App - .get()", async () => {
|
||||
const app = new App()
|
||||
.get("/", () => new Response("ok"))
|
||||
.get("/foo", () => new Response("ok"));
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
let res = await server.get("/");
|
||||
expect(await res.text()).toEqual("ok");
|
||||
|
||||
res = await server.get("/foo");
|
||||
expect(await res.text()).toEqual("ok");
|
||||
});
|
||||
|
||||
Deno.test("App - .get() with basePath", async () => {
|
||||
const app = new App({ basePath: "/foo/bar" })
|
||||
.get("/", () => new Response("ok"))
|
||||
.get("/foo", () => new Response("ok"));
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
let res = await server.get("/");
|
||||
expect(res.status).toEqual(404);
|
||||
res = await server.get("/foo");
|
||||
expect(res.status).toEqual(404);
|
||||
|
||||
res = await server.get("/foo/bar");
|
||||
expect(res.status).toEqual(200);
|
||||
res = await server.get("/foo/bar/foo");
|
||||
expect(res.status).toEqual(200);
|
||||
});
|
||||
|
||||
Deno.test("App - .post()", async () => {
|
||||
const app = new App<{ text: string }>()
|
||||
.get("/", () => new Response("fail"))
|
||||
.get("/foo", () => new Response("fail"))
|
||||
.post("/", () => new Response("ok"))
|
||||
.post("/foo", () => new Response("ok"));
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
let res = await server.post("/");
|
||||
expect(await res.text()).toEqual("ok");
|
||||
|
||||
res = await server.post("/foo");
|
||||
expect(await res.text()).toEqual("ok");
|
||||
});
|
||||
|
||||
Deno.test("App - .post() with basePath", async () => {
|
||||
const app = new App({ basePath: "/foo/bar" })
|
||||
.post("/", () => new Response("ok"))
|
||||
.post("/foo", () => new Response("ok"));
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
let res = await server.post("/");
|
||||
expect(res.status).toEqual(404);
|
||||
res = await server.post("/foo");
|
||||
expect(res.status).toEqual(404);
|
||||
|
||||
res = await server.post("/foo/bar");
|
||||
expect(res.status).toEqual(200);
|
||||
res = await server.post("/foo/bar/foo");
|
||||
expect(res.status).toEqual(200);
|
||||
});
|
||||
|
||||
Deno.test("App - .patch()", async () => {
|
||||
const app = new App<{ text: string }>()
|
||||
.get("/", () => new Response("fail"))
|
||||
.get("/foo", () => new Response("fail"))
|
||||
.patch("/", () => new Response("ok"))
|
||||
.patch("/foo", () => new Response("ok"));
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
let res = await server.patch("/");
|
||||
expect(await res.text()).toEqual("ok");
|
||||
|
||||
res = await server.patch("/foo");
|
||||
expect(await res.text()).toEqual("ok");
|
||||
});
|
||||
|
||||
Deno.test("App - .patch() with basePath", async () => {
|
||||
const app = new App({ basePath: "/foo/bar" })
|
||||
.patch("/", () => new Response("ok"))
|
||||
.patch("/foo", () => new Response("ok"));
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
let res = await server.patch("/");
|
||||
expect(res.status).toEqual(404);
|
||||
res = await server.patch("/foo");
|
||||
expect(res.status).toEqual(404);
|
||||
|
||||
res = await server.patch("/foo/bar");
|
||||
expect(res.status).toEqual(200);
|
||||
res = await server.patch("/foo/bar/foo");
|
||||
expect(res.status).toEqual(200);
|
||||
});
|
||||
|
||||
Deno.test("App - .put()", async () => {
|
||||
const app = new App<{ text: string }>()
|
||||
.get("/", () => new Response("fail"))
|
||||
.get("/foo", () => new Response("fail"))
|
||||
.put("/", () => new Response("ok"))
|
||||
.put("/foo", () => new Response("ok"));
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
let res = await server.put("/");
|
||||
expect(await res.text()).toEqual("ok");
|
||||
|
||||
res = await server.put("/foo");
|
||||
expect(await res.text()).toEqual("ok");
|
||||
});
|
||||
|
||||
Deno.test("App - .put() with basePath", async () => {
|
||||
const app = new App({ basePath: "/foo/bar" })
|
||||
.put("/", () => new Response("ok"))
|
||||
.put("/foo", () => new Response("ok"));
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
let res = await server.put("/");
|
||||
expect(res.status).toEqual(404);
|
||||
res = await server.put("/foo");
|
||||
expect(res.status).toEqual(404);
|
||||
|
||||
res = await server.put("/foo/bar");
|
||||
expect(res.status).toEqual(200);
|
||||
res = await server.put("/foo/bar/foo");
|
||||
expect(res.status).toEqual(200);
|
||||
});
|
||||
|
||||
Deno.test("App - .delete()", async () => {
|
||||
const app = new App<{ text: string }>()
|
||||
.get("/", () => new Response("fail"))
|
||||
.get("/foo", () => new Response("fail"))
|
||||
.delete("/", () => new Response("ok"))
|
||||
.delete("/foo", () => new Response("ok"));
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
let res = await server.delete("/");
|
||||
expect(await res.text()).toEqual("ok");
|
||||
|
||||
res = await server.delete("/foo");
|
||||
expect(await res.text()).toEqual("ok");
|
||||
});
|
||||
|
||||
Deno.test("App - .delete() with basePath", async () => {
|
||||
const app = new App({ basePath: "/foo/bar" })
|
||||
.delete("/", () => new Response("ok"))
|
||||
.delete("/foo", () => new Response("ok"));
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
let res = await server.delete("/");
|
||||
expect(res.status).toEqual(404);
|
||||
res = await server.delete("/foo");
|
||||
expect(res.status).toEqual(404);
|
||||
|
||||
res = await server.delete("/foo/bar");
|
||||
expect(res.status).toEqual(200);
|
||||
res = await server.delete("/foo/bar/foo");
|
||||
expect(res.status).toEqual(200);
|
||||
});
|
||||
|
||||
Deno.test("App - wrong method match", async () => {
|
||||
const app = new App<{ text: string }>()
|
||||
.get("/", () => new Response("ok"))
|
||||
.post("/", () => new Response("ok"));
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
let res = await server.put("/");
|
||||
expect(res.status).toEqual(405);
|
||||
expect(await res.text()).toEqual("Method Not Allowed");
|
||||
|
||||
res = await server.post("/");
|
||||
expect(res.status).toEqual(200);
|
||||
expect(await res.text()).toEqual("ok");
|
||||
});
|
||||
|
||||
Deno.test("App - methods with middleware", async () => {
|
||||
const app = new App<{ text: string }>()
|
||||
.use((ctx) => {
|
||||
ctx.state.text = "A";
|
||||
return ctx.next();
|
||||
})
|
||||
.get("/", (ctx) => new Response(ctx.state.text))
|
||||
.post("/", (ctx) => new Response(ctx.state.text));
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
let res = await server.get("/");
|
||||
expect(await res.text()).toEqual("A");
|
||||
|
||||
res = await server.post("/");
|
||||
expect(await res.text()).toEqual("A");
|
||||
});
|
||||
|
||||
Deno.test("App - .mountApp() compose apps", async () => {
|
||||
const innerApp = new App<{ text: string }>()
|
||||
.use((ctx) => {
|
||||
ctx.state.text = "A";
|
||||
return ctx.next();
|
||||
})
|
||||
.get("/", (ctx) => new Response(ctx.state.text))
|
||||
.post("/", (ctx) => new Response(ctx.state.text));
|
||||
|
||||
const app = new App<{ text: string }>()
|
||||
.get("/", () => new Response("ok"))
|
||||
.mountApp("/foo", innerApp);
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
let res = await server.get("/");
|
||||
expect(await res.text()).toEqual("ok");
|
||||
|
||||
res = await server.get("/foo");
|
||||
expect(await res.text()).toEqual("A");
|
||||
|
||||
res = await server.post("/foo");
|
||||
expect(await res.text()).toEqual("A");
|
||||
});
|
||||
|
||||
Deno.test("App - .mountApp() compose apps with .route()", async () => {
|
||||
const innerApp = new App<{ text: string }>()
|
||||
.use((ctx) => {
|
||||
ctx.state.text = "A";
|
||||
return ctx.next();
|
||||
})
|
||||
.route("/", { handler: (ctx) => new Response(ctx.state.text) });
|
||||
|
||||
const app = new App<{ text: string }>()
|
||||
.get("/", () => new Response("ok"))
|
||||
.mountApp("/foo", innerApp);
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
let res = await server.get("/");
|
||||
expect(await res.text()).toEqual("ok");
|
||||
|
||||
res = await server.get("/foo");
|
||||
expect(await res.text()).toEqual("A");
|
||||
});
|
||||
|
||||
Deno.test("App - .mountApp() self mount, no middleware", async () => {
|
||||
const innerApp = new App<{ text: string }>()
|
||||
.use((ctx) => {
|
||||
ctx.state.text = "A";
|
||||
return ctx.next();
|
||||
})
|
||||
.get("/foo", (ctx) => new Response(ctx.state.text))
|
||||
.post("/foo", (ctx) => new Response(ctx.state.text));
|
||||
|
||||
const app = new App<{ text: string }>()
|
||||
.get("/", () => new Response("ok"))
|
||||
.mountApp("/", innerApp);
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
let res = await server.get("/");
|
||||
expect(await res.text()).toEqual("ok");
|
||||
|
||||
res = await server.get("/foo");
|
||||
expect(await res.text()).toEqual("A");
|
||||
|
||||
res = await server.post("/foo");
|
||||
expect(await res.text()).toEqual("A");
|
||||
});
|
||||
|
||||
Deno.test(
|
||||
"App - .mountApp() self mount, with middleware",
|
||||
async () => {
|
||||
const innerApp = new App<{ text: string }>()
|
||||
.use(function B(ctx) {
|
||||
ctx.state.text += "B";
|
||||
return ctx.next();
|
||||
})
|
||||
.get("/foo", (ctx) => new Response(ctx.state.text))
|
||||
.post("/foo", (ctx) => new Response(ctx.state.text));
|
||||
|
||||
const app = new App<{ text: string }>()
|
||||
.use(function A(ctx) {
|
||||
ctx.state.text = "A";
|
||||
return ctx.next();
|
||||
})
|
||||
.get("/", () => new Response("ok"))
|
||||
.mountApp("/", innerApp);
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
let res = await server.get("/");
|
||||
expect(await res.text()).toEqual("ok");
|
||||
|
||||
res = await server.get("/foo");
|
||||
expect(await res.text()).toEqual("AB");
|
||||
|
||||
res = await server.post("/foo");
|
||||
expect(await res.text()).toEqual("AB");
|
||||
},
|
||||
);
|
||||
|
||||
Deno.test(
|
||||
"App - .mountApp() self mount, different order",
|
||||
async () => {
|
||||
const innerApp = new App<{ text: string }>()
|
||||
.use(function B(ctx) {
|
||||
ctx.state.text += "B";
|
||||
return ctx.next();
|
||||
})
|
||||
.get("/foo", (ctx) => new Response(ctx.state.text))
|
||||
.post("/foo", (ctx) => new Response(ctx.state.text));
|
||||
|
||||
const app = new App<{ text: string }>()
|
||||
.use(function A(ctx) {
|
||||
ctx.state.text = "A";
|
||||
return ctx.next();
|
||||
})
|
||||
.get("/", () => new Response("ok"))
|
||||
.mountApp("/", innerApp);
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
let res = await server.get("/");
|
||||
expect(await res.text()).toEqual("ok");
|
||||
|
||||
res = await server.get("/foo");
|
||||
expect(await res.text()).toEqual("AB");
|
||||
|
||||
res = await server.post("/foo");
|
||||
expect(await res.text()).toEqual("AB");
|
||||
},
|
||||
);
|
||||
|
||||
Deno.test("App - .mountApp() self mount empty", async () => {
|
||||
const innerApp = new App<{ text: string }>()
|
||||
.use((ctx) => {
|
||||
ctx.state.text = "A";
|
||||
return ctx.next();
|
||||
})
|
||||
.get("/foo", (ctx) => new Response(ctx.state.text));
|
||||
|
||||
const app = new App<{ text: string }>()
|
||||
.mountApp("/", innerApp);
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
const res = await server.get("/foo");
|
||||
expect(await res.text()).toEqual("A");
|
||||
});
|
||||
|
||||
Deno.test(
|
||||
"App - .mountApp() self mount with middleware",
|
||||
async () => {
|
||||
const innerApp = new App<{ text: string }>()
|
||||
.use(function Inner(ctx) {
|
||||
ctx.state.text += "_Inner";
|
||||
return ctx.next();
|
||||
})
|
||||
.get("/", (ctx) => new Response(ctx.state.text));
|
||||
|
||||
const app = new App<{ text: string }>()
|
||||
.use(function Outer(ctx) {
|
||||
ctx.state.text = "Outer";
|
||||
return ctx.next();
|
||||
})
|
||||
.mountApp("/", innerApp);
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
const res = await server.get("/");
|
||||
expect(await res.text()).toEqual("Outer_Inner");
|
||||
},
|
||||
);
|
||||
|
||||
// https://github.com/denoland/fresh/issues/3033
|
||||
Deno.test(
|
||||
"App - .mountApp() self mount with dynamic routes",
|
||||
async () => {
|
||||
const innerApp = new App<{ text: string }>()
|
||||
.get("/", () => new Response("list authors"))
|
||||
.get("/:name", (ctx) => new Response(`show: ${ctx.params.name}`));
|
||||
|
||||
const app = new App<{ text: string }>()
|
||||
.mountApp("/api/authors", innerApp);
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
let res = await server.get("/api/authors");
|
||||
expect(await res.text()).toEqual("list authors");
|
||||
|
||||
res = await server.get("/api/authors/foo");
|
||||
expect(await res.text()).toEqual("show: foo");
|
||||
},
|
||||
);
|
||||
|
||||
Deno.test("App - .mountApp() fallback route", async () => {
|
||||
let called = "";
|
||||
const innerApp = new App<{ text: string }>()
|
||||
.use(function Inner(ctx) {
|
||||
called += "_Inner";
|
||||
return ctx.next();
|
||||
})
|
||||
.get("/", (ctx) => new Response(ctx.state.text));
|
||||
|
||||
const app = new App<{ text: string }>()
|
||||
.use(function Outer(ctx) {
|
||||
called += "Outer";
|
||||
return ctx.next();
|
||||
})
|
||||
.mountApp("/", innerApp);
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
const res = await server.get("/invalid");
|
||||
await res.body?.cancel();
|
||||
expect(called).toEqual("Outer_Inner");
|
||||
});
|
||||
|
||||
Deno.test("App - catches errors", async () => {
|
||||
let thrownErr: unknown | null = null;
|
||||
const app = new App<{ text: string }>()
|
||||
.use(async (ctx) => {
|
||||
ctx.state.text = "A";
|
||||
try {
|
||||
return await ctx.next();
|
||||
} catch (err) {
|
||||
thrownErr = err;
|
||||
throw err;
|
||||
}
|
||||
})
|
||||
.get("/", () => {
|
||||
throw new Error("fail");
|
||||
});
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
const res = await server.get("/");
|
||||
expect(res.status).toEqual(500);
|
||||
expect(thrownErr).toBeInstanceOf(Error);
|
||||
});
|
||||
|
||||
Deno.test("App - sets error on context", async () => {
|
||||
const thrown: [unknown, unknown][] = [];
|
||||
const app = new App()
|
||||
.use(async (ctx) => {
|
||||
try {
|
||||
return await ctx.next();
|
||||
} catch (err) {
|
||||
thrown.push([err, ctx.error]);
|
||||
throw err;
|
||||
}
|
||||
})
|
||||
.use(async (ctx) => {
|
||||
try {
|
||||
return await ctx.next();
|
||||
} catch (err) {
|
||||
thrown.push([err, ctx.error]);
|
||||
throw err;
|
||||
}
|
||||
})
|
||||
.get("/", () => {
|
||||
throw "<mock error>";
|
||||
});
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
const res = await server.get("/");
|
||||
await res.body?.cancel();
|
||||
expect(thrown.length).toEqual(2);
|
||||
expect(thrown[0][0]).toEqual(thrown[0][1]);
|
||||
expect(thrown[1][0]).toEqual(thrown[1][1]);
|
||||
});
|
||||
|
||||
Deno.test("App - support setting request init in ctx.render()", async () => {
|
||||
const app = new App<{ text: string }>()
|
||||
.get("/", (ctx) => {
|
||||
return ctx.render(<div>ok</div>, {
|
||||
status: 416,
|
||||
headers: { "X-Foo": "foo" },
|
||||
});
|
||||
});
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
const res = await server.get("/");
|
||||
await res.body?.cancel();
|
||||
expect(res.status).toEqual(416);
|
||||
expect(res.headers.get("X-Foo")).toEqual("foo");
|
||||
});
|
||||
|
||||
Deno.test("App - throw when middleware returns no response", async () => {
|
||||
const app = new App<{ text: string }>()
|
||||
.get(
|
||||
"/",
|
||||
// deno-lint-ignore no-explicit-any
|
||||
(() => {}) as any,
|
||||
);
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
const res = await server.get("/");
|
||||
const text = await res.text();
|
||||
expect(res.status).toEqual(500);
|
||||
expect(text).toContain("Internal server error");
|
||||
});
|
||||
|
||||
Deno.test("App - overwrite default 404 handler", async () => {
|
||||
const app = new App()
|
||||
.notFound(() => new Response("bar", { status: 404 }))
|
||||
.get("/foo", () => new Response("foo"))
|
||||
.get("/thrower", () => {
|
||||
throw new HttpError(404);
|
||||
});
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
let res = await server.get("/invalid");
|
||||
expect(await res.text()).toEqual("bar");
|
||||
|
||||
res = await server.get("/thrower");
|
||||
expect(await res.text()).toEqual("bar");
|
||||
});
|
||||
|
||||
Deno.test("App - uses error route", async () => {
|
||||
const app = new App()
|
||||
.onError("*", () => new Response("error route", { status: 200 }))
|
||||
.get("/thrower", () => {
|
||||
throw new HttpError(404);
|
||||
});
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
let res = await server.get("/invalid");
|
||||
expect(await res.text()).toEqual("error route");
|
||||
|
||||
res = await server.get("/thrower");
|
||||
expect(await res.text()).toEqual("error route");
|
||||
});
|
||||
|
||||
Deno.test("App - uses notFound route on 404", async () => {
|
||||
const app = new App()
|
||||
.notFound(() => new Response("not found route", { status: 404 }))
|
||||
.onError("*", () => new Response("error route", { status: 500 }))
|
||||
.get("/thrower", () => {
|
||||
throw new HttpError(404);
|
||||
})
|
||||
.get("/thrower_2", () => {
|
||||
throw new HttpError(500);
|
||||
});
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
let res = await server.get("/invalid");
|
||||
expect(await res.text()).toEqual("not found route");
|
||||
|
||||
res = await server.get("/thrower");
|
||||
expect(await res.text()).toEqual("not found route");
|
||||
|
||||
res = await server.get("/thrower_2");
|
||||
expect(await res.text()).toEqual("error route");
|
||||
});
|
||||
|
||||
// Issue: https://github.com/denoland/fresh/issues/3115
|
||||
Deno.test("App - .route() with basePath", async () => {
|
||||
const app = new App({ basePath: "/foo/bar" })
|
||||
.route("/", { handler: () => new Response("ok") });
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
let res = await server.delete("/");
|
||||
await res.body?.cancel();
|
||||
expect(res.status).toEqual(404);
|
||||
|
||||
res = await server.delete("/foo");
|
||||
await res.body?.cancel();
|
||||
expect(res.status).toEqual(404);
|
||||
|
||||
res = await server.delete("/foo/bar");
|
||||
expect(await res.text()).toEqual("ok");
|
||||
expect(res.status).toEqual(200);
|
||||
});
|
||||
|
||||
Deno.test("App - .all() with *", async () => {
|
||||
const app = new App()
|
||||
.all("*", () => new Response("ok"));
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
const res = await server.get("/");
|
||||
expect(await res.text()).toEqual("ok");
|
||||
});
|
||||
|
||||
Deno.test("App - .route() with *", async () => {
|
||||
const app = new App()
|
||||
.route("*", { handler: () => new Response("ok") });
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
const res = await server.get("/");
|
||||
expect(await res.text()).toEqual("ok");
|
||||
});
|
||||
|
||||
Deno.test("App - .use() - lazy", async () => {
|
||||
const app = new App<{ text: string }>()
|
||||
// deno-lint-ignore require-await
|
||||
.use(async () => {
|
||||
return (ctx) => {
|
||||
ctx.state.text = "ok";
|
||||
return ctx.next();
|
||||
};
|
||||
})
|
||||
.get("/", (ctx) => new Response(ctx.state.text));
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
const res = await server.get("/");
|
||||
expect(await res.text()).toEqual("ok");
|
||||
});
|
||||
|
||||
Deno.test("App - .route() - lazy", async () => {
|
||||
const app = new App()
|
||||
// deno-lint-ignore require-await
|
||||
.route("/", async () => {
|
||||
return { handler: () => new Response("ok") };
|
||||
});
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
const res = await server.get("/");
|
||||
expect(await res.text()).toEqual("ok");
|
||||
});
|
||||
|
||||
Deno.test("App - .get/post/patch/put/delete/head/all() - lazy", async () => {
|
||||
const app = new App()
|
||||
.get("/", () => Promise.resolve(() => new Response("ok")))
|
||||
.post("/", () => Promise.resolve(() => new Response("ok")))
|
||||
.patch("/", () => Promise.resolve(() => new Response("ok")))
|
||||
.delete("/", () => Promise.resolve(() => new Response("ok")))
|
||||
.put("/", () => Promise.resolve(() => new Response("ok")))
|
||||
.head("/", () => Promise.resolve(() => new Response("ok")))
|
||||
.all("/", () => Promise.resolve(() => new Response("ok")));
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
let res = await server.get("/");
|
||||
expect(await res.text()).toEqual("ok");
|
||||
|
||||
res = await server.post("/");
|
||||
expect(await res.text()).toEqual("ok");
|
||||
|
||||
res = await server.put("/");
|
||||
expect(await res.text()).toEqual("ok");
|
||||
|
||||
res = await server.patch("/");
|
||||
expect(await res.text()).toEqual("ok");
|
||||
|
||||
res = await server.delete("/");
|
||||
expect(await res.text()).toEqual("ok");
|
||||
|
||||
res = await server.head("/");
|
||||
expect(await res.text()).toEqual("ok");
|
||||
});
|
||||
|
||||
Deno.test("App - .appWrapper()", async () => {
|
||||
const app = new App()
|
||||
.appWrapper(({ Component }) => (
|
||||
<>
|
||||
app/<Component />
|
||||
</>
|
||||
))
|
||||
.get("/", (ctx) => ctx.render(<>index</>));
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
const res = await server.get("/");
|
||||
expect(await res.text()).toContain("<body>app/index<");
|
||||
});
|
||||
|
||||
Deno.test.ignore("App - .layout()", async () => {
|
||||
const app = new App()
|
||||
.layout("/", ({ Component }) => (
|
||||
<>
|
||||
layout/<Component />
|
||||
</>
|
||||
))
|
||||
.layout("/foo", ({ Component }) => (
|
||||
<>
|
||||
foo/<Component />
|
||||
</>
|
||||
))
|
||||
.get("/foo", (ctx) => ctx.render(<>index</>));
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
// The `/foo` layout is not applied for GET `/foo`, is that correct?
|
||||
const res = await server.get("/foo");
|
||||
expect(await res.text()).toContain("<body>layout/foo/index<");
|
||||
});
|
||||
|
||||
Deno.test("App - .appWrapper() + .layout()", async () => {
|
||||
const app = new App()
|
||||
.appWrapper(({ Component }) => (
|
||||
<>
|
||||
app/<Component />
|
||||
</>
|
||||
))
|
||||
.layout("/", ({ Component }) => (
|
||||
<>
|
||||
layout/<Component />
|
||||
</>
|
||||
))
|
||||
.get("/", (ctx) => ctx.render(<>index</>));
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
const res = await server.get("/");
|
||||
expect(await res.text()).toContain("<body>app/layout/index<");
|
||||
});
|
||||
|
||||
Deno.test("App - ctx.render() without app wrapper or layout", async () => {
|
||||
const app = new App()
|
||||
.appWrapper(({ Component }) => (
|
||||
<>
|
||||
app/<Component />
|
||||
</>
|
||||
))
|
||||
.layout("/", ({ Component }) => (
|
||||
<>
|
||||
layout/<Component />
|
||||
</>
|
||||
))
|
||||
.get("/", (ctx) =>
|
||||
ctx.render(<>index</>, undefined, {
|
||||
skipAppWrapper: true,
|
||||
skipInheritedLayouts: true,
|
||||
}));
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
const res = await server.get("/");
|
||||
expect(await res.text()).toContain("<body>index<");
|
||||
});
|
||||
@@ -0,0 +1,110 @@
|
||||
import * as path from "@std/path";
|
||||
import type { Command } from "./commands.ts";
|
||||
import { fsItemsToCommands, type FsRouteFile } from "./fs_routes.ts";
|
||||
import type { ServerIslandRegistry } from "./context.ts";
|
||||
import type { AnyComponent } from "preact";
|
||||
import { UniqueNamer } from "./utils.ts";
|
||||
import { setBuildId } from "@fresh/build-id";
|
||||
|
||||
export interface FileSnapshot {
|
||||
name: string;
|
||||
filePath: string;
|
||||
hash: string | null;
|
||||
contentType: string;
|
||||
}
|
||||
|
||||
export interface BuildSnapshot<State> {
|
||||
version: string;
|
||||
clientEntry: string;
|
||||
fsRoutes: FsRouteFile<State>[];
|
||||
staticFiles: Map<string, FileSnapshot>;
|
||||
islands: ServerIslandRegistry;
|
||||
}
|
||||
|
||||
export interface StaticFile {
|
||||
hash: string | null;
|
||||
size: number;
|
||||
contentType: string;
|
||||
readable: ReadableStream<Uint8Array> | Uint8Array;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export interface BuildCache<State = any> {
|
||||
root: string;
|
||||
islandRegistry: ServerIslandRegistry;
|
||||
clientEntry: string;
|
||||
features: {
|
||||
errorOverlay: boolean;
|
||||
};
|
||||
getFsRoutes(): Command<State>[];
|
||||
readFile(pathname: string): Promise<StaticFile | null>;
|
||||
}
|
||||
|
||||
export class ProdBuildCache<State> implements BuildCache<State> {
|
||||
#snapshot: BuildSnapshot<State>;
|
||||
islandRegistry: ServerIslandRegistry;
|
||||
clientEntry: string;
|
||||
features = { errorOverlay: false };
|
||||
|
||||
constructor(public root: string, snapshot: BuildSnapshot<State>) {
|
||||
setBuildId(snapshot.version);
|
||||
this.#snapshot = snapshot;
|
||||
this.islandRegistry = snapshot.islands;
|
||||
this.clientEntry = snapshot.clientEntry;
|
||||
}
|
||||
|
||||
getFsRoutes(): Command<State>[] {
|
||||
return fsItemsToCommands(this.#snapshot.fsRoutes);
|
||||
}
|
||||
|
||||
async readFile(pathname: string): Promise<StaticFile | null> {
|
||||
const { staticFiles } = this.#snapshot;
|
||||
|
||||
const info = staticFiles.get(pathname);
|
||||
if (info === undefined) return null;
|
||||
|
||||
const filePath = path.isAbsolute(info.filePath)
|
||||
? info.filePath
|
||||
: path.join(this.root, info.filePath);
|
||||
|
||||
const [stat, file] = await Promise.all([
|
||||
Deno.stat(filePath),
|
||||
Deno.open(filePath),
|
||||
]);
|
||||
|
||||
return {
|
||||
hash: info.hash,
|
||||
contentType: info.contentType,
|
||||
size: stat.size,
|
||||
readable: file.readable,
|
||||
close: () => file.close(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export class IslandPreparer {
|
||||
#namer = new UniqueNamer();
|
||||
|
||||
prepare(
|
||||
registry: ServerIslandRegistry,
|
||||
mod: Record<string, unknown>,
|
||||
chunkName: string,
|
||||
modName: string,
|
||||
) {
|
||||
for (const [name, value] of Object.entries(mod)) {
|
||||
if (typeof value !== "function") continue;
|
||||
|
||||
const islandName = name === "default" ? modName : name;
|
||||
const uniqueName = this.#namer.getUniqueName(islandName);
|
||||
|
||||
const fn = value as AnyComponent;
|
||||
registry.set(fn, {
|
||||
exportName: name,
|
||||
file: chunkName,
|
||||
fn,
|
||||
name: uniqueName,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
import { HttpError } from "./error.ts";
|
||||
import { isHandlerByMethod, type PageResponse } from "./handlers.ts";
|
||||
import type { MaybeLazyMiddleware, Middleware } from "./middlewares/mod.ts";
|
||||
import { mergePath, type Method, type Router, toRoutePath } from "./router.ts";
|
||||
import {
|
||||
getOrCreateSegment,
|
||||
newSegment,
|
||||
renderRoute,
|
||||
type RouteComponent,
|
||||
type Segment,
|
||||
segmentToMiddlewares,
|
||||
} from "./segments.ts";
|
||||
import type { LayoutConfig, MaybeLazy, Route, RouteConfig } from "./types.ts";
|
||||
import { isLazy } from "./utils.ts";
|
||||
|
||||
export const DEFAULT_NOT_FOUND = (): Promise<Response> => {
|
||||
throw new HttpError(404);
|
||||
};
|
||||
export const DEFAULT_NOT_ALLOWED_METHOD = (): Promise<Response> => {
|
||||
throw new HttpError(405);
|
||||
};
|
||||
|
||||
const DEFAULT_RENDER = <State>(): Promise<PageResponse<State>> =>
|
||||
// deno-lint-ignore no-explicit-any
|
||||
Promise.resolve({ data: {} as any });
|
||||
|
||||
function ensureHandler<State>(route: Route<State>) {
|
||||
if (route.handler === undefined) {
|
||||
route.handler = route.component !== undefined
|
||||
? DEFAULT_RENDER
|
||||
: DEFAULT_NOT_FOUND;
|
||||
} else if (isHandlerByMethod(route.handler)) {
|
||||
if (route.component !== undefined && !route.handler.GET) {
|
||||
route.handler.GET = DEFAULT_RENDER;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const enum CommandType {
|
||||
Middleware = "middleware",
|
||||
Layout = "layout",
|
||||
App = "app",
|
||||
Route = "route",
|
||||
Error = "error",
|
||||
NotFound = "notFound",
|
||||
Handler = "handler",
|
||||
FsRoute = "fsRoute",
|
||||
}
|
||||
|
||||
export interface ErrorCmd<State> {
|
||||
type: CommandType.Error;
|
||||
pattern: string;
|
||||
item: Route<State>;
|
||||
includeLastSegment: boolean;
|
||||
}
|
||||
export function newErrorCmd<State>(
|
||||
pattern: string,
|
||||
routeOrMiddleware: Route<State> | Middleware<State>,
|
||||
includeLastSegment: boolean,
|
||||
): ErrorCmd<State> {
|
||||
const route = typeof routeOrMiddleware === "function"
|
||||
? { handler: routeOrMiddleware }
|
||||
: routeOrMiddleware;
|
||||
ensureHandler(route);
|
||||
|
||||
return { type: CommandType.Error, pattern, item: route, includeLastSegment };
|
||||
}
|
||||
|
||||
export interface AppCommand<State> {
|
||||
type: CommandType.App;
|
||||
component: RouteComponent<State>;
|
||||
}
|
||||
export function newAppCmd<State>(
|
||||
component: RouteComponent<State>,
|
||||
): AppCommand<State> {
|
||||
return { type: CommandType.App, component };
|
||||
}
|
||||
|
||||
export interface LayoutCommand<State> {
|
||||
type: CommandType.Layout;
|
||||
pattern: string;
|
||||
component: RouteComponent<State>;
|
||||
config?: LayoutConfig;
|
||||
includeLastSegment: boolean;
|
||||
}
|
||||
export function newLayoutCmd<State>(
|
||||
pattern: string,
|
||||
component: RouteComponent<State>,
|
||||
config: LayoutConfig | undefined,
|
||||
includeLastSegment: boolean,
|
||||
): LayoutCommand<State> {
|
||||
return {
|
||||
type: CommandType.Layout,
|
||||
pattern,
|
||||
component,
|
||||
config,
|
||||
includeLastSegment,
|
||||
};
|
||||
}
|
||||
|
||||
export interface MiddlewareCmd<State> {
|
||||
type: CommandType.Middleware;
|
||||
pattern: string;
|
||||
fns: MaybeLazyMiddleware<State>[];
|
||||
includeLastSegment: boolean;
|
||||
}
|
||||
export function newMiddlewareCmd<State>(
|
||||
pattern: string,
|
||||
fns: MaybeLazyMiddleware<State>[],
|
||||
includeLastSegment: boolean,
|
||||
): MiddlewareCmd<State> {
|
||||
return { type: CommandType.Middleware, pattern, fns, includeLastSegment };
|
||||
}
|
||||
|
||||
export interface NotFoundCmd<State> {
|
||||
type: CommandType.NotFound;
|
||||
fn: Middleware<State>;
|
||||
}
|
||||
export function newNotFoundCmd<State>(
|
||||
routeOrMiddleware: Route<State> | Middleware<State>,
|
||||
): NotFoundCmd<State> {
|
||||
const route = typeof routeOrMiddleware === "function"
|
||||
? { handler: routeOrMiddleware }
|
||||
: routeOrMiddleware;
|
||||
ensureHandler(route);
|
||||
|
||||
return { type: CommandType.NotFound, fn: (ctx) => renderRoute(ctx, route) };
|
||||
}
|
||||
|
||||
export interface RouteCommand<State> {
|
||||
type: CommandType.Route;
|
||||
pattern: string;
|
||||
route: MaybeLazy<Route<State>>;
|
||||
config: RouteConfig | undefined;
|
||||
includeLastSegment: boolean;
|
||||
}
|
||||
export function newRouteCmd<State>(
|
||||
pattern: string,
|
||||
route: MaybeLazy<Route<State>>,
|
||||
config: RouteConfig | undefined,
|
||||
includeLastSegment: boolean,
|
||||
): RouteCommand<State> {
|
||||
let normalized;
|
||||
if (isLazy(route)) {
|
||||
normalized = async () => {
|
||||
const result = await route();
|
||||
ensureHandler(result);
|
||||
return result;
|
||||
};
|
||||
} else {
|
||||
ensureHandler(route);
|
||||
normalized = route;
|
||||
}
|
||||
|
||||
return {
|
||||
type: CommandType.Route,
|
||||
pattern,
|
||||
route: normalized,
|
||||
config,
|
||||
includeLastSegment,
|
||||
};
|
||||
}
|
||||
|
||||
export interface HandlerCommand<State> {
|
||||
type: CommandType.Handler;
|
||||
pattern: string;
|
||||
method: Method | "ALL";
|
||||
fns: MaybeLazy<Middleware<State>>[];
|
||||
includeLastSegment: boolean;
|
||||
}
|
||||
export function newHandlerCmd<State>(
|
||||
method: Method | "ALL",
|
||||
pattern: string,
|
||||
fns: MaybeLazy<Middleware<State>>[],
|
||||
includeLastSegment: boolean,
|
||||
): HandlerCommand<State> {
|
||||
return {
|
||||
type: CommandType.Handler,
|
||||
pattern,
|
||||
method,
|
||||
fns,
|
||||
includeLastSegment,
|
||||
};
|
||||
}
|
||||
|
||||
export interface FsRouteCommand<State> {
|
||||
type: CommandType.FsRoute;
|
||||
pattern: string;
|
||||
getItems: () => Command<State>[];
|
||||
includeLastSegment: boolean;
|
||||
}
|
||||
|
||||
export type Command<State> =
|
||||
| ErrorCmd<State>
|
||||
| AppCommand<State>
|
||||
| LayoutCommand<State>
|
||||
| NotFoundCmd<State>
|
||||
| MiddlewareCmd<State>
|
||||
| RouteCommand<State>
|
||||
| HandlerCommand<State>
|
||||
| FsRouteCommand<State>;
|
||||
|
||||
export function applyCommands<State>(
|
||||
router: Router<MaybeLazyMiddleware<State>>,
|
||||
commands: Command<State>[],
|
||||
basePath: string,
|
||||
): { rootMiddlewares: MaybeLazyMiddleware<State>[] } {
|
||||
const root = newSegment<State>("", null);
|
||||
|
||||
applyCommandsInner(root, router, commands, basePath);
|
||||
|
||||
return { rootMiddlewares: segmentToMiddlewares(root) };
|
||||
}
|
||||
|
||||
function applyCommandsInner<State>(
|
||||
root: Segment<State>,
|
||||
router: Router<MaybeLazyMiddleware<State>>,
|
||||
commands: Command<State>[],
|
||||
basePath: string,
|
||||
) {
|
||||
for (let i = 0; i < commands.length; i++) {
|
||||
const cmd = commands[i];
|
||||
|
||||
switch (cmd.type) {
|
||||
case CommandType.Middleware: {
|
||||
const segment = getOrCreateSegment(
|
||||
root,
|
||||
cmd.pattern,
|
||||
cmd.includeLastSegment,
|
||||
);
|
||||
segment.middlewares.push(...cmd.fns);
|
||||
break;
|
||||
}
|
||||
case CommandType.NotFound: {
|
||||
root.notFound = cmd.fn;
|
||||
break;
|
||||
}
|
||||
case CommandType.Error: {
|
||||
const segment = getOrCreateSegment(
|
||||
root,
|
||||
cmd.pattern,
|
||||
cmd.includeLastSegment,
|
||||
);
|
||||
segment.errorRoute = cmd.item;
|
||||
break;
|
||||
}
|
||||
case CommandType.App: {
|
||||
root.app = cmd.component;
|
||||
break;
|
||||
}
|
||||
case CommandType.Layout: {
|
||||
const segment = getOrCreateSegment(
|
||||
root,
|
||||
cmd.pattern,
|
||||
cmd.includeLastSegment,
|
||||
);
|
||||
segment.layout = {
|
||||
component: cmd.component,
|
||||
config: cmd.config ?? null,
|
||||
};
|
||||
break;
|
||||
}
|
||||
case CommandType.Route: {
|
||||
const { pattern, route, config } = cmd;
|
||||
const segment = getOrCreateSegment(
|
||||
root,
|
||||
pattern,
|
||||
cmd.includeLastSegment,
|
||||
);
|
||||
const fns = segmentToMiddlewares(segment);
|
||||
|
||||
if (isLazy(route)) {
|
||||
const routePath = mergePath(
|
||||
basePath,
|
||||
config?.routeOverride ?? pattern,
|
||||
);
|
||||
|
||||
let def: Route<State>;
|
||||
fns.push(async (ctx) => {
|
||||
if (def === undefined) {
|
||||
def = await route();
|
||||
}
|
||||
|
||||
return renderRoute(ctx, def);
|
||||
});
|
||||
|
||||
if (config === undefined || config.methods === "ALL") {
|
||||
router.add("GET", routePath, fns);
|
||||
router.add("DELETE", routePath, fns);
|
||||
router.add("HEAD", routePath, fns);
|
||||
router.add("OPTIONS", routePath, fns);
|
||||
router.add("PATCH", routePath, fns);
|
||||
router.add("POST", routePath, fns);
|
||||
router.add("PUT", routePath, fns);
|
||||
} else if (Array.isArray(config.methods)) {
|
||||
for (let i = 0; i < config.methods.length; i++) {
|
||||
const method = config.methods[i];
|
||||
router.add(method, routePath, fns);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
fns.push((ctx) => renderRoute(ctx, route));
|
||||
|
||||
const routePath = toRoutePath(mergePath(
|
||||
basePath,
|
||||
route.config?.routeOverride ?? pattern,
|
||||
));
|
||||
|
||||
if (typeof route.handler === "function") {
|
||||
router.add("GET", routePath, fns);
|
||||
router.add("DELETE", routePath, fns);
|
||||
router.add("HEAD", routePath, fns);
|
||||
router.add("OPTIONS", routePath, fns);
|
||||
router.add("PATCH", routePath, fns);
|
||||
router.add("POST", routePath, fns);
|
||||
router.add("PUT", routePath, fns);
|
||||
} else if (isHandlerByMethod(route.handler!)) {
|
||||
for (const method of Object.keys(route.handler)) {
|
||||
router.add(method as Method, routePath, fns);
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case CommandType.Handler: {
|
||||
const { pattern, fns, method } = cmd;
|
||||
const segment = getOrCreateSegment(
|
||||
root,
|
||||
pattern,
|
||||
cmd.includeLastSegment,
|
||||
);
|
||||
const result = segmentToMiddlewares(segment);
|
||||
|
||||
result.push(...fns);
|
||||
|
||||
const resPath = toRoutePath(mergePath(basePath, pattern));
|
||||
if (method === "ALL") {
|
||||
router.add("GET", resPath, result);
|
||||
router.add("DELETE", resPath, result);
|
||||
router.add("HEAD", resPath, result);
|
||||
router.add("OPTIONS", resPath, result);
|
||||
router.add("PATCH", resPath, result);
|
||||
router.add("POST", resPath, result);
|
||||
router.add("PUT", resPath, result);
|
||||
} else {
|
||||
router.add(method, resPath, result);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case CommandType.FsRoute: {
|
||||
const items = cmd.getItems();
|
||||
applyCommandsInner(root, router, items, basePath);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw new Error(`Unknown command: ${JSON.stringify(cmd)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { ComponentChildren } from "preact";
|
||||
import type { Context } from "./context.ts";
|
||||
import type { PageProps } from "./render.ts";
|
||||
import type { HandlerFn, RouteHandler } from "./handlers.ts";
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode PageProps} instead.
|
||||
*/
|
||||
export type AppProps<_Data = unknown, T = unknown> = Context<T>;
|
||||
/**
|
||||
* @deprecated Use {@linkcode PageProps} instead.
|
||||
*/
|
||||
export type LayoutProps<_Data = unknown, T = unknown> = Context<T>;
|
||||
/**
|
||||
* @deprecated Use {@linkcode PageProps} instead.
|
||||
*/
|
||||
export type UnknownPageProps<_Data = unknown, T = unknown> = Context<T>;
|
||||
/**
|
||||
* @deprecated Use {@linkcode PageProps} instead.
|
||||
*/
|
||||
export type ErrorPageProps<_Data = unknown, T = unknown> = Context<T>;
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode FreshContext} instead.
|
||||
*/
|
||||
export type RouteContext<_T = never, S = Record<string, unknown>> = Context<S>;
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode RouteHandler} instead.
|
||||
*/
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export type Handlers<T = any, State = Record<string, unknown>> = RouteHandler<
|
||||
T,
|
||||
State
|
||||
>;
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode HandlerFn} instead.
|
||||
*/
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export type Handler<T = any, State = Record<string, unknown>> = HandlerFn<
|
||||
T,
|
||||
State
|
||||
>;
|
||||
|
||||
function defineFn<State>(
|
||||
fn: (
|
||||
ctx: PageProps<State>,
|
||||
) =>
|
||||
| ComponentChildren
|
||||
| Response
|
||||
| Promise<Response | ComponentChildren>,
|
||||
): (
|
||||
ctx: PageProps<State>,
|
||||
) =>
|
||||
| ComponentChildren
|
||||
| Response
|
||||
| Promise<Response | ComponentChildren> {
|
||||
return fn;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode [./mod.ts].Define.page|define.page} instead.
|
||||
*/
|
||||
export const defineApp = defineFn;
|
||||
/**
|
||||
* @deprecated Use {@linkcode [./mod.ts].Define.page|define.page} instead.
|
||||
*/
|
||||
export const defineRoute = defineFn;
|
||||
/**
|
||||
* @deprecated Use {@linkcode [./mod.ts].Define.page|define.page} instead.
|
||||
*/
|
||||
export const defineLayout = defineFn;
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { PageProps } from "./render.ts";
|
||||
import { assertType, type IsExact } from "@std/testing/types";
|
||||
import { expect } from "@std/expect";
|
||||
import { type defineApp, type defineLayout, defineRoute } from "./compat.ts";
|
||||
|
||||
Deno.test("compat - defineFn works", () => {
|
||||
const ctx = {} as PageProps<unknown>;
|
||||
expect(defineRoute(() => new Response("test"))(ctx)).toBeInstanceOf(Response);
|
||||
expect(defineRoute(() => <span>test</span>)(ctx)).toBeInstanceOf(Object);
|
||||
expect(defineRoute(() => null)(ctx)).toEqual(null);
|
||||
});
|
||||
|
||||
Deno.test("compat - functions equivalent", () => {
|
||||
assertType<IsExact<typeof defineApp, typeof defineRoute>>(true);
|
||||
assertType<IsExact<typeof defineRoute, typeof defineLayout>>(true);
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
import * as path from "@std/path";
|
||||
|
||||
export interface FreshConfig {
|
||||
/**
|
||||
* Serve fresh from a base path instead of from the root.
|
||||
* "/foo/bar" -> http://localhost:8000/foo/bar
|
||||
* @default undefined
|
||||
*/
|
||||
basePath?: string;
|
||||
/**
|
||||
* The mode Fresh can run in.
|
||||
*/
|
||||
mode?: "development" | "production";
|
||||
}
|
||||
|
||||
/**
|
||||
* The final resolved Fresh configuration where fields the user didn't specify are set to the default values.
|
||||
*/
|
||||
export interface ResolvedFreshConfig {
|
||||
root: string;
|
||||
/**
|
||||
* Serve fresh from a base path instead of from the root.
|
||||
* "/foo/bar" -> http://localhost:8000/foo/bar
|
||||
*/
|
||||
basePath: string;
|
||||
/**
|
||||
* The mode Fresh can run in.
|
||||
*/
|
||||
mode: "development" | "production";
|
||||
}
|
||||
|
||||
export function parseDirPath(
|
||||
dirPath: string,
|
||||
root: string,
|
||||
): string {
|
||||
if (dirPath.startsWith("file://")) {
|
||||
dirPath = path.fromFileUrl(dirPath);
|
||||
} else if (!path.isAbsolute(dirPath)) {
|
||||
dirPath = path.join(root, dirPath);
|
||||
}
|
||||
|
||||
if (Deno.build.os === "windows") {
|
||||
dirPath = dirPath.replaceAll("\\", "/");
|
||||
}
|
||||
|
||||
return dirPath;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { expect } from "@std/expect";
|
||||
import { parseDirPath } from "./config.ts";
|
||||
|
||||
Deno.test("parseDirPath", () => {
|
||||
const cwd = Deno.cwd().replaceAll("\\", "/");
|
||||
|
||||
// File paths
|
||||
expect(parseDirPath("file:///foo/bar", cwd)).toEqual("/foo/bar");
|
||||
if (Deno.build.os === "windows") {
|
||||
expect(parseDirPath("file:///C:/foo/bar", cwd)).toEqual("C:/foo/bar");
|
||||
}
|
||||
|
||||
// Relative paths
|
||||
expect(parseDirPath("./foo/bar", cwd)).toEqual(`${cwd}/foo/bar`);
|
||||
|
||||
// Absolute paths
|
||||
expect(parseDirPath("/foo/bar", cwd)).toEqual("/foo/bar");
|
||||
if (Deno.build.os === "windows") {
|
||||
expect(parseDirPath("C:/foo/bar", cwd)).toEqual("C:/foo/bar");
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
export const INTERNAL_PREFIX = "/_frsh";
|
||||
export const DEV_ERROR_OVERLAY_URL = `${INTERNAL_PREFIX}/error_overlay`;
|
||||
export const ALIVE_URL = `${INTERNAL_PREFIX}/alive`;
|
||||
export const PARTIAL_SEARCH_PARAM = "fresh-partial";
|
||||
|
||||
export const SECOND = 1000;
|
||||
export const MINUTE = SECOND * 60;
|
||||
export const HOUR = MINUTE * 60;
|
||||
export const DAY = HOUR * 24;
|
||||
export const WEEK = DAY * 7;
|
||||
@@ -0,0 +1,298 @@
|
||||
import {
|
||||
type AnyComponent,
|
||||
type ComponentType,
|
||||
Fragment,
|
||||
type FunctionComponent,
|
||||
h,
|
||||
isValidElement,
|
||||
type VNode,
|
||||
} from "preact";
|
||||
import { SpanStatusCode } from "@opentelemetry/api";
|
||||
import type { ResolvedFreshConfig } from "./config.ts";
|
||||
import type { BuildCache } from "./build_cache.ts";
|
||||
import type { LayoutConfig } from "./types.ts";
|
||||
import { RenderState, setRenderState } from "./runtime/server/preact_hooks.tsx";
|
||||
import { PARTIAL_SEARCH_PARAM } from "./constants.ts";
|
||||
import { tracer } from "./otel.ts";
|
||||
import {
|
||||
type ComponentDef,
|
||||
isAsyncAnyComponent,
|
||||
type PageProps,
|
||||
preactRender,
|
||||
renderAsyncAnyComponent,
|
||||
renderRouteComponent,
|
||||
} from "./render.ts";
|
||||
|
||||
export interface Island {
|
||||
file: string;
|
||||
name: string;
|
||||
exportName: string;
|
||||
fn: ComponentType;
|
||||
}
|
||||
|
||||
export type ServerIslandRegistry = Map<ComponentType, Island>;
|
||||
|
||||
export const internals: unique symbol = Symbol("fresh_internal");
|
||||
|
||||
export interface UiTree<Data, State> {
|
||||
app: AnyComponent<PageProps<Data, State>> | null;
|
||||
layouts: ComponentDef<Data, State>[];
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode Context} instead.
|
||||
*/
|
||||
export type FreshContext<State = unknown> = Context<State>;
|
||||
|
||||
export let getBuildCache: <T>(ctx: Context<T>) => BuildCache<T>;
|
||||
export let getInternals: <T>(ctx: Context<T>) => UiTree<unknown, T>;
|
||||
|
||||
/**
|
||||
* The context passed to every middleware. It is unique for every request.
|
||||
*/
|
||||
export class Context<State> {
|
||||
#internal: UiTree<unknown, State> = {
|
||||
app: null,
|
||||
layouts: [],
|
||||
};
|
||||
/** Reference to the resolved Fresh configuration */
|
||||
readonly config: ResolvedFreshConfig;
|
||||
/**
|
||||
* The request url parsed into an `URL` instance. This is typically used
|
||||
* to apply logic based on the pathname of the incoming url or when
|
||||
* certain search parameters are set.
|
||||
*/
|
||||
readonly url: URL;
|
||||
/** The original incoming {@linkcode Request} object. */
|
||||
readonly req: Request;
|
||||
/** The matched route pattern. */
|
||||
readonly route: string | null;
|
||||
/** The url parameters of the matched route pattern. */
|
||||
readonly params: Record<string, string>;
|
||||
/** State object that is shared with all middlewares. */
|
||||
readonly state: State = {} as State;
|
||||
data: unknown = undefined;
|
||||
/** Error value if an error was caught (Default: null) */
|
||||
error: unknown | null = null;
|
||||
readonly info: Deno.ServeHandlerInfo | Deno.ServeHandlerInfo;
|
||||
/**
|
||||
* Whether the current Request is a partial request.
|
||||
*
|
||||
* Partials in Fresh will append the query parameter
|
||||
* {@linkcode PARTIAL_SEARCH_PARAM} to the URL. This property can
|
||||
* be used to determine if only `<Partial>`'s need to be rendered.
|
||||
*/
|
||||
readonly isPartial: boolean;
|
||||
|
||||
/**
|
||||
* Call the next middleware.
|
||||
* ```ts
|
||||
* const myMiddleware: Middleware = (ctx) => {
|
||||
* // do something
|
||||
*
|
||||
* // Call the next middleware
|
||||
* return ctx.next();
|
||||
* }
|
||||
*
|
||||
* const myMiddleware2: Middleware = async (ctx) => {
|
||||
* // do something before the next middleware
|
||||
* doSomething()
|
||||
*
|
||||
* const res = await ctx.next();
|
||||
*
|
||||
* // do something after the middleware
|
||||
* doSomethingAfter()
|
||||
*
|
||||
* // Return the `Response`
|
||||
* return res
|
||||
* }
|
||||
*/
|
||||
next: () => Promise<Response>;
|
||||
|
||||
#buildCache: BuildCache<State>;
|
||||
|
||||
Component!: FunctionComponent;
|
||||
|
||||
static {
|
||||
// deno-lint-ignore no-explicit-any
|
||||
getInternals = <T>(ctx: Context<T>) => ctx.#internal as any;
|
||||
getBuildCache = <T>(ctx: Context<T>) => ctx.#buildCache;
|
||||
}
|
||||
|
||||
constructor(
|
||||
req: Request,
|
||||
url: URL,
|
||||
info: Deno.ServeHandlerInfo,
|
||||
route: string | null,
|
||||
params: Record<string, string>,
|
||||
config: ResolvedFreshConfig,
|
||||
next: () => Promise<Response>,
|
||||
buildCache: BuildCache<State>,
|
||||
) {
|
||||
this.url = url;
|
||||
this.req = req;
|
||||
this.info = info;
|
||||
this.params = params;
|
||||
this.route = route;
|
||||
this.config = config;
|
||||
this.isPartial = url.searchParams.has(PARTIAL_SEARCH_PARAM);
|
||||
this.next = next;
|
||||
this.#buildCache = buildCache;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a redirect response to the specified path. This is the
|
||||
* preferred way to do redirects in Fresh.
|
||||
*
|
||||
* ```ts
|
||||
* ctx.redirect("/foo/bar") // redirect user to "<yoursite>/foo/bar"
|
||||
*
|
||||
* // Disallows protocol relative URLs for improved security. This
|
||||
* // redirects the user to `<yoursite>/evil.com` which is safe,
|
||||
* // instead of redirecting to `http://evil.com`.
|
||||
* ctx.redirect("//evil.com/");
|
||||
* ```
|
||||
*/
|
||||
redirect(pathOrUrl: string, status = 302): Response {
|
||||
let location = pathOrUrl;
|
||||
|
||||
// Disallow protocol relative URLs
|
||||
if (pathOrUrl !== "/" && pathOrUrl.startsWith("/")) {
|
||||
let idx = pathOrUrl.indexOf("?");
|
||||
if (idx === -1) {
|
||||
idx = pathOrUrl.indexOf("#");
|
||||
}
|
||||
|
||||
const pathname = idx > -1 ? pathOrUrl.slice(0, idx) : pathOrUrl;
|
||||
const search = idx > -1 ? pathOrUrl.slice(idx) : "";
|
||||
|
||||
// Remove double slashes to prevent open redirect vulnerability.
|
||||
location = `${pathname.replaceAll(/\/+/g, "/")}${search}`;
|
||||
}
|
||||
|
||||
return new Response(null, {
|
||||
status,
|
||||
headers: {
|
||||
location,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Render JSX and return an HTML `Response` instance.
|
||||
* ```tsx
|
||||
* ctx.render(<h1>hello world</h1>);
|
||||
* ```
|
||||
*/
|
||||
async render(
|
||||
// deno-lint-ignore no-explicit-any
|
||||
vnode: VNode<any> | null,
|
||||
init: ResponseInit | undefined = {},
|
||||
config: LayoutConfig = {},
|
||||
): Promise<Response> {
|
||||
if (arguments.length === 0) {
|
||||
throw new Error(`No arguments passed to: ctx.render()`);
|
||||
} else if (vnode !== null && !isValidElement(vnode)) {
|
||||
throw new Error(`Non-JSX element passed to: ctx.render()`);
|
||||
}
|
||||
|
||||
const defs = config.skipInheritedLayouts ? [] : this.#internal.layouts;
|
||||
const appDef = config.skipAppWrapper ? null : this.#internal.app;
|
||||
const props = this as Context<State>;
|
||||
|
||||
// Compose final vnode tree
|
||||
for (let i = defs.length - 1; i >= 0; i--) {
|
||||
const child = vnode;
|
||||
props.Component = () => child;
|
||||
|
||||
const def = defs[i];
|
||||
|
||||
const result = await renderRouteComponent(this, def, () => child);
|
||||
if (result instanceof Response) {
|
||||
return result;
|
||||
}
|
||||
|
||||
vnode = result;
|
||||
}
|
||||
|
||||
if (isAsyncAnyComponent(appDef)) {
|
||||
const child = vnode;
|
||||
props.Component = () => child;
|
||||
const result = await renderAsyncAnyComponent(appDef, props);
|
||||
if (result instanceof Response) {
|
||||
return result;
|
||||
}
|
||||
|
||||
vnode = result;
|
||||
} else if (appDef !== null) {
|
||||
const child = vnode;
|
||||
vnode = h(appDef, {
|
||||
Component: () => child,
|
||||
config: this.config,
|
||||
data: null,
|
||||
error: this.error,
|
||||
info: this.info,
|
||||
isPartial: this.isPartial,
|
||||
params: this.params,
|
||||
req: this.req,
|
||||
state: this.state,
|
||||
url: this.url,
|
||||
});
|
||||
}
|
||||
|
||||
const headers = init.headers !== undefined
|
||||
? init.headers instanceof Headers
|
||||
? init.headers
|
||||
: new Headers(init.headers)
|
||||
: new Headers();
|
||||
|
||||
headers.set("Content-Type", "text/html; charset=utf-8");
|
||||
const responseInit: ResponseInit = {
|
||||
status: init.status ?? 200,
|
||||
headers,
|
||||
statusText: init.statusText,
|
||||
};
|
||||
|
||||
let partialId = "";
|
||||
if (this.url.searchParams.has(PARTIAL_SEARCH_PARAM)) {
|
||||
partialId = crypto.randomUUID();
|
||||
headers.set("X-Fresh-Id", partialId);
|
||||
}
|
||||
|
||||
const html = tracer.startActiveSpan("render", (span) => {
|
||||
span.setAttribute("fresh.span_type", "render");
|
||||
const state = new RenderState(
|
||||
this,
|
||||
this.#buildCache,
|
||||
partialId,
|
||||
);
|
||||
|
||||
try {
|
||||
setRenderState(state);
|
||||
|
||||
return preactRender(
|
||||
vnode ?? h(Fragment, null),
|
||||
this,
|
||||
state,
|
||||
headers,
|
||||
);
|
||||
} catch (err) {
|
||||
if (err instanceof Error) {
|
||||
span.recordException(err);
|
||||
} else {
|
||||
span.setStatus({
|
||||
code: SpanStatusCode.ERROR,
|
||||
message: String(err),
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
} finally {
|
||||
state.clear();
|
||||
setRenderState(null);
|
||||
|
||||
span.end();
|
||||
}
|
||||
});
|
||||
return new Response(html, responseInit);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import { expect } from "@std/expect";
|
||||
import { Context } from "./context.ts";
|
||||
import { App } from "fresh";
|
||||
import { asset } from "fresh/runtime";
|
||||
import { FakeServer } from "./test_utils.ts";
|
||||
import { BUILD_ID } from "@fresh/build-id";
|
||||
import { parseHtml } from "../tests/test_utils.tsx";
|
||||
|
||||
Deno.test("FreshReqContext.prototype.redirect", () => {
|
||||
let res = Context.prototype.redirect("/");
|
||||
expect(res.status).toEqual(302);
|
||||
expect(res.headers.get("Location")).toEqual("/");
|
||||
|
||||
res = Context.prototype.redirect("//evil.com");
|
||||
expect(res.status).toEqual(302);
|
||||
expect(res.headers.get("Location")).toEqual("/evil.com");
|
||||
|
||||
res = Context.prototype.redirect("//evil.com/foo//bar");
|
||||
expect(res.status).toEqual(302);
|
||||
expect(res.headers.get("Location")).toEqual("/evil.com/foo/bar");
|
||||
|
||||
res = Context.prototype.redirect("https://deno.com");
|
||||
expect(res.status).toEqual(302);
|
||||
expect(res.headers.get("Location")).toEqual("https://deno.com");
|
||||
|
||||
res = Context.prototype.redirect("/", 307);
|
||||
expect(res.status).toEqual(307);
|
||||
});
|
||||
|
||||
Deno.test("render asset()", async () => {
|
||||
const app = new App()
|
||||
.get("/", (ctx) =>
|
||||
ctx.render(
|
||||
<>
|
||||
<p class="raw">{asset("/foo")}</p>
|
||||
<img src="/foo" srcset="/foo-bar" />
|
||||
<source src="/foo" />
|
||||
</>,
|
||||
));
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
const res = await server.get("/");
|
||||
const doc = parseHtml(await res.text());
|
||||
|
||||
expect(doc.querySelector(".raw")!.textContent).toContain(BUILD_ID);
|
||||
expect(doc.querySelector("img")!.src).toContain(BUILD_ID);
|
||||
expect(doc.querySelector("img")!.srcset).toContain(BUILD_ID);
|
||||
expect(doc.querySelector("source")!.src).toContain(BUILD_ID);
|
||||
});
|
||||
|
||||
Deno.test("ctx.render - throw with no arguments", async () => {
|
||||
const app = new App()
|
||||
// deno-lint-ignore no-explicit-any
|
||||
.get("/", (ctx) => (ctx as any).render());
|
||||
const server = new FakeServer(app.handler());
|
||||
const res = await server.get("/");
|
||||
|
||||
await res.body?.cancel();
|
||||
expect(res.status).toEqual(500);
|
||||
});
|
||||
|
||||
Deno.test("ctx.render - throw with invalid first arg", async () => {
|
||||
const app = new App()
|
||||
// deno-lint-ignore no-explicit-any
|
||||
.get("/", (ctx) => (ctx as any).render({}));
|
||||
const server = new FakeServer(app.handler());
|
||||
const res = await server.get("/");
|
||||
|
||||
await res.body?.cancel();
|
||||
expect(res.status).toEqual(500);
|
||||
});
|
||||
|
||||
Deno.test("ctx.isPartial - should indicate whether request is partial or not", async () => {
|
||||
const isPartials: boolean[] = [];
|
||||
const app = new App()
|
||||
.get("/", (ctx) => {
|
||||
isPartials.push(ctx.isPartial);
|
||||
return new Response("ok");
|
||||
});
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
await server.get("/");
|
||||
await server.get("/?fresh-partial");
|
||||
|
||||
expect(isPartials).toEqual([false, true]);
|
||||
});
|
||||
|
||||
Deno.test("ctx.route - should contain matched route", async () => {
|
||||
let route: string | null = null;
|
||||
const app = new App()
|
||||
.use((ctx) => {
|
||||
route = ctx.route;
|
||||
return ctx.next();
|
||||
})
|
||||
.get("/foo/bar", () => new Response("ok"))
|
||||
.get("/foo/:id", () => new Response("ok"));
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
await server.get("/invalid");
|
||||
expect(route).toEqual(null);
|
||||
|
||||
await server.get("/foo/bar");
|
||||
expect(route).toEqual("/foo/bar");
|
||||
|
||||
await server.get("/foo/123");
|
||||
expect(route).toEqual("/foo/:id");
|
||||
});
|
||||
@@ -0,0 +1,185 @@
|
||||
import type { AnyComponent } from "preact";
|
||||
import type { HandlerByMethod, HandlerFn, RouteHandler } from "./handlers.ts";
|
||||
import type { Middleware } from "./middlewares/mod.ts";
|
||||
import type { PageProps } from "./render.ts";
|
||||
|
||||
/**
|
||||
* A set of define functions that enable better type inference and code
|
||||
* completion when defining routes and middleware.
|
||||
*
|
||||
* To create a define object, call {@link createDefine}.
|
||||
*/
|
||||
export interface Define<State> {
|
||||
/**
|
||||
* Define a {@link RouteHandler} object. This function returns the passed
|
||||
* input as-is.
|
||||
*
|
||||
* You can use this function to help the TypeScript compiler infer the types
|
||||
* of your route handlers. For example:
|
||||
*
|
||||
* ```ts
|
||||
* import { define } from "../utils.ts";
|
||||
*
|
||||
* export const handler = define.handlers((ctx) => {
|
||||
* ctx.url; // ctx is inferred to be a Context object, so this is a URL
|
||||
* return new Response("Hello, world!");
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* This is particularly useful when combined with the {@link Define.page}
|
||||
* helper function, which can infer the data type from the handler function.
|
||||
* For more information, see {@link Define.page}.
|
||||
*
|
||||
* You can also pass an explicit type argument to ensure that all data
|
||||
* returned from the handler is of the correct type:
|
||||
*
|
||||
* ```ts
|
||||
* import { page } from "fresh";
|
||||
* import { define } from "../utils.ts";
|
||||
*
|
||||
* export const handler = define.handlers<{ slug: string }>({
|
||||
* async GET(ctx) {
|
||||
* const slug = ctx.params.slug; // slug is inferred to be a string
|
||||
* return page({ slug });
|
||||
* },
|
||||
*
|
||||
* // This method will cause a type error because the data object is missing
|
||||
* // the required `slug` property.
|
||||
* async POST(ctx) {
|
||||
* return page({ });
|
||||
* },
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @typeParam Data The type of data that the handler returns. This will be inferred from the handler methods if not provided.
|
||||
* @typeParam Handlers This will always be inferred from the input object. Do not manually specify this type.
|
||||
*/
|
||||
handlers<
|
||||
Data,
|
||||
Handlers extends RouteHandler<Data, State> = RouteHandler<Data, State>,
|
||||
>(handlers: Handlers): typeof handlers;
|
||||
|
||||
/**
|
||||
* Define a page component that will be rendered when a route handler returns
|
||||
* data. This function returns the passed input as-is.
|
||||
*
|
||||
* You can use this function to help the TypeScript compiler infer the types
|
||||
* of the data that your page component receives. For example:
|
||||
*
|
||||
* ```ts
|
||||
* import { define } from "../utils.ts";
|
||||
*
|
||||
* export default define.page((props) => {
|
||||
* const slug = props.params.slug; // Because props is inferred to be a Context object, slug is inferred to be a string
|
||||
* return <h1>{slug}</h1>;
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* This is particularly useful when combined with the {@link handlers}
|
||||
* helper function, in which case the data type will be inferred from the
|
||||
* return type of the handler method.
|
||||
*
|
||||
* ```ts
|
||||
* import { page } from "fresh";
|
||||
* import { define } from "../utils.ts";
|
||||
*
|
||||
* export const handler = define.handlers({
|
||||
* async GET(ctx) {
|
||||
* const slug = ctx.params.slug; // slug is inferred to be a string
|
||||
* return page({ slug });
|
||||
* },
|
||||
* });
|
||||
*
|
||||
* export default define.page<typeof handler>(({ data }) => {
|
||||
* const slug = data.slug; // slug is inferred to be a string here
|
||||
* return <h1>{slug}</h1>;
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* As a rule of thumb, always use this function to define your page
|
||||
* components. If you also have a handler for this route, pass the handler
|
||||
* object as a type argument to this function. If you do not have a handler,
|
||||
* omit the type argument.
|
||||
*
|
||||
* @typeParam Handler The type of the handler object that this page component is associated with. If this route has a handler, pass the handler object as a type argument to this function, e.g. `typeof handler`. If this route does not have a handler, omit this type argument.
|
||||
* @typeParam Data The type of data that the page component receives. This will be inferred from the handler methods if not provided. In very advanced use cases, you can specify `never` to the `Handler` type argument and provide the `Data` type explicitly.
|
||||
*/
|
||||
page<
|
||||
// deno-lint-ignore no-explicit-any
|
||||
Handler extends RouteHandler<any, State> = never,
|
||||
Data = Handler extends HandlerFn<infer Data, State> ? Data
|
||||
: Handler extends HandlerByMethod<infer Data, State> ? Data
|
||||
: never,
|
||||
>(render: AnyComponent<PageProps<Data, State>>): typeof render;
|
||||
|
||||
/**
|
||||
* Define a {@link Middleware} that will be used to process requests before
|
||||
* they are passed to the route handler. This function returns the passed
|
||||
* input as-is.
|
||||
*
|
||||
* You can use this function to help the TypeScript compiler infer the types
|
||||
* of the context object that your middleware receives. For example:
|
||||
*
|
||||
* ```ts
|
||||
* import { define } from "../utils.ts";
|
||||
*
|
||||
* export const middleware = define.middleware((ctx) => {
|
||||
* ctx.url; // ctx is inferred to be a Context object, so this is a URL
|
||||
* return ctx.next();
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* You may also pass an array of middleware functions to this function.
|
||||
*
|
||||
* @typeParam M The type of the middleware function. This will be inferred from the input function. Do not manually specify this type.
|
||||
*/
|
||||
middleware<M extends Middleware<State> | Middleware<State>[]>(
|
||||
middleware: M,
|
||||
): typeof middleware;
|
||||
/**
|
||||
* Define a layout component. This function returns the passed input as-is.
|
||||
*
|
||||
* You can use this function to help the TypeScript compiler infer the types
|
||||
* of `props` that your component receives. For example:
|
||||
*
|
||||
* ```ts
|
||||
* import { define } from "../utils.ts";
|
||||
*
|
||||
* export default define.layout((props) => {
|
||||
* const slug = props.params.slug; // Because props is inferred to be a Context object, slug is inferred to be a string
|
||||
* return <h1>{slug}</h1>;
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
layout(render: AnyComponent<PageProps<unknown, State>>): typeof render;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a set of define functions that enable better type inference and code
|
||||
* completion when defining routes and middleware.
|
||||
*
|
||||
* To use, call this function in a central file and export the result. In your
|
||||
* route and middleware files, import the {@link Define|define object} and use
|
||||
* it to define your routes and middleware using the
|
||||
* {@link Define.handlers|define.handlers},
|
||||
* {@link Define.page|define.page}, and
|
||||
* {@link Define.middleware|define.middleware} functions.
|
||||
*
|
||||
* @typeParam State The type of the state object that is passed to all middleware and route handlers.
|
||||
*/
|
||||
export function createDefine<State>(): Define<State> {
|
||||
return {
|
||||
handlers(handlers) {
|
||||
return handlers;
|
||||
},
|
||||
page(render) {
|
||||
return render;
|
||||
},
|
||||
layout(render) {
|
||||
return render;
|
||||
},
|
||||
middleware(middleware) {
|
||||
return middleware;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { expect } from "@std/expect";
|
||||
import { createDefine } from "./define.ts";
|
||||
import { page } from "./handlers.ts";
|
||||
|
||||
Deno.test.ignore("createDefine", () => {
|
||||
const define = createDefine<{ foo: number }>();
|
||||
|
||||
// Testing the types
|
||||
const handlerFn = define.handlers((ctx) => {
|
||||
ctx.state.foo satisfies number;
|
||||
return page({ bar: true });
|
||||
});
|
||||
const handlerObj = define.handlers({
|
||||
GET(ctx) {
|
||||
ctx.state.foo satisfies number;
|
||||
return page({ bar: [1, 2, 3] });
|
||||
},
|
||||
POST: () => {
|
||||
return page({ baz: "hello" });
|
||||
},
|
||||
});
|
||||
|
||||
define.page<typeof handlerFn>(({ data }) => {
|
||||
data.bar satisfies boolean;
|
||||
return "page";
|
||||
});
|
||||
|
||||
define.page<typeof handlerObj>(({ data }) => {
|
||||
if ("baz" in data) {
|
||||
data.baz satisfies string;
|
||||
} else {
|
||||
data.bar satisfies number[];
|
||||
}
|
||||
return "page";
|
||||
});
|
||||
|
||||
define.middleware((ctx) => {
|
||||
ctx.state.foo satisfies number;
|
||||
return new Response("Hello");
|
||||
});
|
||||
|
||||
expect(typeof define.page).toBe("function");
|
||||
expect(typeof define.handlers).toBe("function");
|
||||
expect(typeof define.middleware).toBe("function");
|
||||
});
|
||||
@@ -0,0 +1,400 @@
|
||||
import { App, type ListenOptions, setBuildCache } from "../app.ts";
|
||||
import { fsAdapter } from "../fs.ts";
|
||||
import * as path from "@std/path";
|
||||
import * as colors from "@std/fmt/colors";
|
||||
import { bundleJs, type FreshBundleOptions } from "./esbuild.ts";
|
||||
|
||||
import { liveReload } from "./middlewares/live_reload.ts";
|
||||
import {
|
||||
cssAssetHash,
|
||||
FileTransformer,
|
||||
type OnTransformOptions,
|
||||
} from "./file_transformer.ts";
|
||||
import type { TransformFn } from "./file_transformer.ts";
|
||||
import {
|
||||
type DevBuildCache,
|
||||
DiskBuildCache,
|
||||
type FsRoute,
|
||||
MemoryBuildCache,
|
||||
} from "./dev_build_cache.ts";
|
||||
import { BUILD_ID } from "@fresh/build-id";
|
||||
import { updateCheck } from "./update_check.ts";
|
||||
import { devErrorOverlay } from "./middlewares/error_overlay/middleware.tsx";
|
||||
import { automaticWorkspaceFolders } from "./middlewares/automatic_workspace_folders.ts";
|
||||
import { parseDirPath } from "../config.ts";
|
||||
import { pathToExportName, UniqueNamer } from "../utils.ts";
|
||||
import { checkDenoCompilerOptions } from "./check.ts";
|
||||
import { crawlFsItem } from "./fs_crawl.ts";
|
||||
import { DAY } from "../constants.ts";
|
||||
|
||||
export interface BuildOptions {
|
||||
/**
|
||||
* This sets the target environment for the generated code. Newer
|
||||
* language constructs will be transformed to match the specified
|
||||
* support range. See https://esbuild.github.io/api/#target
|
||||
* @default {"es2022"}
|
||||
*/
|
||||
target?: string | string[];
|
||||
/**
|
||||
* The root directory of the Fresh project.
|
||||
*
|
||||
* Other paths, such as `build.outDir`, `staticDir`, and `fsRoutes()`
|
||||
* are resolved relative to this directory.
|
||||
* @default Deno.cwd()
|
||||
*/
|
||||
root?: string;
|
||||
/**
|
||||
* The directory to write generated files to when `dev.ts build` is run.
|
||||
*
|
||||
* This can be an absolute path, a file URL or a relative path.
|
||||
* Relative paths are resolved against the `root` option.
|
||||
* @default "_fresh"
|
||||
*/
|
||||
outDir?: string;
|
||||
/**
|
||||
* The directory to serve static files from.
|
||||
*
|
||||
* This can be an absolute path, a file URL or a relative path.
|
||||
* Relative paths are resolved against the `root` option.
|
||||
* @default "static"
|
||||
*/
|
||||
staticDir?: string;
|
||||
/**
|
||||
* The directory which contains islands.
|
||||
*
|
||||
* This can be an absolute path, a file URL or a relative path.
|
||||
* Relative paths are resolved against the `root` option.
|
||||
* @default "islands"
|
||||
*/
|
||||
islandDir?: string;
|
||||
/**
|
||||
* The directory which contains routes.
|
||||
*
|
||||
* This can be an absolute path, a file URL or a relative path.
|
||||
* Relative paths are resolved against the `root` option.
|
||||
* @default "routes"
|
||||
*/
|
||||
routeDir?: string;
|
||||
/**
|
||||
* File paths which should be ignored when crawling the file system.
|
||||
*/
|
||||
ignore?: RegExp[];
|
||||
|
||||
/**
|
||||
* Control if/how production source maps should be handled.
|
||||
* See https://esbuild.github.io/api/#source-maps for more information.
|
||||
*/
|
||||
sourceMap?: FreshBundleOptions["sourceMap"];
|
||||
}
|
||||
|
||||
/**
|
||||
* The final resolved Builder configuration.
|
||||
*/
|
||||
export type ResolvedBuildConfig = Required<Omit<BuildOptions, "sourceMap">> & {
|
||||
mode: "development" | "production";
|
||||
buildId: string;
|
||||
sourceMap?: FreshBundleOptions["sourceMap"];
|
||||
};
|
||||
|
||||
const TEST_FILE_PATTERN = /[._]test\.(?:[tj]sx?|[mc][tj]s)$/;
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export class Builder<State = any> {
|
||||
#transformer: FileTransformer;
|
||||
#addedInternalTransforms = false;
|
||||
config: ResolvedBuildConfig;
|
||||
#islandSpecifiers = new Set<string>();
|
||||
#fsRoutes: FsRoute<State>;
|
||||
#ready = Promise.withResolvers<void>();
|
||||
|
||||
constructor(options?: BuildOptions) {
|
||||
const root = parseDirPath(options?.root ?? ".", Deno.cwd());
|
||||
const outDir = parseDirPath(options?.outDir ?? "_fresh", root);
|
||||
const staticDir = parseDirPath(options?.staticDir ?? "static", root);
|
||||
const islandDir = parseDirPath(options?.islandDir ?? "islands", root);
|
||||
const routeDir = parseDirPath(options?.routeDir ?? "routes", root);
|
||||
|
||||
this.#fsRoutes = { dir: routeDir, files: [], id: "default" };
|
||||
|
||||
this.#transformer = new FileTransformer(fsAdapter, root);
|
||||
|
||||
this.config = {
|
||||
target: options?.target ?? ["chrome99", "firefox99", "safari15"],
|
||||
root,
|
||||
outDir,
|
||||
staticDir,
|
||||
islandDir,
|
||||
routeDir,
|
||||
ignore: options?.ignore ?? [TEST_FILE_PATTERN],
|
||||
mode: "production",
|
||||
buildId: BUILD_ID,
|
||||
sourceMap: options?.sourceMap,
|
||||
};
|
||||
}
|
||||
|
||||
registerIsland(specifier: string): void {
|
||||
this.#islandSpecifiers.add(specifier);
|
||||
}
|
||||
|
||||
onTransformStaticFile(
|
||||
options: OnTransformOptions,
|
||||
callback: TransformFn,
|
||||
): void {
|
||||
this.#transformer.onTransform(options, callback);
|
||||
}
|
||||
|
||||
async listen(
|
||||
importApp: () => Promise<{ app: App<State> } | App<State>>,
|
||||
options: ListenOptions = {},
|
||||
): Promise<void> {
|
||||
// Run update check in background
|
||||
updateCheck(DAY).catch(() => {});
|
||||
|
||||
this.config.mode = "development";
|
||||
|
||||
await this.#crawlFsItems();
|
||||
|
||||
let app = await importApp();
|
||||
if (!(app instanceof App) && "app" in app) {
|
||||
app = app.app;
|
||||
}
|
||||
|
||||
const buildCache = new MemoryBuildCache<State>(
|
||||
this.config,
|
||||
this.#fsRoutes,
|
||||
this.#transformer,
|
||||
);
|
||||
|
||||
await buildCache.prepare();
|
||||
|
||||
app.config.root = this.config.root;
|
||||
app.config.mode = "development";
|
||||
setBuildCache(app, buildCache, "development");
|
||||
|
||||
const appHandler = app.handler();
|
||||
|
||||
const devApp = new App<State>(app.config)
|
||||
.use(liveReload())
|
||||
.use(devErrorOverlay())
|
||||
.use(automaticWorkspaceFolders(this.config.root))
|
||||
// Wait for islands to be ready
|
||||
.use(async (ctx) => {
|
||||
await this.#ready.promise;
|
||||
return ctx.next();
|
||||
})
|
||||
.all("*", (ctx) => appHandler(ctx.req, ctx.info));
|
||||
|
||||
devApp.config.root = this.config.root;
|
||||
devApp.config.mode = "development";
|
||||
|
||||
setBuildCache(devApp, buildCache, "development");
|
||||
|
||||
// Boot in parallel to spin up the server quicker. We'll hold
|
||||
// requests until the required assets are processed.
|
||||
await Promise.all([
|
||||
devApp.listen(options),
|
||||
this.#build(buildCache, true),
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build optimized assets for your app. By default this will create
|
||||
* a production build.
|
||||
*
|
||||
* This can also be used for testing to apply a snapshot to a particular
|
||||
* {@linkcode App} instance.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const builder = new Builder();
|
||||
* const applySnapshot = await builder.build({ snapshot: "memory" });
|
||||
*
|
||||
* Deno.test("My Test", () => {
|
||||
* const app = new App()
|
||||
* .get("/", () => new Response("hello"))
|
||||
*
|
||||
* applySnapshot(app)
|
||||
*
|
||||
* // ... your usual testing
|
||||
* })
|
||||
* ```
|
||||
* @param options
|
||||
* @returns Apply a snapshot to a particular {@linkcode App} instance.
|
||||
*/
|
||||
async build(
|
||||
options?: {
|
||||
mode?: ResolvedBuildConfig["mode"];
|
||||
snapshot?: "disk" | "memory";
|
||||
},
|
||||
): Promise<(app: App<State>) => void> {
|
||||
this.config.mode = options?.mode ?? "production";
|
||||
|
||||
await this.#crawlFsItems();
|
||||
|
||||
const buildCache = options?.snapshot === "memory"
|
||||
? new MemoryBuildCache(
|
||||
this.config,
|
||||
this.#fsRoutes,
|
||||
this.#transformer,
|
||||
)
|
||||
: new DiskBuildCache(
|
||||
this.config,
|
||||
this.#fsRoutes,
|
||||
this.#transformer,
|
||||
);
|
||||
|
||||
await this.#build(buildCache, this.config.mode === "development");
|
||||
await buildCache.prepare();
|
||||
|
||||
return (app) => {
|
||||
setBuildCache(app, buildCache, app.config.mode);
|
||||
};
|
||||
}
|
||||
|
||||
async #crawlFsItems() {
|
||||
const { islands, routes } = await crawlFsItem(
|
||||
{
|
||||
islandDir: this.config.islandDir,
|
||||
routeDir: this.config.routeDir,
|
||||
ignore: this.config.ignore,
|
||||
},
|
||||
);
|
||||
|
||||
for (let i = 0; i < islands.length; i++) {
|
||||
this.registerIsland(islands[i]);
|
||||
}
|
||||
|
||||
this.#fsRoutes.files = routes;
|
||||
}
|
||||
|
||||
async #build<T>(buildCache: DevBuildCache<T>, dev: boolean): Promise<void> {
|
||||
const { target, outDir, root } = this.config;
|
||||
const staticOutDir = path.join(outDir, "static");
|
||||
|
||||
const { denoJson, jsxImportSource } = await checkDenoCompilerOptions(root);
|
||||
|
||||
if (!this.#addedInternalTransforms) {
|
||||
this.#addedInternalTransforms = true;
|
||||
cssAssetHash(this.#transformer);
|
||||
}
|
||||
|
||||
try {
|
||||
await Deno.remove(staticOutDir);
|
||||
} catch {
|
||||
// Ignore
|
||||
}
|
||||
|
||||
const runtimePath = dev
|
||||
? "../runtime/client/dev.ts"
|
||||
: "../runtime/client/mod.tsx";
|
||||
|
||||
const entryPoints: Record<string, string> = {
|
||||
"fresh-runtime": new URL(runtimePath, import.meta.url).href,
|
||||
};
|
||||
|
||||
const namer = new UniqueNamer();
|
||||
for (const spec of this.#islandSpecifiers) {
|
||||
const specName = specToName(spec);
|
||||
const name = namer.getUniqueName(specName);
|
||||
|
||||
entryPoints[name] = spec;
|
||||
|
||||
buildCache.islandModNameToChunk.set(name, {
|
||||
name,
|
||||
server: spec,
|
||||
browser: null,
|
||||
});
|
||||
}
|
||||
|
||||
const output = await bundleJs({
|
||||
cwd: root,
|
||||
outDir: staticOutDir,
|
||||
dev: dev ?? false,
|
||||
target,
|
||||
buildId: BUILD_ID,
|
||||
entryPoints,
|
||||
jsxImportSource,
|
||||
denoJsonPath: denoJson,
|
||||
sourceMap: this.config.sourceMap,
|
||||
});
|
||||
|
||||
const prefix = `/_fresh/js/${BUILD_ID}/`;
|
||||
|
||||
for (const name of buildCache.islandModNameToChunk.keys()) {
|
||||
const chunkName = output.entryToChunk.get(name);
|
||||
if (chunkName === undefined) {
|
||||
throw new Error(`Could not find chunk for island ${name}`);
|
||||
}
|
||||
|
||||
const pathname = `${prefix}${chunkName}`;
|
||||
buildCache.islandModNameToChunk.get(name)!.browser = pathname;
|
||||
}
|
||||
|
||||
for (let i = 0; i < output.files.length; i++) {
|
||||
const file = output.files[i];
|
||||
const pathname = `${prefix}${file.path}`;
|
||||
await buildCache.addProcessedFile(pathname, file.contents, file.hash);
|
||||
}
|
||||
|
||||
await buildCache.flush();
|
||||
|
||||
if (!dev) {
|
||||
// deno-lint-ignore no-console
|
||||
console.log(
|
||||
`Assets written to: ${colors.cyan(outDir)}`,
|
||||
);
|
||||
}
|
||||
|
||||
this.#ready.resolve();
|
||||
}
|
||||
}
|
||||
|
||||
export function specToName(spec: string): string {
|
||||
if (/^(https?:|file:)/.test(spec)) {
|
||||
const url = new URL(spec);
|
||||
if (url.pathname === "/") {
|
||||
return pathToExportName(url.hostname);
|
||||
}
|
||||
|
||||
const idx = spec.lastIndexOf("/");
|
||||
return pathToExportName(spec.slice(idx + 1));
|
||||
} else if (spec.startsWith("jsr:")) {
|
||||
const match = spec.match(
|
||||
/jsr:@([^/]+)\/([^@/]+)(@[\^~]?\d+\.\d+\.\d+([^/]+)?)?(\/.*)?$/,
|
||||
)!;
|
||||
if (match[5] === undefined) {
|
||||
return pathToExportName(`${match[1]}_${match[2]}`);
|
||||
}
|
||||
|
||||
return pathToExportName(match[5]);
|
||||
} else if (spec.startsWith("npm:")) {
|
||||
const match = spec.match(
|
||||
/npm:(@([^/]+)\/([^@/]+)|[^@/]+)(@[\^~]?\d+\.\d+\.\d+([^/]+)?)?(\/.*)?$/,
|
||||
)!;
|
||||
|
||||
if (match[6] === undefined) {
|
||||
if (match[2] === undefined) {
|
||||
return pathToExportName(match[1]);
|
||||
}
|
||||
return pathToExportName(`${match[2]}_${match[3]}`);
|
||||
}
|
||||
|
||||
return pathToExportName(match[6]);
|
||||
}
|
||||
|
||||
const match = spec.match(/^(@([^/]+)\/([^@/]+)|[^@/]+)(\/.*)?$/);
|
||||
if (match !== null) {
|
||||
if (match[4] === undefined) {
|
||||
if (match[2] !== undefined) {
|
||||
return pathToExportName(`${match[2]}_${match[3]}`);
|
||||
}
|
||||
|
||||
return pathToExportName(match[1]);
|
||||
}
|
||||
|
||||
return pathToExportName(match[4]);
|
||||
}
|
||||
|
||||
return pathToExportName(spec);
|
||||
}
|
||||
@@ -0,0 +1,777 @@
|
||||
import { expect, fn } from "@std/expect";
|
||||
import * as path from "@std/path";
|
||||
import { Builder, specToName } from "./builder.ts";
|
||||
import { App } from "../app.ts";
|
||||
import { DEV_ERROR_OVERLAY_URL } from "../constants.ts";
|
||||
import { BUILD_ID } from "@fresh/build-id";
|
||||
import { withTmpDir, writeFiles } from "../test_utils.ts";
|
||||
import {
|
||||
getStdOutput,
|
||||
withChildProcessServer,
|
||||
} from "../../tests/test_utils.tsx";
|
||||
import { staticFiles } from "../middlewares/static_files.ts";
|
||||
|
||||
Deno.test({
|
||||
name: "Builder - chain onTransformStaticFile",
|
||||
fn: async () => {
|
||||
await using _tmp = await withTmpDir();
|
||||
const tmp = _tmp.dir;
|
||||
|
||||
const logs: string[] = [];
|
||||
const builder = new Builder({
|
||||
outDir: path.join(tmp, "dist"),
|
||||
staticDir: tmp,
|
||||
});
|
||||
builder.onTransformStaticFile(
|
||||
{ pluginName: "A", filter: /\.css$/ },
|
||||
() => {
|
||||
logs.push("A");
|
||||
},
|
||||
);
|
||||
builder.onTransformStaticFile(
|
||||
{ pluginName: "B", filter: /\.css$/ },
|
||||
() => {
|
||||
logs.push("B");
|
||||
},
|
||||
);
|
||||
builder.onTransformStaticFile(
|
||||
{ pluginName: "C", filter: /\.css$/ },
|
||||
() => {
|
||||
logs.push("C");
|
||||
},
|
||||
);
|
||||
|
||||
await Deno.writeTextFile(path.join(tmp, "foo.css"), "body { color: red; }");
|
||||
await builder.build();
|
||||
|
||||
expect(logs).toEqual(["A", "B", "C"]);
|
||||
},
|
||||
sanitizeOps: false,
|
||||
sanitizeResources: false,
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "Builder - handles Windows paths",
|
||||
fn: async () => {
|
||||
await using _tmp = await withTmpDir();
|
||||
const tmp = _tmp.dir;
|
||||
|
||||
const builder = new Builder({
|
||||
outDir: path.join(tmp, "dist"),
|
||||
staticDir: tmp,
|
||||
});
|
||||
await Deno.mkdir(path.join(tmp, "images"));
|
||||
await Deno.writeTextFile(
|
||||
path.join(tmp, "images", "batman.svg"),
|
||||
"<svg></svg>",
|
||||
);
|
||||
await builder.build();
|
||||
|
||||
const snapshotJson = await Deno.readTextFile(
|
||||
path.join(tmp, "dist", "snapshot.js"),
|
||||
);
|
||||
expect(snapshotJson).toContain("/images/batman.svg");
|
||||
},
|
||||
sanitizeOps: false,
|
||||
sanitizeResources: false,
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "Builder - hashes CSS urls by default",
|
||||
fn: async () => {
|
||||
await using _tmp = await withTmpDir();
|
||||
const tmp = _tmp.dir;
|
||||
const builder = new Builder({
|
||||
outDir: path.join(tmp, "dist"),
|
||||
staticDir: tmp,
|
||||
});
|
||||
|
||||
await Deno.writeTextFile(
|
||||
path.join(tmp, "foo.css"),
|
||||
"body { background: url('/foo.jpg'); }",
|
||||
);
|
||||
await builder.build();
|
||||
|
||||
const css = await Deno.readTextFile(
|
||||
path.join(tmp, "dist", "static", "foo.css"),
|
||||
);
|
||||
expect(css).toContain('body { background: url("/foo.jpg?__frsh_c=');
|
||||
},
|
||||
sanitizeOps: false,
|
||||
sanitizeResources: false,
|
||||
});
|
||||
|
||||
// Issue https://github.com/denoland/fresh/issues/2599
|
||||
Deno.test({
|
||||
name: "Builder - hashes CSS urls by default",
|
||||
fn: async () => {
|
||||
await using _tmp = await withTmpDir();
|
||||
const tmp = _tmp.dir;
|
||||
const builder = new Builder({
|
||||
outDir: path.join(tmp, "dist"),
|
||||
staticDir: tmp,
|
||||
});
|
||||
await Deno.writeTextFile(
|
||||
path.join(tmp, "foo.css"),
|
||||
`:root { --icon: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(76, 154.5, 137.5)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='20 6 9 17 4 12'%3E%3C/polyline%3E%3C/svg%3E"); }`,
|
||||
);
|
||||
await builder.build();
|
||||
|
||||
const css = await Deno.readTextFile(
|
||||
path.join(tmp, "dist", "static", "foo.css"),
|
||||
);
|
||||
expect(css).toEqual(
|
||||
`:root { --icon: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(76, 154.5, 137.5)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='20 6 9 17 4 12'%3E%3C/polyline%3E%3C/svg%3E"); }`,
|
||||
);
|
||||
},
|
||||
sanitizeOps: false,
|
||||
sanitizeResources: false,
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "Builder - can bundle islands from JSR",
|
||||
fn: async () => {
|
||||
await using _tmp = await withTmpDir();
|
||||
const tmp = _tmp.dir;
|
||||
|
||||
const outDir = path.join(tmp, "dist");
|
||||
const builder = new Builder({ outDir });
|
||||
|
||||
const specifier = "jsr:@marvinh-test/fresh-island";
|
||||
builder.registerIsland(specifier);
|
||||
|
||||
await builder.build();
|
||||
|
||||
const name = specToName(specifier);
|
||||
const code = await Deno.readTextFile(
|
||||
path.join(
|
||||
tmp,
|
||||
"dist",
|
||||
"static",
|
||||
"_fresh",
|
||||
"js",
|
||||
BUILD_ID,
|
||||
`${name}.js`,
|
||||
),
|
||||
);
|
||||
expect(code).toContain('"remote-island"');
|
||||
},
|
||||
sanitizeOps: false,
|
||||
sanitizeResources: false,
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "Builder - can bundle islands with import.meta.resolve()",
|
||||
fn: async () => {
|
||||
await using _tmp = await withTmpDir();
|
||||
const tmp = _tmp.dir;
|
||||
|
||||
const outDir = path.join(tmp, "dist");
|
||||
const builder = new Builder({ outDir });
|
||||
|
||||
const specifier = import.meta.resolve(
|
||||
"../../tests/fixtures_islands/Counter.tsx",
|
||||
);
|
||||
builder.registerIsland(specifier);
|
||||
|
||||
await builder.build({ mode: "production", snapshot: "disk" });
|
||||
|
||||
const name = specToName(specifier);
|
||||
const code = await Deno.readTextFile(
|
||||
path.join(
|
||||
tmp,
|
||||
"dist",
|
||||
"static",
|
||||
"_fresh",
|
||||
"js",
|
||||
BUILD_ID,
|
||||
`${name}.js`,
|
||||
),
|
||||
);
|
||||
expect(code).toContain('"decrement"');
|
||||
},
|
||||
sanitizeOps: false,
|
||||
sanitizeResources: false,
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "Builder - exclude files",
|
||||
fn: async () => {
|
||||
await using _tmp = await withTmpDir();
|
||||
const tmp = _tmp.dir;
|
||||
|
||||
const logs: string[] = [];
|
||||
const builder = new Builder({
|
||||
outDir: path.join(tmp, "dist"),
|
||||
staticDir: tmp,
|
||||
});
|
||||
|
||||
// String
|
||||
builder.onTransformStaticFile(
|
||||
{ pluginName: "A", filter: /\.css$/, exclude: ["foo.css"] },
|
||||
(args) => {
|
||||
logs.push(`A: ${path.basename(args.path)}`);
|
||||
},
|
||||
);
|
||||
|
||||
// Regex
|
||||
builder.onTransformStaticFile(
|
||||
{ pluginName: "B", filter: /\.css$/, exclude: [/foo\.css$/] },
|
||||
(args) => {
|
||||
logs.push(`B: ${path.basename(args.path)}`);
|
||||
},
|
||||
);
|
||||
|
||||
// Glob
|
||||
builder.onTransformStaticFile(
|
||||
{ pluginName: "C", filter: /\.css$/, exclude: ["**/foo.css"] },
|
||||
(args) => {
|
||||
logs.push(`C: ${path.basename(args.path)}`);
|
||||
},
|
||||
);
|
||||
|
||||
await Deno.writeTextFile(path.join(tmp, "foo.css"), "body { color: red; }");
|
||||
await Deno.writeTextFile(
|
||||
path.join(tmp, "bar.css"),
|
||||
"body { color: blue; }",
|
||||
);
|
||||
await builder.build();
|
||||
|
||||
expect(logs).toEqual(["A: bar.css", "B: bar.css", "C: bar.css"]);
|
||||
},
|
||||
sanitizeOps: false,
|
||||
sanitizeResources: false,
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "Builder - workspace folder middleware on listen",
|
||||
fn: async () => {
|
||||
await using _tmp = await withTmpDir();
|
||||
const tmp = _tmp.dir;
|
||||
|
||||
const builder = new Builder({
|
||||
outDir: path.join(tmp, "dist"),
|
||||
staticDir: tmp,
|
||||
});
|
||||
const app = new App();
|
||||
const abort = new AbortController();
|
||||
const port = 8011;
|
||||
await builder.listen(() => Promise.resolve(app), {
|
||||
port,
|
||||
signal: abort.signal,
|
||||
});
|
||||
|
||||
const res = await fetch(
|
||||
`http://localhost:${port}/.well-known/appspecific/com.chrome.devtools.json`,
|
||||
);
|
||||
const json = await res.json();
|
||||
await abort.abort();
|
||||
|
||||
expect(res.ok).toBe(true);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("etag")).toEqual(expect.any(String));
|
||||
expect(json).toEqual({
|
||||
workspace: {
|
||||
root: builder.config.root,
|
||||
uuid: expect.any(String),
|
||||
},
|
||||
});
|
||||
},
|
||||
sanitizeOps: false,
|
||||
sanitizeResources: false,
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "Builder - write prod routePattern",
|
||||
fn: async () => {
|
||||
const root = path.join(import.meta.dirname!, "..", "..");
|
||||
await using _tmp = await withTmpDir({ dir: root, prefix: "tmp_builder_" });
|
||||
const tmp = _tmp.dir;
|
||||
|
||||
await writeFiles(tmp, {
|
||||
"routes/foo/index.ts": `export const handler = () => new Response("ok")`,
|
||||
"main.ts": `import { App } from "fresh";
|
||||
export const app = new App().fsRoutes()`,
|
||||
});
|
||||
|
||||
const builder = new Builder({
|
||||
root: tmp,
|
||||
outDir: path.join(tmp, "dist"),
|
||||
});
|
||||
|
||||
await builder.build();
|
||||
|
||||
let text = "fail";
|
||||
await withChildProcessServer(
|
||||
{ cwd: tmp, args: ["serve", "-A", "dist/server.js"] },
|
||||
async (address) => {
|
||||
const res = await fetch(`${address}/foo`);
|
||||
text = await res.text();
|
||||
},
|
||||
);
|
||||
|
||||
expect(text).toEqual("ok");
|
||||
},
|
||||
sanitizeOps: false,
|
||||
sanitizeResources: false,
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "Builder - file:// islands",
|
||||
fn: async () => {
|
||||
const root = path.join(import.meta.dirname!, "..", "..");
|
||||
await using _tmp = await withTmpDir({ dir: root, prefix: "tmp_builder_" });
|
||||
const tmp = _tmp.dir;
|
||||
|
||||
await writeFiles(tmp, {
|
||||
"other/Foo.tsx": `export default () => <h1>ok</h1>;`,
|
||||
"routes/index.tsx": `import Foo from "../other/Foo.tsx";
|
||||
export default () => <Foo />;`,
|
||||
"main.ts": `import { App } from "fresh";
|
||||
export const app = new App().fsRoutes()`,
|
||||
});
|
||||
|
||||
const builder = new Builder({
|
||||
root: tmp,
|
||||
outDir: path.join(tmp, "dist"),
|
||||
});
|
||||
|
||||
const islandPath = path.join(tmp, "other", "Foo.tsx");
|
||||
builder.registerIsland(path.toFileUrl(islandPath).href);
|
||||
|
||||
await builder.build();
|
||||
|
||||
let text = "fail";
|
||||
await withChildProcessServer(
|
||||
{ cwd: tmp, args: ["serve", "-A", "dist/server.js"] },
|
||||
async (address) => {
|
||||
const res = await fetch(address);
|
||||
text = await res.text();
|
||||
},
|
||||
);
|
||||
|
||||
expect(text).toContain("<h1>ok</h1>");
|
||||
},
|
||||
sanitizeOps: false,
|
||||
sanitizeResources: false,
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "Builder - dev server doesn't overtake _error handler",
|
||||
fn: async () => {
|
||||
const root = path.join(import.meta.dirname!, "..", "..");
|
||||
await using _tmp = await withTmpDir({ dir: root, prefix: "tmp_builder_" });
|
||||
const tmp = _tmp.dir;
|
||||
|
||||
const app = new App()
|
||||
.onError("*", () => new Response("it works"))
|
||||
.get("/", () => new Response("no"));
|
||||
|
||||
const builder = new Builder({
|
||||
root: tmp,
|
||||
outDir: path.join(tmp, "dist"),
|
||||
});
|
||||
|
||||
const controller = new AbortController();
|
||||
await builder.listen(() => Promise.resolve<App<unknown>>(app), {
|
||||
signal: controller.signal,
|
||||
async onListen(addr) {
|
||||
const res = await fetch(`http://localhost:${addr.port}/invalid`);
|
||||
|
||||
const text = await res.text();
|
||||
expect(text).toEqual("it works");
|
||||
|
||||
controller.abort();
|
||||
},
|
||||
});
|
||||
},
|
||||
sanitizeOps: false,
|
||||
sanitizeResources: false,
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "Builder - serves static files in subdir",
|
||||
fn: async () => {
|
||||
const root = path.join(import.meta.dirname!, "..", "..");
|
||||
await using _tmp = await withTmpDir({ dir: root, prefix: "tmp_builder_" });
|
||||
const tmp = _tmp.dir;
|
||||
|
||||
const app = new App()
|
||||
.use(staticFiles())
|
||||
.get("/", () => new Response("no"));
|
||||
|
||||
await writeFiles(tmp, {
|
||||
"static/foo.txt": "ok",
|
||||
"static/test/foo.txt": "ok",
|
||||
});
|
||||
|
||||
const builder = new Builder({
|
||||
root: tmp,
|
||||
});
|
||||
|
||||
const controller = new AbortController();
|
||||
const waiter = Promise.withResolvers<void>();
|
||||
await builder.listen(() => Promise.resolve<App<unknown>>(app), {
|
||||
signal: controller.signal,
|
||||
async onListen(addr) {
|
||||
try {
|
||||
let res = await fetch(`http://localhost:${addr.port}/foo.txt`);
|
||||
expect(await res.text()).toEqual("ok");
|
||||
|
||||
res = await fetch(`http://localhost:${addr.port}/test/foo.txt`);
|
||||
expect(await res.text()).toEqual("ok");
|
||||
|
||||
controller.abort();
|
||||
waiter.resolve();
|
||||
} catch (err) {
|
||||
waiter.reject(err);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
await waiter.promise;
|
||||
},
|
||||
sanitizeOps: false,
|
||||
sanitizeResources: false,
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "Builder - serves static files in subdir in prod",
|
||||
fn: async () => {
|
||||
const root = path.join(import.meta.dirname!, "..", "..");
|
||||
await using _tmp = await withTmpDir({ dir: root, prefix: "tmp_builder_" });
|
||||
const tmp = _tmp.dir;
|
||||
|
||||
await writeFiles(tmp, {
|
||||
"main.ts": `import { App, staticFiles } from "fresh";
|
||||
export const app = new App()
|
||||
.use(staticFiles());`,
|
||||
"static/foo.txt": "ok",
|
||||
"static/test/foo.txt": "ok",
|
||||
});
|
||||
|
||||
await new Builder({ root: tmp }).build();
|
||||
|
||||
await withChildProcessServer(
|
||||
{ cwd: tmp, args: ["serve", "-A", "_fresh/server.js"] },
|
||||
async (address) => {
|
||||
let res = await fetch(`${address}/foo.txt`);
|
||||
expect(await res.text()).toEqual("ok");
|
||||
|
||||
res = await fetch(`${address}/test/foo.txt`);
|
||||
expect(await res.text()).toEqual("ok");
|
||||
},
|
||||
);
|
||||
},
|
||||
sanitizeOps: false,
|
||||
sanitizeResources: false,
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "Builder - dev server error_overlay ignores _app and _layout",
|
||||
fn: async () => {
|
||||
const root = path.join(import.meta.dirname!, "..", "..");
|
||||
await using _tmp = await withTmpDir({ dir: root, prefix: "tmp_builder_" });
|
||||
const tmp = _tmp.dir;
|
||||
const appLayoutSpy = fn(() => "app or layout") as () => string;
|
||||
|
||||
const app = new App()
|
||||
.appWrapper(appLayoutSpy)
|
||||
.layout("/", appLayoutSpy);
|
||||
|
||||
const builder = new Builder({
|
||||
root: tmp,
|
||||
outDir: path.join(tmp, "dist"),
|
||||
});
|
||||
|
||||
const controller = new AbortController();
|
||||
await builder.listen(() => Promise.resolve<App<unknown>>(app), {
|
||||
signal: controller.signal,
|
||||
async onListen(addr) {
|
||||
const res = await fetch(
|
||||
`http://localhost:${addr.port}/${DEV_ERROR_OVERLAY_URL}?message=__ok__`,
|
||||
);
|
||||
|
||||
const text = await res.text();
|
||||
expect(text).toMatch(/__ok__/);
|
||||
expect(appLayoutSpy).toHaveBeenCalledTimes(0);
|
||||
|
||||
controller.abort();
|
||||
},
|
||||
});
|
||||
},
|
||||
sanitizeOps: false,
|
||||
sanitizeResources: false,
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
// Currently waiting on bug fixes in @deno/loader
|
||||
// to support resolving without passing entry points
|
||||
ignore: true,
|
||||
name: "Builder - mapped islands",
|
||||
fn: async () => {
|
||||
const root = path.join(import.meta.dirname!, "..", "..");
|
||||
await using _tmp = await withTmpDir({ dir: root, prefix: "tmp_builder_" });
|
||||
const tmp = _tmp.dir;
|
||||
|
||||
await writeFiles(tmp, {
|
||||
"other/Foo.tsx": `export default () => <h1>ok</h1>;`,
|
||||
"routes/index.tsx": `import Foo from "foo-island";
|
||||
export default () => <Foo />;`,
|
||||
"main.ts": `import { App } from "fresh";
|
||||
export const app = new App().fsRoutes()`,
|
||||
"deno.json": JSON.stringify({
|
||||
imports: { "foo-island": "other/Foo.tsx" },
|
||||
}),
|
||||
});
|
||||
|
||||
const builder = new Builder({
|
||||
root: tmp,
|
||||
outDir: path.join(tmp, "dist"),
|
||||
});
|
||||
|
||||
builder.registerIsland("foo-island");
|
||||
|
||||
await builder.build();
|
||||
|
||||
let text = "fail";
|
||||
await withChildProcessServer(
|
||||
{ cwd: tmp, args: ["serve", "-A", "dist/server.js"] },
|
||||
async (address) => {
|
||||
const res = await fetch(address);
|
||||
text = await res.text();
|
||||
},
|
||||
);
|
||||
|
||||
expect(text).toContain("<h1>ok</h1>");
|
||||
},
|
||||
sanitizeOps: false,
|
||||
sanitizeResources: false,
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "Builder - source maps",
|
||||
fn: async () => {
|
||||
const root = path.join(import.meta.dirname!, "..", "..");
|
||||
await using _tmp = await withTmpDir({ dir: root, prefix: "tmp_builder_" });
|
||||
const tmp = _tmp.dir;
|
||||
|
||||
await writeFiles(tmp, {
|
||||
"islands/Foo.tsx": `export const Foo = () => <h1>hello</h1>`,
|
||||
"routes/index.ts": `export const handler = () => new Response("ok")`,
|
||||
"main.ts": `import { App } from "fresh";
|
||||
export const app = new App().fsRoutes()`,
|
||||
});
|
||||
|
||||
const builder = new Builder({
|
||||
root: tmp,
|
||||
outDir: path.join(tmp, "dist"),
|
||||
sourceMap: {
|
||||
kind: "external",
|
||||
sourceRoot: "foo",
|
||||
sourcesContent: true,
|
||||
},
|
||||
});
|
||||
await builder.build();
|
||||
|
||||
const assetDir = path.join(
|
||||
builder.config.outDir,
|
||||
"static",
|
||||
"_fresh",
|
||||
"js",
|
||||
builder.config.buildId,
|
||||
);
|
||||
const entries = await Array.fromAsync(Deno.readDir(assetDir));
|
||||
|
||||
const map = entries.find((entry) =>
|
||||
entry.isFile && entry.name.endsWith(".js.map")
|
||||
);
|
||||
if (!map) throw new Error(`Sourcemap not found`);
|
||||
|
||||
const content = await Deno.readTextFile(path.join(assetDir, map.name));
|
||||
|
||||
const json = JSON.parse(content) as {
|
||||
version: 3;
|
||||
sources: string[];
|
||||
sourceRoot?: string;
|
||||
sourcesContent: string[];
|
||||
mappings: string;
|
||||
names?: string[];
|
||||
};
|
||||
|
||||
expect(json.sourcesContent.length).toBeGreaterThan(0);
|
||||
expect(json.sourcesContent.length).toBeGreaterThan(0);
|
||||
},
|
||||
sanitizeOps: false,
|
||||
sanitizeResources: false,
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "Builder - compile entry",
|
||||
fn: async () => {
|
||||
const root = path.join(import.meta.dirname!, "..", "..");
|
||||
await using _tmp = await withTmpDir({ dir: root, prefix: "tmp_builder_" });
|
||||
await using _outDir = await withTmpDir();
|
||||
const tmp = _tmp.dir;
|
||||
|
||||
await writeFiles(tmp, {
|
||||
"deno.json": JSON.stringify({
|
||||
links: [path.relative(tmp, root)],
|
||||
workspace: [],
|
||||
compilerOptions: {
|
||||
jsx: "react-jsx",
|
||||
jsxImportSource: "preact",
|
||||
},
|
||||
imports: {
|
||||
"fresh": "jsr:@fresh/core@*",
|
||||
"preact": "npm:preact@*",
|
||||
"@preact/signals": "npm:@preact/signals@*",
|
||||
},
|
||||
}),
|
||||
"islands/Foo.tsx": `export const Foo = () => <h1>hello</h1>`,
|
||||
"routes/index.ts": `export const handler = () => new Response("ok")`,
|
||||
"static/foo.txt": "ok",
|
||||
"main.ts": `import { App, staticFiles } from "fresh";
|
||||
export const app = new App()
|
||||
.use(staticFiles())
|
||||
.fsRoutes();`,
|
||||
});
|
||||
|
||||
const builder = new Builder({
|
||||
root: tmp,
|
||||
});
|
||||
await builder.build();
|
||||
|
||||
const outBin = path.join(_outDir.dir, "fresh-compiled");
|
||||
const bin = Deno.build.os === "windows" ? "deno.exe" : "deno";
|
||||
const cp = await new Deno.Command(bin, {
|
||||
args: [
|
||||
"compile",
|
||||
"-A",
|
||||
"--include",
|
||||
"static/",
|
||||
"--include",
|
||||
"_fresh",
|
||||
"--output",
|
||||
outBin,
|
||||
path.join("_fresh", "compiled-entry.js"),
|
||||
],
|
||||
cwd: tmp,
|
||||
}).output();
|
||||
|
||||
const { stderr, stdout } = getStdOutput(cp);
|
||||
// deno-lint-ignore no-console
|
||||
console.log(stdout);
|
||||
// deno-lint-ignore no-console
|
||||
console.log(stderr);
|
||||
|
||||
await withChildProcessServer({
|
||||
bin: outBin,
|
||||
cwd: _outDir.dir,
|
||||
args: [],
|
||||
env: {
|
||||
PORT: "0",
|
||||
HOSTNAME: "127.0.0.1",
|
||||
},
|
||||
}, async (address) => {
|
||||
let res = await fetch(address);
|
||||
expect(await res.text()).toEqual("ok");
|
||||
|
||||
res = await fetch(`${address}/foo.txt`);
|
||||
expect(await res.text()).toEqual("ok");
|
||||
});
|
||||
},
|
||||
sanitizeOps: false,
|
||||
sanitizeResources: false,
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "Builder - island that imports json entry",
|
||||
fn: async () => {
|
||||
const root = path.join(import.meta.dirname!, "..", "..");
|
||||
await using _tmp = await withTmpDir({ dir: root, prefix: "tmp_builder_" });
|
||||
await using _outDir = await withTmpDir();
|
||||
const tmp = _tmp.dir;
|
||||
|
||||
await writeFiles(tmp, {
|
||||
"deno.json": JSON.stringify({
|
||||
links: [path.relative(tmp, root)],
|
||||
workspace: [],
|
||||
compilerOptions: {
|
||||
jsx: "react-jsx",
|
||||
jsxImportSource: "preact",
|
||||
},
|
||||
imports: {
|
||||
"fresh": "jsr:@fresh/core@*",
|
||||
"preact": "npm:preact@*",
|
||||
"@preact/signals": "npm:@preact/signals@*",
|
||||
"mime-db": "npm:mime-db@*",
|
||||
},
|
||||
}),
|
||||
"islands/Foo.tsx": `import * as mime from "mime-db"
|
||||
export const Foo = () => {
|
||||
console.log(mime);
|
||||
return <h1>ok</h1>
|
||||
}`,
|
||||
"routes/index.ts": `export default () => <Foo />`,
|
||||
"main.ts": `import { App, staticFiles } from "fresh";
|
||||
export const app = new App()
|
||||
.use(staticFiles())
|
||||
.fsRoutes();`,
|
||||
});
|
||||
|
||||
const builder = new Builder({
|
||||
root: tmp,
|
||||
});
|
||||
await builder.build();
|
||||
},
|
||||
sanitizeOps: false,
|
||||
sanitizeResources: false,
|
||||
});
|
||||
|
||||
Deno.test("specToName", () => {
|
||||
// HTTP
|
||||
expect(specToName("http://example.com")).toEqual("example");
|
||||
expect(specToName("http://example.com:8000")).toEqual("example");
|
||||
expect(specToName("http://example.com:8000/foo/bar")).toEqual(
|
||||
"bar",
|
||||
);
|
||||
|
||||
// HTTPS
|
||||
expect(specToName("https://example.com")).toEqual("example");
|
||||
expect(specToName("https://example.com:8000")).toEqual("example");
|
||||
expect(specToName("https://example.com:8000/foo/bar")).toEqual(
|
||||
"bar",
|
||||
);
|
||||
|
||||
// JSR
|
||||
expect(specToName("jsr:@foo/bar")).toEqual("foo_bar");
|
||||
expect(specToName("jsr:@foo/bar@1.0.0")).toEqual("foo_bar");
|
||||
expect(specToName("jsr:@foo/bar@^1.0.0")).toEqual("foo_bar");
|
||||
expect(specToName("jsr:@foo/bar@~1.0.0")).toEqual("foo_bar");
|
||||
expect(specToName("jsr:@foo/bar@~1.0.0-alpha.32")).toEqual("foo_bar");
|
||||
expect(specToName("jsr:@foo/bar@~1.0.0-alpha.32/asdf")).toEqual("asdf");
|
||||
expect(specToName("jsr:@foo/bar/asdf")).toEqual("asdf");
|
||||
|
||||
// npm
|
||||
expect(specToName("npm:foo")).toEqual("foo");
|
||||
expect(specToName("npm:foo/bar")).toEqual("bar");
|
||||
expect(specToName("npm:foo@1.0.0")).toEqual("foo");
|
||||
expect(specToName("npm:foo@^1.0.0")).toEqual("foo");
|
||||
expect(specToName("npm:foo@~1.0.0-alpha.32")).toEqual("foo");
|
||||
expect(specToName("npm:@foo/bar")).toEqual("foo_bar");
|
||||
expect(specToName("npm:@foo/bar/asdf")).toEqual("asdf");
|
||||
expect(specToName("npm:@foo/bar@1.0.0")).toEqual("foo_bar");
|
||||
expect(specToName("npm:@foo/bar@^1.0.0")).toEqual("foo_bar");
|
||||
expect(specToName("npm:@foo/bar@~1.0.0-alpha.32")).toEqual("foo_bar");
|
||||
|
||||
// other
|
||||
expect(specToName("foo")).toEqual("foo");
|
||||
expect(specToName("@foo/bar")).toEqual("foo_bar");
|
||||
expect(specToName("foo/bar")).toEqual("bar");
|
||||
expect(specToName("@foo/bar/asdf")).toEqual("asdf");
|
||||
|
||||
expect(specToName("islands/foo.v2.tsx")).toEqual("foo_v2");
|
||||
expect(specToName("/islands/_bar-baz-...-$.tsx")).toEqual("_bar_baz_$");
|
||||
expect(specToName("/islands/1_hello.tsx")).toEqual("_hello");
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import * as JSONC from "@std/jsonc";
|
||||
import * as path from "@std/path";
|
||||
|
||||
export interface DenoConfig {
|
||||
workspace?: string[];
|
||||
compilerOptions?: {
|
||||
jsx?: string;
|
||||
jsxImportSource?: string;
|
||||
jsxPrecompileSkipElements?: string[];
|
||||
};
|
||||
}
|
||||
|
||||
export async function checkDenoCompilerOptions(root: string) {
|
||||
const denoJson = await findNearestDenoConfigWithCompilerOptions(
|
||||
root,
|
||||
);
|
||||
|
||||
const jsxImportSource = denoJson.config.compilerOptions?.jsxImportSource;
|
||||
if (jsxImportSource === undefined) {
|
||||
throw new Error(
|
||||
`Option compilerOptions > jsxImportSource not set in: ${denoJson.filePath}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Check precompile option
|
||||
if (denoJson.config.compilerOptions?.jsx === "precompile") {
|
||||
const expected = ["a", "img", "source", "body", "html", "head"];
|
||||
const skipped = denoJson.config.compilerOptions.jsxPrecompileSkipElements;
|
||||
if (!skipped || expected.some((name) => !skipped.includes(name))) {
|
||||
throw new Error(
|
||||
`Expected option compilerOptions > jsxPrecompileSkipElements to contain ${
|
||||
expected.map((name) => `"${name}"`).join(", ")
|
||||
}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return { jsxImportSource, denoJson: denoJson.filePath };
|
||||
}
|
||||
|
||||
export async function findNearestDenoConfigWithCompilerOptions(
|
||||
directory: string,
|
||||
): Promise<{ config: DenoConfig; filePath: string }> {
|
||||
let dir = directory;
|
||||
while (true) {
|
||||
for (const name of ["deno.json", "deno.jsonc"]) {
|
||||
const filePath = path.join(dir, name);
|
||||
try {
|
||||
const file = await Deno.readTextFile(filePath);
|
||||
let config;
|
||||
if (name.endsWith(".jsonc")) {
|
||||
config = JSONC.parse(file);
|
||||
} else {
|
||||
config = JSON.parse(file);
|
||||
}
|
||||
if (config.compilerOptions) return { config, filePath };
|
||||
if (config.workspace) break;
|
||||
break;
|
||||
} catch (err) {
|
||||
if (!(err instanceof Deno.errors.NotFound)) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
const parent = path.dirname(dir);
|
||||
if (parent === dir) break;
|
||||
dir = parent;
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`Could not find a deno.json or deno.jsonc file in the current directory or any parent directory that contains a 'compilerOptions' field.`,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,556 @@
|
||||
import {
|
||||
type BuildCache,
|
||||
IslandPreparer,
|
||||
type StaticFile,
|
||||
} from "../build_cache.ts";
|
||||
import * as path from "@std/path";
|
||||
import * as pathWin32 from "@std/path/windows";
|
||||
import { encodeHex } from "@std/encoding/hex";
|
||||
import { fsAdapter } from "../fs.ts";
|
||||
import type { FileTransformer } from "./file_transformer.ts";
|
||||
import { assertInDir, pathToSpec } from "../utils.ts";
|
||||
import type { ResolvedBuildConfig } from "./builder.ts";
|
||||
import { fsItemsToCommands, type FsRouteFile } from "../fs_routes.ts";
|
||||
import type { Command } from "../commands.ts";
|
||||
import type { ServerIslandRegistry } from "../context.ts";
|
||||
import { contentType as getStdContentType } from "@std/media-types/content-type";
|
||||
|
||||
const WINDOWS_SEPARATOR = pathWin32.SEPARATOR;
|
||||
|
||||
export interface MemoryFile {
|
||||
hash: string | null;
|
||||
contentType: string;
|
||||
content: Uint8Array;
|
||||
}
|
||||
|
||||
export interface IslandModChunk {
|
||||
name: string;
|
||||
server: string;
|
||||
browser: string | null;
|
||||
}
|
||||
|
||||
export type FsRouteFileNoMod<State> = Omit<FsRouteFile<State>, "mod"> & {
|
||||
lazy: boolean;
|
||||
};
|
||||
|
||||
export interface FsRoute<State> {
|
||||
id: string;
|
||||
dir: string;
|
||||
files: FsRouteFileNoMod<State>[];
|
||||
}
|
||||
|
||||
export interface DevBuildCache<State> extends BuildCache<State> {
|
||||
islandModNameToChunk: Map<string, IslandModChunk>;
|
||||
addUnprocessedFile(pathname: string, dir: string): void;
|
||||
addProcessedFile(
|
||||
pathname: string,
|
||||
content: Uint8Array,
|
||||
hash: string | null,
|
||||
): Promise<void>;
|
||||
flush(): Promise<void>;
|
||||
prepare(): Promise<void>;
|
||||
}
|
||||
|
||||
export class MemoryBuildCache<State> implements DevBuildCache<State> {
|
||||
#processedFiles = new Map<string, MemoryFile>();
|
||||
#unprocessedFiles = new Map<string, string>();
|
||||
#config: ResolvedBuildConfig;
|
||||
#transformer: FileTransformer;
|
||||
islandModNameToChunk = new Map<string, IslandModChunk>();
|
||||
#fsRoutes: FsRoute<State>;
|
||||
#commands: Command<State>[] = [];
|
||||
root: string;
|
||||
islandRegistry: ServerIslandRegistry = new Map();
|
||||
clientEntry: string;
|
||||
features = { errorOverlay: false };
|
||||
|
||||
constructor(
|
||||
config: ResolvedBuildConfig,
|
||||
fsRoutes: FsRoute<State>,
|
||||
transformer: FileTransformer,
|
||||
) {
|
||||
if (config.mode === "development") {
|
||||
this.features.errorOverlay = true;
|
||||
}
|
||||
|
||||
this.#config = config;
|
||||
this.#fsRoutes = fsRoutes;
|
||||
this.#transformer = transformer;
|
||||
this.root = config.root;
|
||||
|
||||
this.clientEntry = getClientEntry(config.buildId);
|
||||
}
|
||||
|
||||
getFsRoutes(): Command<State>[] {
|
||||
return this.#commands;
|
||||
}
|
||||
|
||||
async readFile(pathname: string): Promise<StaticFile | null> {
|
||||
const processed = this.#processedFiles.get(pathname);
|
||||
if (processed !== undefined) {
|
||||
return {
|
||||
hash: processed.hash,
|
||||
readable: processed.content,
|
||||
size: processed.content.byteLength,
|
||||
contentType: processed.contentType,
|
||||
close: () => {},
|
||||
};
|
||||
}
|
||||
|
||||
const unprocessed = this.#unprocessedFiles.get(pathname);
|
||||
if (unprocessed !== undefined) {
|
||||
try {
|
||||
const [stat, file] = await Promise.all([
|
||||
Deno.stat(unprocessed),
|
||||
Deno.open(unprocessed, { read: true }),
|
||||
]);
|
||||
|
||||
return {
|
||||
hash: null,
|
||||
size: stat.size,
|
||||
readable: file.readable,
|
||||
contentType: getContentType(unprocessed),
|
||||
close: () => file.close(),
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
let entry = pathname.startsWith("/") ? pathname.slice(1) : pathname;
|
||||
entry = path.join(this.#config.staticDir, entry);
|
||||
const relative = path.relative(this.#config.staticDir, entry);
|
||||
if (relative.startsWith("..")) {
|
||||
throw new Error(
|
||||
`Processed file resolved outside of static dir ${entry}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Might be a file that we still need to process
|
||||
const transformed = await this.#transformer.process(
|
||||
entry,
|
||||
"development",
|
||||
this.#config.target,
|
||||
);
|
||||
|
||||
if (transformed !== null) {
|
||||
for (let i = 0; i < transformed.length; i++) {
|
||||
const file = transformed[i];
|
||||
const relative = path.relative(this.#config.staticDir, file.path);
|
||||
if (relative.startsWith(".")) {
|
||||
throw new Error(
|
||||
`Processed file resolved outside of static dir ${file.path}`,
|
||||
);
|
||||
}
|
||||
const pathname = new URL(relative, "http://localhost").pathname;
|
||||
|
||||
this.addProcessedFile(pathname, file.content, null);
|
||||
}
|
||||
if (this.#processedFiles.has(pathname)) {
|
||||
return this.readFile(pathname);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
const filePath = path.join(this.#config.staticDir, pathname);
|
||||
const relative = path.relative(this.#config.staticDir, filePath);
|
||||
if (!relative.startsWith(".") && (await Deno.stat(filePath)).isFile) {
|
||||
const pathname = new URL(relative, "http://localhost").pathname;
|
||||
this.addUnprocessedFile(pathname, this.#config.staticDir);
|
||||
return this.readFile(pathname);
|
||||
}
|
||||
} catch (err) {
|
||||
if (!(err instanceof Deno.errors.NotFound)) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
addUnprocessedFile(pathname: string, dir: string): void {
|
||||
this.#unprocessedFiles.set(
|
||||
pathname,
|
||||
path.join(dir, pathname),
|
||||
);
|
||||
}
|
||||
|
||||
// deno-lint-ignore require-await
|
||||
async addProcessedFile(
|
||||
pathname: string,
|
||||
content: Uint8Array,
|
||||
hash: string | null,
|
||||
): Promise<void> {
|
||||
this.#processedFiles.set(pathname, {
|
||||
content,
|
||||
hash,
|
||||
contentType: getContentType(pathname),
|
||||
});
|
||||
}
|
||||
|
||||
async flush(): Promise<void> {
|
||||
const preparer = new IslandPreparer();
|
||||
|
||||
// Load islands
|
||||
await Promise.all(
|
||||
Array.from(this.islandModNameToChunk.entries()).map(
|
||||
async ([name, chunk]) => {
|
||||
const fileUrl = maybeToFileUrl(chunk.server);
|
||||
const mod = await import(fileUrl);
|
||||
|
||||
if (chunk.browser === null) {
|
||||
throw new Error(`Unexpected missing browser chunk`);
|
||||
}
|
||||
|
||||
preparer.prepare(this.islandRegistry, mod, chunk.browser, name);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async prepare(): Promise<void> {
|
||||
// Load FS routes
|
||||
const files = await Promise.all(this.#fsRoutes.files.map(async (file) => {
|
||||
const fileUrl = maybeToFileUrl(file.filePath);
|
||||
return {
|
||||
...file,
|
||||
mod: file.lazy ? () => import(fileUrl) : await import(fileUrl),
|
||||
};
|
||||
}));
|
||||
this.#commands = fsItemsToCommands(files);
|
||||
}
|
||||
}
|
||||
|
||||
export class DiskBuildCache<State> implements DevBuildCache<State> {
|
||||
#processedFiles = new Map<string, string | null>();
|
||||
#unprocessedFiles = new Map<string, string>();
|
||||
#transformer: FileTransformer;
|
||||
#config: ResolvedBuildConfig;
|
||||
islandModNameToChunk = new Map<string, IslandModChunk>();
|
||||
#fsRoutes: FsRoute<State>;
|
||||
root: string;
|
||||
islandRegistry: ServerIslandRegistry = new Map();
|
||||
clientEntry: string = "";
|
||||
features = { errorOverlay: false };
|
||||
|
||||
constructor(
|
||||
config: ResolvedBuildConfig,
|
||||
fsRoutes: FsRoute<State>,
|
||||
transformer: FileTransformer,
|
||||
) {
|
||||
if (config.mode === "development") {
|
||||
this.features.errorOverlay = true;
|
||||
}
|
||||
this.#fsRoutes = fsRoutes;
|
||||
this.#transformer = transformer;
|
||||
this.#config = config;
|
||||
this.root = config.root;
|
||||
}
|
||||
|
||||
getFsRoutes(): Command<State>[] {
|
||||
return [];
|
||||
}
|
||||
|
||||
addUnprocessedFile(pathname: string, dir: string): void {
|
||||
this.#unprocessedFiles.set(
|
||||
pathname.replaceAll(WINDOWS_SEPARATOR, "/"),
|
||||
path.join(dir, pathname),
|
||||
);
|
||||
}
|
||||
|
||||
async addProcessedFile(
|
||||
pathname: string,
|
||||
content: Uint8Array,
|
||||
hash: string | null,
|
||||
) {
|
||||
this.#processedFiles.set(pathname, hash);
|
||||
|
||||
const outDir = pathname === "/metafile.json"
|
||||
? this.#config.outDir
|
||||
: path.join(this.#config.outDir, "static");
|
||||
const filePath = path.join(outDir, pathname);
|
||||
assertInDir(filePath, outDir);
|
||||
|
||||
await fsAdapter.mkdirp(path.dirname(filePath));
|
||||
await Deno.writeFile(filePath, content);
|
||||
}
|
||||
|
||||
// deno-lint-ignore require-await
|
||||
async readFile(_pathname: string): Promise<StaticFile | null> {
|
||||
throw new Error("Not implemented in build mode");
|
||||
}
|
||||
|
||||
async prepare(): Promise<void> {
|
||||
// not needed
|
||||
}
|
||||
|
||||
async flush(): Promise<void> {
|
||||
const { staticDir, outDir, target, root } = this.#config;
|
||||
|
||||
if (await fsAdapter.isDirectory(staticDir)) {
|
||||
const entries = fsAdapter.walk(staticDir, {
|
||||
includeDirs: false,
|
||||
includeFiles: true,
|
||||
followSymlinks: false,
|
||||
// Skip any folder or file starting with a "."
|
||||
skip: [/\/\.[^/]+(\/|$)/],
|
||||
});
|
||||
|
||||
for await (const entry of entries) {
|
||||
// OutDir might be inside static dir
|
||||
if (!path.relative(outDir, entry.path).startsWith("..")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const result = await this.#transformer.process(
|
||||
entry.path,
|
||||
"production",
|
||||
target,
|
||||
);
|
||||
|
||||
if (result !== null) {
|
||||
for (let i = 0; i < result.length; i++) {
|
||||
const file = result[i];
|
||||
assertInDir(file.path, staticDir);
|
||||
const pathname = `/${path.relative(staticDir, file.path)}`;
|
||||
await this.addProcessedFile(pathname, file.content, null);
|
||||
}
|
||||
} else {
|
||||
const relative = path.relative(staticDir, entry.path);
|
||||
const pathname = `/${relative}`;
|
||||
this.addUnprocessedFile(pathname, staticDir);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const staticFiles: PendingStaticFile[] = [];
|
||||
for (const [name, filePath] of this.#unprocessedFiles.entries()) {
|
||||
staticFiles.push({ filePath, pathname: name, hash: null });
|
||||
}
|
||||
|
||||
for (const [name, maybeHash] of this.#processedFiles.entries()) {
|
||||
// Ignore esbuild meta file. It's not intended for serving
|
||||
if (name === "/metafile.json") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const filePath = path.join(outDir, "static", name);
|
||||
staticFiles.push({ filePath, pathname: name, hash: maybeHash });
|
||||
}
|
||||
|
||||
const islandSpecifiers: string[] = [];
|
||||
for (const spec of this.islandModNameToChunk.keys()) {
|
||||
islandSpecifiers.push(spec);
|
||||
}
|
||||
|
||||
const islands = Array.from(this.islandModNameToChunk.values());
|
||||
|
||||
await Deno.writeTextFile(
|
||||
path.join(outDir, "snapshot.js"),
|
||||
await generateSnapshotServer({
|
||||
buildId: this.#config.buildId,
|
||||
clientEntry: getClientEntry(this.#config.buildId),
|
||||
staticFiles,
|
||||
islands,
|
||||
writeSpecifier: (filePath) => {
|
||||
return pathToSpec(outDir, filePath);
|
||||
},
|
||||
fsRoutesFiles: this.#fsRoutes.files,
|
||||
outDir: root,
|
||||
}),
|
||||
);
|
||||
|
||||
// TODO: Make main file configurable
|
||||
const appPath = path.relative(outDir, root);
|
||||
await Deno.writeTextFile(
|
||||
path.join(outDir, "server.js"),
|
||||
generateServerEntry({
|
||||
root: appPath,
|
||||
serverEntry: path
|
||||
.join(appPath, "main.ts")
|
||||
.replaceAll(/[\\/]+/g, "/"),
|
||||
snapshotSpecifier: "./snapshot.js",
|
||||
}),
|
||||
);
|
||||
|
||||
await Deno.writeTextFile(
|
||||
path.join(outDir, "compiled-entry.js"),
|
||||
`import fetcher from "./server.js";
|
||||
|
||||
Deno.serve(
|
||||
{ port: Deno.env.get("PORT"), hostname: Deno.env.get("HOSTNAME") },
|
||||
fetcher.fetch
|
||||
);`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const EDIT_WARNING =
|
||||
`// WARNING: DO NOT EDIT THIS FILE. It is autogenerated by Fresh.`;
|
||||
|
||||
export async function hashContent(
|
||||
content: Uint8Array | ReadableStream<Uint8Array>,
|
||||
): Promise<string> {
|
||||
const buffer = await new Response(content).arrayBuffer();
|
||||
|
||||
const hashBuf = await crypto.subtle.digest(
|
||||
"SHA-256",
|
||||
buffer,
|
||||
);
|
||||
return encodeHex(hashBuf);
|
||||
}
|
||||
|
||||
export function getContentType(filePath: string): string {
|
||||
const ext = path.extname(filePath);
|
||||
return getStdContentType(ext) ?? "text/plain";
|
||||
}
|
||||
|
||||
function maybeToFileUrl(file: string) {
|
||||
return file.startsWith("file://") ? file : path.toFileUrl(file).href;
|
||||
}
|
||||
|
||||
export interface PendingStaticFile {
|
||||
pathname: string;
|
||||
filePath: string;
|
||||
hash: string | null;
|
||||
}
|
||||
|
||||
export async function generateSnapshotServer(
|
||||
options: {
|
||||
outDir: string;
|
||||
buildId: string;
|
||||
clientEntry: string;
|
||||
islands: IslandModChunk[];
|
||||
// deno-lint-ignore no-explicit-any
|
||||
fsRoutesFiles: FsRouteFileNoMod<any>[];
|
||||
staticFiles: PendingStaticFile[];
|
||||
writeSpecifier: (filePath: string) => string;
|
||||
},
|
||||
): Promise<string> {
|
||||
const {
|
||||
islands,
|
||||
writeSpecifier,
|
||||
fsRoutesFiles,
|
||||
outDir,
|
||||
} = options;
|
||||
|
||||
const islandImports = islands
|
||||
.map((item) => {
|
||||
const spec = writeSpecifier(item.server);
|
||||
return `import * as ${item.name} from "${spec}";`;
|
||||
})
|
||||
.join("\n");
|
||||
|
||||
const fsRouteImports = fsRoutesFiles
|
||||
.map((item, i) => {
|
||||
if (item.lazy) return null;
|
||||
const spec = writeSpecifier(item.filePath);
|
||||
return `import * as fsRoute_${i} from "${spec}"`;
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
|
||||
const islandMarkers = islands.map((item) => {
|
||||
const browser = JSON.stringify(item.browser);
|
||||
const name = JSON.stringify(item.name);
|
||||
return `islandPreparer.prepare(islands, ${item.name}, ${browser}, ${name});`;
|
||||
}).join("\n");
|
||||
|
||||
const serializedFsRoutes = fsRoutesFiles
|
||||
.map((item, i) => {
|
||||
const id = JSON.stringify(item.id);
|
||||
const pattern = JSON.stringify(item.pattern);
|
||||
const type = JSON.stringify(item.type);
|
||||
const routePattern = JSON.stringify(item.routePattern);
|
||||
|
||||
let mod = "";
|
||||
if (item.lazy) {
|
||||
const spec = writeSpecifier(item.filePath);
|
||||
mod = `() => import(${JSON.stringify(spec)})`;
|
||||
} else {
|
||||
mod = `fsRoute_${i}`;
|
||||
}
|
||||
|
||||
return ` { id: ${id}, mod: ${mod}, type: ${type}, pattern: ${pattern}, routePattern: ${routePattern} },`;
|
||||
})
|
||||
.join("\n");
|
||||
|
||||
const staticFiles = await Promise.all(
|
||||
options.staticFiles.map(async (item) => {
|
||||
const file = await Deno.open(item.filePath);
|
||||
const hash = item.hash ? item.hash : await hashContent(file.readable);
|
||||
const url = new URL(item.pathname, "http://localhost");
|
||||
|
||||
return {
|
||||
name: url.pathname,
|
||||
hash,
|
||||
filePath: path.isAbsolute(item.filePath)
|
||||
? path.relative(outDir, item.filePath)
|
||||
: item.filePath,
|
||||
contentType: getContentType(item.filePath),
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
return `${EDIT_WARNING}
|
||||
import { IslandPreparer } from "fresh/internal";
|
||||
${islandImports}
|
||||
${fsRouteImports}
|
||||
|
||||
export const clientEntry = ${JSON.stringify(options.clientEntry)}
|
||||
export const version = ${JSON.stringify(options.buildId)}
|
||||
|
||||
export const islands = new Map();
|
||||
const islandPreparer = new IslandPreparer();
|
||||
${islandMarkers}
|
||||
|
||||
export const staticFiles = new Map([
|
||||
${
|
||||
staticFiles.map((def) =>
|
||||
` [${JSON.stringify(def.name)}, ${JSON.stringify(def)}]`
|
||||
).join(",\n")
|
||||
}
|
||||
]);
|
||||
|
||||
export const fsRoutes = [
|
||||
${serializedFsRoutes}
|
||||
];
|
||||
`.replaceAll(/\n[\n]+/g, "\n\n");
|
||||
}
|
||||
|
||||
export function generateServerEntry(
|
||||
options: {
|
||||
root: string;
|
||||
serverEntry: string;
|
||||
snapshotSpecifier: string;
|
||||
},
|
||||
): string {
|
||||
let rootPath = `path.join(import.meta.dirname, ${
|
||||
JSON.stringify(options.root)
|
||||
})`;
|
||||
if (path.isAbsolute(options.root)) {
|
||||
// deno-lint-ignore no-console
|
||||
console.warn(
|
||||
`WARN: using absolute root path in snapshot: "${options.root}"`,
|
||||
);
|
||||
|
||||
rootPath = JSON.stringify(options.root);
|
||||
}
|
||||
|
||||
return `${EDIT_WARNING}
|
||||
import { setBuildCache, ProdBuildCache, path } from "fresh/internal";
|
||||
import * as snapshot from "${options.snapshotSpecifier}";
|
||||
import { app } from "${options.serverEntry}";
|
||||
|
||||
const root = ${rootPath};
|
||||
setBuildCache(app, new ProdBuildCache(root, snapshot), "production");
|
||||
|
||||
export default {
|
||||
fetch: app.handler()
|
||||
};
|
||||
`;
|
||||
}
|
||||
|
||||
function getClientEntry(buildId: string) {
|
||||
return `/_fresh/js/${buildId}/fresh-runtime.js`;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { expect } from "@std/expect";
|
||||
import { MemoryBuildCache } from "./dev_build_cache.ts";
|
||||
import { FileTransformer } from "./file_transformer.ts";
|
||||
import { createFakeFs, withTmpDir } from "../test_utils.ts";
|
||||
import type { ResolvedBuildConfig } from "./builder.ts";
|
||||
|
||||
Deno.test({
|
||||
name: "MemoryBuildCache - should error if reading outside of staticDir",
|
||||
fn: async () => {
|
||||
await using _tmp = await withTmpDir();
|
||||
const tmp = _tmp.dir;
|
||||
const config: ResolvedBuildConfig = {
|
||||
root: tmp,
|
||||
mode: "development",
|
||||
buildId: "",
|
||||
ignore: [],
|
||||
islandDir: "",
|
||||
outDir: "",
|
||||
routeDir: "",
|
||||
staticDir: "",
|
||||
target: "latest",
|
||||
};
|
||||
const fileTransformer = new FileTransformer(createFakeFs({}), tmp);
|
||||
const buildCache = new MemoryBuildCache(
|
||||
config,
|
||||
{ dir: "", files: [], id: "" },
|
||||
fileTransformer,
|
||||
);
|
||||
|
||||
const thrown = buildCache.readFile("../SECRETS.txt");
|
||||
const thrown2 = buildCache.readFile("./../../SECRETS.txt");
|
||||
const noThrown = buildCache.readFile("styles.css");
|
||||
const noThrown2 = buildCache.readFile(".well-known/foo.txt");
|
||||
const noThrown3 = buildCache.readFile("./styles.css");
|
||||
const noThrown4 = buildCache.readFile("./.well-known/foo.txt");
|
||||
await buildCache.flush();
|
||||
|
||||
const err = "Processed file resolved outside of static dir";
|
||||
await expect(thrown).rejects.toThrow(err);
|
||||
await expect(thrown2).rejects.toThrow(err);
|
||||
await expect(noThrown).resolves.toBe(null);
|
||||
await expect(noThrown2).resolves.toBe(null);
|
||||
await expect(noThrown3).resolves.toBe(null);
|
||||
await expect(noThrown4).resolves.toBe(null);
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,236 @@
|
||||
import { denoPlugin } from "@deno/esbuild-plugin";
|
||||
import type { BuildOptions, Plugin as EsbuildPlugin } from "esbuild";
|
||||
import * as path from "@std/path";
|
||||
|
||||
export interface FreshBundleOptions {
|
||||
dev: boolean;
|
||||
cwd: string;
|
||||
buildId: string;
|
||||
outDir: string;
|
||||
denoJsonPath: string;
|
||||
entryPoints: Record<string, string>;
|
||||
target: string | string[];
|
||||
jsxImportSource?: string;
|
||||
sourceMap?: {
|
||||
/** Documentation: https://esbuild.github.io/api/#sourcemap */
|
||||
kind: BuildOptions["sourcemap"];
|
||||
/** Documentation: https://esbuild.github.io/api/#source-root */
|
||||
sourceRoot?: BuildOptions["sourceRoot"];
|
||||
/** Documentation: https://esbuild.github.io/api/#sources-content */
|
||||
sourcesContent?: BuildOptions["sourcesContent"];
|
||||
};
|
||||
}
|
||||
|
||||
export interface BuildOutput {
|
||||
entryToChunk: Map<string, string>;
|
||||
dependencies: Map<string, string[]>;
|
||||
files: Array<{ hash: string | null; contents: Uint8Array; path: string }>;
|
||||
}
|
||||
|
||||
let esbuild: null | typeof import("esbuild") = null;
|
||||
|
||||
const PREACT_ENV = Deno.env.get("PREACT_PATH");
|
||||
|
||||
export async function bundleJs(
|
||||
options: FreshBundleOptions,
|
||||
): Promise<BuildOutput> {
|
||||
if (esbuild === null) {
|
||||
await startEsbuild();
|
||||
}
|
||||
|
||||
try {
|
||||
await Deno.mkdir(options.cwd, { recursive: true });
|
||||
} catch (err) {
|
||||
if (!(err instanceof Deno.errors.AlreadyExists)) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
const bundle = await esbuild!.build({
|
||||
entryPoints: options.entryPoints,
|
||||
|
||||
platform: "browser",
|
||||
target: options.target,
|
||||
|
||||
format: "esm",
|
||||
bundle: true,
|
||||
splitting: true,
|
||||
treeShaking: true,
|
||||
sourcemap: options.dev ? "linked" : options.sourceMap?.kind,
|
||||
sourceRoot: options.dev ? undefined : options.sourceMap?.sourceRoot,
|
||||
sourcesContent: options.dev ? undefined : options.sourceMap?.sourcesContent,
|
||||
minify: !options.dev,
|
||||
logOverride: {
|
||||
"suspicious-nullish-coalescing": "silent",
|
||||
"unsupported-jsx-comment": "silent",
|
||||
},
|
||||
|
||||
jsxDev: options.dev,
|
||||
jsx: "automatic",
|
||||
jsxImportSource: options.jsxImportSource ?? "preact",
|
||||
|
||||
absWorkingDir: options.cwd,
|
||||
outdir: ".",
|
||||
write: false,
|
||||
metafile: true,
|
||||
|
||||
define: {
|
||||
"process.env.NODE_ENV": JSON.stringify(
|
||||
options.dev ? "development" : "production",
|
||||
),
|
||||
},
|
||||
|
||||
plugins: [
|
||||
preactDebugger(PREACT_ENV),
|
||||
buildIdPlugin(options.buildId),
|
||||
windowsPathFixer(),
|
||||
denoPlugin({ preserveJsx: true, debug: false }),
|
||||
],
|
||||
});
|
||||
|
||||
const files: BuildOutput["files"] = [];
|
||||
for (let i = 0; i < bundle.outputFiles.length; i++) {
|
||||
const outputFile = bundle.outputFiles[i];
|
||||
const relative = path.relative(options.cwd, outputFile.path);
|
||||
files.push({
|
||||
path: relative,
|
||||
contents: outputFile.contents,
|
||||
hash: outputFile.hash,
|
||||
});
|
||||
}
|
||||
|
||||
files.push({
|
||||
path: "metafile.json",
|
||||
contents: new TextEncoder().encode(JSON.stringify(bundle.metafile)),
|
||||
hash: null,
|
||||
});
|
||||
|
||||
const entryToChunk = new Map<string, string>();
|
||||
const dependencies = new Map<string, string[]>();
|
||||
|
||||
const entryToName = new Map(
|
||||
Array.from(Object.entries(options.entryPoints)).map(
|
||||
(entry) => [entry[1], entry[0]],
|
||||
),
|
||||
);
|
||||
|
||||
if (bundle.metafile) {
|
||||
const metaOutputs = new Map(Object.entries(bundle.metafile.outputs));
|
||||
|
||||
for (const [entryPath, entry] of metaOutputs.entries()) {
|
||||
const imports = entry.imports
|
||||
.filter(({ kind }) => kind === "import-statement")
|
||||
.map(({ path }) => path);
|
||||
dependencies.set(entryPath, imports);
|
||||
|
||||
// Map entries to chunks
|
||||
if (entryPath !== "fresh-runtime.js" && entry.entryPoint !== undefined) {
|
||||
const basename = path.basename(
|
||||
entryPath,
|
||||
path.extname(entryPath),
|
||||
);
|
||||
|
||||
const filePath = options.entryPoints[basename];
|
||||
|
||||
const name = entryToName.get(filePath)!;
|
||||
entryToChunk.set(name, entryPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!options.dev) {
|
||||
esbuild = null;
|
||||
}
|
||||
|
||||
return {
|
||||
files,
|
||||
entryToChunk,
|
||||
dependencies,
|
||||
};
|
||||
}
|
||||
|
||||
let initialized = false;
|
||||
|
||||
export async function startEsbuild() {
|
||||
esbuild = Deno.env.get("FRESH_ESBUILD_LOADER") === "portable"
|
||||
? await import("esbuild-wasm")
|
||||
: await import("esbuild");
|
||||
|
||||
if (!initialized) {
|
||||
await esbuild.initialize({});
|
||||
initialized = true;
|
||||
}
|
||||
}
|
||||
|
||||
function buildIdPlugin(buildId: string): EsbuildPlugin {
|
||||
return {
|
||||
name: "fresh-build-id",
|
||||
setup(build) {
|
||||
build.onResolve({ filter: /^(jsr:)?@fresh\/build-id(@.*)?$/ }, (args) => {
|
||||
return {
|
||||
path: args.path,
|
||||
namespace: "fresh-internal",
|
||||
};
|
||||
});
|
||||
build.onLoad({
|
||||
filter: /^(jsr:)?@fresh\/build-id$/,
|
||||
namespace: "fresh-internal",
|
||||
}, () => {
|
||||
return {
|
||||
contents: `export const BUILD_ID = "${buildId}";`,
|
||||
};
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function toPreactModPath(mod: string): string {
|
||||
if (mod === "preact/debug") {
|
||||
return path.join("debug", "dist", "debug.module.js");
|
||||
} else if (mod === "preact/hooks") {
|
||||
return path.join("hooks", "dist", "hooks.module.js");
|
||||
} else if (mod === "preact/devtools") {
|
||||
return path.join("devtools", "dist", "devtools.module.js");
|
||||
} else if (mod === "preact/compat") {
|
||||
return path.join("compat", "dist", "compat.module.js");
|
||||
} else if (mod === "preact/jsx-runtime" || mod === "preact/jsx-dev-runtime") {
|
||||
return path.join("jsx-runtime", "dist", "jsxRuntime.module.js");
|
||||
} else {
|
||||
return path.join("dist", "preact.module.js");
|
||||
}
|
||||
}
|
||||
|
||||
function preactDebugger(preactPath: string | undefined): EsbuildPlugin {
|
||||
return {
|
||||
name: "fresh-preact-debugger",
|
||||
setup(build) {
|
||||
if (preactPath === undefined) return;
|
||||
|
||||
build.onResolve({ filter: /^preact/ }, (args) => {
|
||||
const resolved = path.resolve(preactPath, toPreactModPath(args.path));
|
||||
|
||||
return {
|
||||
path: resolved,
|
||||
};
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function windowsPathFixer(): EsbuildPlugin {
|
||||
return {
|
||||
name: "fresh-fix-windows",
|
||||
setup(build) {
|
||||
if (Deno.build.os === "windows") {
|
||||
build.onResolve({ filter: /\.*/ }, (args) => {
|
||||
if (args.path.startsWith("\\")) {
|
||||
const normalized = path.resolve(args.path);
|
||||
return {
|
||||
path: normalized,
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
import { globToRegExp, isGlob } from "@std/path";
|
||||
import type { FsAdapter } from "../fs.ts";
|
||||
import { BUILD_ID } from "@fresh/build-id";
|
||||
import { assetInternal } from "../runtime/shared_internal.tsx";
|
||||
|
||||
export type TransformMode = "development" | "production";
|
||||
|
||||
export interface OnTransformOptions {
|
||||
pluginName: string;
|
||||
filter: RegExp;
|
||||
exclude?: Array<string | RegExp>;
|
||||
}
|
||||
|
||||
export interface OnTransformResult {
|
||||
content: string | Uint8Array;
|
||||
path?: string;
|
||||
map?: string | Uint8Array;
|
||||
}
|
||||
|
||||
export interface OnTransformArgs {
|
||||
path: string;
|
||||
target: string | string[];
|
||||
text: string;
|
||||
content: Uint8Array;
|
||||
mode: TransformMode;
|
||||
root: string;
|
||||
}
|
||||
export type TransformFn = (
|
||||
args: OnTransformArgs,
|
||||
) =>
|
||||
| void
|
||||
| OnTransformResult
|
||||
| Array<{ path: string } & Omit<OnTransformResult, "path">>
|
||||
| Promise<
|
||||
| void
|
||||
| OnTransformResult
|
||||
| Array<{ path: string } & Omit<OnTransformResult, "path">>
|
||||
>;
|
||||
|
||||
export interface Transformer {
|
||||
options: OnTransformOptions;
|
||||
fn: TransformFn;
|
||||
}
|
||||
|
||||
export interface ProcessedFile {
|
||||
path: string;
|
||||
content: Uint8Array;
|
||||
map: Uint8Array | null;
|
||||
inputFiles: string[];
|
||||
}
|
||||
|
||||
interface TransformReq {
|
||||
newFile: boolean;
|
||||
filePath: string;
|
||||
content: Uint8Array;
|
||||
map: null | Uint8Array;
|
||||
inputFiles: string[];
|
||||
}
|
||||
|
||||
export class FileTransformer {
|
||||
#transformers: Transformer[] = [];
|
||||
#fs: FsAdapter;
|
||||
#root: string;
|
||||
|
||||
constructor(fs: FsAdapter, root: string) {
|
||||
this.#fs = fs;
|
||||
this.#root = root;
|
||||
}
|
||||
|
||||
onTransform(options: OnTransformOptions, callback: TransformFn): void {
|
||||
this.#transformers.push({ options, fn: callback });
|
||||
}
|
||||
|
||||
async process(
|
||||
filePath: string,
|
||||
mode: TransformMode,
|
||||
target: string | string[],
|
||||
): Promise<ProcessedFile[] | null> {
|
||||
// Pre-check if we have any transformer for this file at all
|
||||
let hasTransformer = false;
|
||||
for (let i = 0; i < this.#transformers.length; i++) {
|
||||
if (this.#transformers[i].options.filter.test(filePath)) {
|
||||
hasTransformer = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasTransformer) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let content: Uint8Array;
|
||||
try {
|
||||
content = await this.#fs.readFile(filePath);
|
||||
} catch (err) {
|
||||
if (err instanceof Deno.errors.NotFound) {
|
||||
return null;
|
||||
}
|
||||
|
||||
throw err;
|
||||
}
|
||||
|
||||
const queue: TransformReq[] = [{
|
||||
newFile: false,
|
||||
content,
|
||||
filePath,
|
||||
map: null,
|
||||
inputFiles: [filePath],
|
||||
}];
|
||||
const outFiles: ProcessedFile[] = [];
|
||||
|
||||
const seen = new Set<string>();
|
||||
|
||||
let req: TransformReq | undefined = undefined;
|
||||
while ((req = queue.pop()) !== undefined) {
|
||||
if (seen.has(req.filePath)) continue;
|
||||
seen.add(req.filePath);
|
||||
|
||||
let transformed = false;
|
||||
outer: for (let i = 0; i < this.#transformers.length; i++) {
|
||||
const transformer = this.#transformers[i];
|
||||
|
||||
const { options, fn } = transformer;
|
||||
options.filter.lastIndex = 0;
|
||||
if (!options.filter.test(req.filePath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check if file is excluded
|
||||
if (options.exclude !== undefined) {
|
||||
for (let j = 0; j < options.exclude.length; j++) {
|
||||
const exclude = options.exclude[j];
|
||||
if (exclude instanceof RegExp) {
|
||||
if (exclude.test(filePath)) {
|
||||
continue outer;
|
||||
}
|
||||
} else if (isGlob(exclude)) {
|
||||
const regex = globToRegExp(exclude);
|
||||
if (regex.test(filePath)) {
|
||||
continue outer;
|
||||
}
|
||||
} else if (filePath.includes(exclude)) {
|
||||
continue outer;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const result = await fn({
|
||||
path: req.filePath,
|
||||
mode,
|
||||
target,
|
||||
content: req!.content,
|
||||
root: this.#root,
|
||||
get text() {
|
||||
return new TextDecoder().decode(req!.content);
|
||||
},
|
||||
});
|
||||
|
||||
if (result !== undefined) {
|
||||
if (Array.isArray(result)) {
|
||||
for (let i = 0; i < result.length; i++) {
|
||||
const item = result[i];
|
||||
if (item.path === undefined) {
|
||||
throw new Error(
|
||||
`The ".path" property must be set when returning multiple files in a transformer. [${transformer.options.pluginName}]`,
|
||||
);
|
||||
}
|
||||
|
||||
const outContent = typeof item.content === "string"
|
||||
? new TextEncoder().encode(item.content)
|
||||
: item.content;
|
||||
|
||||
const outMap = item.map !== undefined
|
||||
? typeof item.map === "string"
|
||||
? new TextEncoder().encode(item.map)
|
||||
: item.map
|
||||
: null;
|
||||
|
||||
if (req.filePath === item.path) {
|
||||
if (req.content === outContent && req.map === outMap) {
|
||||
continue;
|
||||
}
|
||||
|
||||
transformed = true;
|
||||
req.content = outContent;
|
||||
req.map = outMap;
|
||||
} else {
|
||||
let found = false;
|
||||
for (let i = 0; i < queue.length; i++) {
|
||||
const req = queue[i];
|
||||
if (req.filePath === item.path) {
|
||||
found = true;
|
||||
transformed = true;
|
||||
req.content = outContent;
|
||||
req.map = outMap;
|
||||
}
|
||||
}
|
||||
|
||||
if (!found) {
|
||||
queue.push({
|
||||
newFile: true,
|
||||
filePath: item.path,
|
||||
content: outContent,
|
||||
map: outMap,
|
||||
inputFiles: req.inputFiles.slice(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const outContent = typeof result.content === "string"
|
||||
? new TextEncoder().encode(result.content)
|
||||
: result.content;
|
||||
|
||||
const outMap = result.map !== undefined
|
||||
? typeof result.map === "string"
|
||||
? new TextEncoder().encode(result.map)
|
||||
: result.map
|
||||
: null;
|
||||
|
||||
if (req.content === outContent && req.map === outMap) {
|
||||
continue;
|
||||
}
|
||||
|
||||
transformed = true;
|
||||
req.content = outContent;
|
||||
req.map = outMap;
|
||||
req.filePath = result.path ?? req.filePath;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Keep transforming until no one processes anymore
|
||||
if (transformed || req.newFile) {
|
||||
outFiles.push({
|
||||
content: req.content,
|
||||
map: req.map,
|
||||
path: req.filePath,
|
||||
inputFiles: req.inputFiles,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return outFiles.length > 0 ? outFiles : null;
|
||||
}
|
||||
}
|
||||
|
||||
const CSS_URL_REGEX = /url\(("[^"]+"|'[^']+'|[^)]+)\)/g;
|
||||
|
||||
export function cssAssetHash(transformer: FileTransformer) {
|
||||
transformer.onTransform({
|
||||
pluginName: "fresh-css",
|
||||
filter: /\.css$/,
|
||||
}, (args) => {
|
||||
const replaced = args.text.replaceAll(CSS_URL_REGEX, (_, str) => {
|
||||
let rawUrl = str;
|
||||
if (str[0] === "'" || str[0] === '"') {
|
||||
rawUrl = str.slice(1, -1);
|
||||
}
|
||||
|
||||
if (rawUrl.length === 0) {
|
||||
return str;
|
||||
}
|
||||
|
||||
return `url(${JSON.stringify(assetInternal(rawUrl, BUILD_ID))})`;
|
||||
});
|
||||
|
||||
return {
|
||||
content: replaced,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
import { expect } from "@std/expect";
|
||||
import type { FsAdapter } from "../fs.ts";
|
||||
import { FileTransformer, type ProcessedFile } from "./file_transformer.ts";
|
||||
import { delay } from "../test_utils.ts";
|
||||
|
||||
function testTransformer(files: Record<string, string>, root = "/") {
|
||||
const mockFs: FsAdapter = {
|
||||
cwd: () => root,
|
||||
isDirectory: () => Promise.resolve(false),
|
||||
mkdirp: () => Promise.resolve(),
|
||||
walk: async function* foo() {
|
||||
},
|
||||
readFile: (file) => {
|
||||
if (file instanceof URL) throw new Error("Not supported");
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const content = (files as any)[file];
|
||||
const buf = new TextEncoder().encode(content);
|
||||
return Promise.resolve(buf);
|
||||
},
|
||||
readTextFile: (file) => {
|
||||
if (file instanceof URL) throw new Error("Not supported");
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const content = (files as any)[file];
|
||||
return Promise.resolve(content);
|
||||
},
|
||||
};
|
||||
return new FileTransformer(mockFs, root);
|
||||
}
|
||||
|
||||
function consumeResult(result: ProcessedFile[]) {
|
||||
const out: {
|
||||
path: string;
|
||||
content: string;
|
||||
map: string | null;
|
||||
inputFiles: string[];
|
||||
}[] = [];
|
||||
for (let i = 0; i < result.length; i++) {
|
||||
const file = result[i];
|
||||
|
||||
out.push({
|
||||
path: file.path,
|
||||
content: typeof file.content === "string"
|
||||
? file.content
|
||||
: new TextDecoder().decode(file.content),
|
||||
map: file.map !== null
|
||||
? typeof file.map === "string"
|
||||
? file.map
|
||||
: new TextDecoder().decode(file.map)
|
||||
: null,
|
||||
inputFiles: file.inputFiles,
|
||||
});
|
||||
}
|
||||
|
||||
return out.sort((a, b) => a.path.localeCompare(b.path));
|
||||
}
|
||||
|
||||
Deno.test("FileTransformer - transform sync", async () => {
|
||||
const transformer = testTransformer({
|
||||
"foo.txt": "foo",
|
||||
});
|
||||
|
||||
transformer.onTransform({ pluginName: "foo", filter: /.*/ }, (args) => {
|
||||
return {
|
||||
content: args.text + "bar",
|
||||
};
|
||||
});
|
||||
|
||||
const result = await transformer.process("foo.txt", "development", "");
|
||||
const files = await consumeResult(result!);
|
||||
expect(files).toEqual([
|
||||
{ content: "foobar", map: null, path: "foo.txt", inputFiles: ["foo.txt"] },
|
||||
]);
|
||||
});
|
||||
|
||||
Deno.test("FileTransformer - transform async", async () => {
|
||||
const transformer = testTransformer({
|
||||
"foo.txt": "foo",
|
||||
});
|
||||
|
||||
transformer.onTransform({ pluginName: "foo", filter: /.*/ }, async (args) => {
|
||||
await delay(1);
|
||||
return {
|
||||
content: args.text + "bar",
|
||||
};
|
||||
});
|
||||
|
||||
const result = await transformer.process("foo.txt", "development", "");
|
||||
const files = await consumeResult(result!);
|
||||
expect(files).toEqual([
|
||||
{ content: "foobar", map: null, path: "foo.txt", inputFiles: ["foo.txt"] },
|
||||
]);
|
||||
});
|
||||
|
||||
Deno.test("FileTransformer - transform return Uint8Array", async () => {
|
||||
const transformer = testTransformer({
|
||||
"foo.txt": "foo",
|
||||
});
|
||||
|
||||
transformer.onTransform({ pluginName: "foo", filter: /.*/ }, () => {
|
||||
return {
|
||||
content: new TextEncoder().encode("foobar"),
|
||||
};
|
||||
});
|
||||
|
||||
const result = await transformer.process("foo.txt", "development", "");
|
||||
const files = await consumeResult(result!);
|
||||
expect(files).toEqual([
|
||||
{ content: "foobar", map: null, path: "foo.txt", inputFiles: ["foo.txt"] },
|
||||
]);
|
||||
});
|
||||
|
||||
Deno.test("FileTransformer - pass transformed content", async () => {
|
||||
const transformer = testTransformer({
|
||||
"input.txt": "input",
|
||||
});
|
||||
|
||||
transformer.onTransform({ pluginName: "A", filter: /.*/ }, (args) => {
|
||||
return {
|
||||
content: args.text + " -> A",
|
||||
};
|
||||
});
|
||||
transformer.onTransform({ pluginName: "B", filter: /.*/ }, (args) => {
|
||||
return {
|
||||
content: args.text + " -> B",
|
||||
};
|
||||
});
|
||||
|
||||
const result = await transformer.process("input.txt", "development", "");
|
||||
const files = await consumeResult(result!);
|
||||
expect(files).toEqual([
|
||||
{
|
||||
content: "input -> A -> B",
|
||||
map: null,
|
||||
path: "input.txt",
|
||||
inputFiles: ["input.txt"],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
Deno.test(
|
||||
"FileTransformer - pass transformed content with multiple",
|
||||
async () => {
|
||||
const transformer = testTransformer({
|
||||
"input.txt": "input",
|
||||
});
|
||||
|
||||
transformer.onTransform({ pluginName: "A", filter: /.*/ }, (args) => {
|
||||
return [{
|
||||
path: args.path,
|
||||
content: args.text + " -> A",
|
||||
}];
|
||||
});
|
||||
transformer.onTransform({ pluginName: "B", filter: /.*/ }, (args) => {
|
||||
return {
|
||||
content: args.text + " -> B",
|
||||
};
|
||||
});
|
||||
|
||||
const result = await transformer.process("input.txt", "development", "");
|
||||
const files = await consumeResult(result!);
|
||||
expect(files).toEqual([
|
||||
{
|
||||
content: "input -> A -> B",
|
||||
map: null,
|
||||
path: "input.txt",
|
||||
inputFiles: ["input.txt"],
|
||||
},
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
Deno.test("FileTransformer - return multiple results", async () => {
|
||||
const transformer = testTransformer({
|
||||
"foo.txt": "foo",
|
||||
});
|
||||
|
||||
const received: string[] = [];
|
||||
transformer.onTransform({ pluginName: "A", filter: /foo\.txt$/ }, () => {
|
||||
return [{
|
||||
path: "a.txt",
|
||||
content: "A",
|
||||
}, {
|
||||
path: "b.txt",
|
||||
content: "B",
|
||||
}];
|
||||
});
|
||||
transformer.onTransform({ pluginName: "B", filter: /.*/ }, (args) => {
|
||||
received.push(args.path);
|
||||
});
|
||||
|
||||
const result = await transformer.process("foo.txt", "development", "");
|
||||
const files = await consumeResult(result!);
|
||||
expect(files).toEqual([
|
||||
{ content: "A", map: null, path: "a.txt", inputFiles: ["foo.txt"] },
|
||||
{ content: "B", map: null, path: "b.txt", inputFiles: ["foo.txt"] },
|
||||
]);
|
||||
expect(received).toEqual(["foo.txt", "b.txt", "a.txt"]);
|
||||
});
|
||||
|
||||
Deno.test(
|
||||
"FileTransformer - track input files through temporary results",
|
||||
async () => {
|
||||
const transformer = testTransformer({
|
||||
"foo.txt": "foo",
|
||||
});
|
||||
|
||||
transformer.onTransform({ pluginName: "A", filter: /foo\.txt$/ }, () => {
|
||||
return [{
|
||||
path: "a.txt",
|
||||
content: "A",
|
||||
}, {
|
||||
path: "b.txt",
|
||||
content: "B",
|
||||
}];
|
||||
});
|
||||
transformer.onTransform(
|
||||
{ pluginName: "B", filter: /[ab]\.txt$/ },
|
||||
(args) => {
|
||||
return {
|
||||
path: "c" + args.path,
|
||||
content: args.text + "C",
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
const result = await transformer.process("foo.txt", "development", "");
|
||||
const files = await consumeResult(result!);
|
||||
expect(files).toEqual([
|
||||
{ content: "AC", map: null, path: "ca.txt", inputFiles: ["foo.txt"] },
|
||||
{ content: "BC", map: null, path: "cb.txt", inputFiles: ["foo.txt"] },
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
Deno.test("FileTransformer - pass root to args", async () => {
|
||||
const transformer = testTransformer({ "foo.txt": "foo" }, "/<root>/");
|
||||
|
||||
let root = "";
|
||||
transformer.onTransform({ pluginName: "A", filter: /.*/ }, (args) => {
|
||||
root = args.root;
|
||||
return undefined;
|
||||
});
|
||||
|
||||
await transformer.process("foo.txt", "development", "");
|
||||
|
||||
expect(root).toEqual("/<root>/");
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
import { type FsAdapter, fsAdapter } from "../fs.ts";
|
||||
import type { WalkEntry } from "@std/fs/walk";
|
||||
import type { FsRouteFileNoMod } from "./dev_build_cache.ts";
|
||||
import * as path from "@std/path";
|
||||
import { pathToPattern } from "../router.ts";
|
||||
import { CommandType } from "../commands.ts";
|
||||
import { sortRoutePaths } from "../fs_routes.ts";
|
||||
import type { RouteConfig } from "../types.ts";
|
||||
|
||||
const GROUP_REG = /[/\\\\]\((_[^/\\\\]+)\)[/\\\\]/;
|
||||
|
||||
export async function crawlRouteDir<State>(
|
||||
fs: FsAdapter,
|
||||
routeDir: string,
|
||||
ignore: RegExp[],
|
||||
onIslandSpecifier: (spec: string) => void,
|
||||
): Promise<FsRouteFileNoMod<State>[]> {
|
||||
const files: FsRouteFileNoMod<State>[] = [];
|
||||
|
||||
await walkDir(fs, routeDir, async (entry) => {
|
||||
// A `(_islands)` path segment is a local island folder.
|
||||
// Any route path segment wrapped in `(_...)` is ignored
|
||||
// during route collection.
|
||||
const match = entry.path.match(GROUP_REG);
|
||||
if (match !== null) {
|
||||
if (match[1] === "_islands") {
|
||||
onIslandSpecifier(entry.path);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let lazy = false;
|
||||
const relative = path.relative(routeDir, entry.path);
|
||||
const url = new URL(relative, "http://localhost/");
|
||||
const id = url.pathname.slice(0, url.pathname.lastIndexOf("."));
|
||||
|
||||
let overrideConfig: RouteConfig | undefined;
|
||||
let pattern = "*";
|
||||
let routePattern = pattern;
|
||||
let type = CommandType.Route;
|
||||
if (id.endsWith("/_middleware")) {
|
||||
type = CommandType.Middleware;
|
||||
pattern = pathToPattern(
|
||||
id.slice(1, -"/_middleware".length),
|
||||
{ keepGroups: true },
|
||||
);
|
||||
routePattern = pattern;
|
||||
} else if (id.endsWith("/_layout")) {
|
||||
type = CommandType.Layout;
|
||||
pattern = pathToPattern(
|
||||
id.slice(1, -"/_layout".length),
|
||||
{ keepGroups: true },
|
||||
);
|
||||
routePattern = pattern;
|
||||
} else if (id.endsWith("/_app")) {
|
||||
type = CommandType.App;
|
||||
} else if (id.endsWith("/_404")) {
|
||||
type = CommandType.NotFound;
|
||||
} else if (id.endsWith("/_error") || id.endsWith("/_500")) {
|
||||
type = CommandType.Error;
|
||||
pattern = pathToPattern(
|
||||
id.slice(1, -"/_error".length),
|
||||
{ keepGroups: true },
|
||||
);
|
||||
routePattern = pattern;
|
||||
} else {
|
||||
pattern = pathToPattern(id.slice(1), { keepGroups: true });
|
||||
if (id.endsWith("/index")) {
|
||||
if (!pattern.endsWith("/")) {
|
||||
pattern += "/";
|
||||
}
|
||||
}
|
||||
|
||||
routePattern = pathToPattern(id.slice(1));
|
||||
|
||||
const code = await fs.readTextFile(entry.path);
|
||||
lazy = !code.includes("routeOverride");
|
||||
|
||||
// TODO: We could do an AST parse here to detect the
|
||||
// kind of handler that's used to get a more accurate
|
||||
// list of methods this route supports.
|
||||
overrideConfig = {
|
||||
methods: "ALL",
|
||||
};
|
||||
}
|
||||
|
||||
files.push({
|
||||
id,
|
||||
filePath: entry.path,
|
||||
type,
|
||||
pattern,
|
||||
routePattern,
|
||||
lazy,
|
||||
overrideConfig,
|
||||
});
|
||||
}, ignore);
|
||||
|
||||
files.sort((a, b) => sortRoutePaths(a.id, b.id));
|
||||
|
||||
return files;
|
||||
}
|
||||
|
||||
export async function walkDir(
|
||||
fs: FsAdapter,
|
||||
dir: string,
|
||||
callback: (entry: WalkEntry) => void | Promise<void>,
|
||||
ignore: RegExp[],
|
||||
) {
|
||||
if (!await fs.isDirectory(dir)) return;
|
||||
|
||||
const entries = fs.walk(dir, {
|
||||
includeDirs: false,
|
||||
includeFiles: true,
|
||||
exts: ["tsx", "jsx", "ts", "js"],
|
||||
skip: ignore,
|
||||
});
|
||||
|
||||
for await (const entry of entries) {
|
||||
await callback(entry);
|
||||
}
|
||||
}
|
||||
|
||||
export async function crawlFsItem(
|
||||
options: { islandDir: string; routeDir: string; ignore: RegExp[] },
|
||||
): Promise<{ islands: string[]; routes: FsRouteFileNoMod<unknown>[] }> {
|
||||
const islands: string[] = [];
|
||||
|
||||
const [, routes] = await Promise.all([
|
||||
walkDir(
|
||||
fsAdapter,
|
||||
options.islandDir,
|
||||
(entry) => {
|
||||
islands.push(entry.path);
|
||||
},
|
||||
options.ignore,
|
||||
),
|
||||
crawlRouteDir(
|
||||
fsAdapter,
|
||||
options.routeDir,
|
||||
options.ignore,
|
||||
(entry) => islands.push(entry),
|
||||
),
|
||||
]);
|
||||
|
||||
return { islands, routes };
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { expect } from "@std/expect/expect";
|
||||
import { createFakeFs } from "../test_utils.ts";
|
||||
import { walkDir } from "./fs_crawl.ts";
|
||||
|
||||
Deno.test("walkDir - ", async () => {
|
||||
const fs = createFakeFs({
|
||||
"foo/bar/baz.txt": "foo",
|
||||
"foo/bar.txt": "foo",
|
||||
});
|
||||
|
||||
const files: string[] = [];
|
||||
|
||||
await walkDir(fs, "foo", async (entry) => {
|
||||
// Purposely delay
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
files.push(entry.path);
|
||||
}, []);
|
||||
|
||||
expect(files).toEqual(["foo/bar/baz.txt", "foo/bar.txt"]);
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import { eTag, ifNoneMatch } from "@std/http/etag";
|
||||
import { generate } from "@std/uuid/v5";
|
||||
import { NAMESPACE_URL } from "@std/uuid/constants";
|
||||
import type { Middleware } from "../../middlewares/mod.ts";
|
||||
|
||||
/**
|
||||
* Automatically detects workspace folders for DevTools in Chromium browsers.
|
||||
*
|
||||
* Without this middleware, if the feature is enabled and devTools is opened
|
||||
* there will be 404 errors in the console. This can be annoying for developers,
|
||||
* especially if there is logging for incoming requests.
|
||||
*
|
||||
* Enabling this feature can be helpful to make edits in DevTools change source
|
||||
* files directly, for a small amount of code.
|
||||
*
|
||||
* The UUID is generated with a UUIDv5, so that the same directory should
|
||||
* always generate the same UUID. This way, we can preserve the connected
|
||||
* workspace across reloads without writing anything to disk.
|
||||
*
|
||||
* @see https://chromium.googlesource.com/devtools/devtools-frontend/+/main/docs/ecosystem/automatic_workspace_folders.md
|
||||
*/
|
||||
export function automaticWorkspaceFolders<T>(root: string): Middleware<T> {
|
||||
let uuid: string | undefined;
|
||||
let etag: string | undefined;
|
||||
let content: string | undefined;
|
||||
|
||||
return async (ctx) => {
|
||||
const { pathname } = ctx.url;
|
||||
|
||||
if (pathname !== "/.well-known/appspecific/com.chrome.devtools.json") {
|
||||
return ctx.next();
|
||||
}
|
||||
|
||||
uuid ??= await generate(
|
||||
NAMESPACE_URL,
|
||||
new TextEncoder().encode(
|
||||
`https://fresh.deno.dev?root=${encodeURIComponent(root)}&v=${0}`,
|
||||
),
|
||||
);
|
||||
content ??= JSON.stringify({ workspace: { root, uuid } }, undefined, 2);
|
||||
etag ??= await eTag(content);
|
||||
|
||||
const noneMatchValue = ctx.req.headers.get("if-none-match");
|
||||
if (!ifNoneMatch(noneMatchValue, etag)) {
|
||||
return new Response(undefined, { status: 304, headers: { etag } });
|
||||
}
|
||||
return new Response(content, { status: 200, headers: { etag } });
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import * as path from "@std/path";
|
||||
|
||||
function tabs2Spaces(str: string) {
|
||||
return str.replace(/^\t+/, (tabs) => " ".repeat(tabs.length));
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate an excerpt of the location in the source around the
|
||||
* specified position.
|
||||
*/
|
||||
export function createCodeFrame(
|
||||
text: string,
|
||||
lineNum: number,
|
||||
columnNum: number,
|
||||
): string | undefined {
|
||||
// Default settings
|
||||
const before = 2;
|
||||
const after = 3;
|
||||
|
||||
const lines = text.split("\n");
|
||||
|
||||
// Check if specified range is valid
|
||||
if (lines.length <= lineNum || lines[lineNum].length < columnNum) {
|
||||
return;
|
||||
}
|
||||
|
||||
const start = Math.max(0, lineNum - before);
|
||||
const end = Math.min(lines.length, lineNum + after + 1);
|
||||
|
||||
// Maximum space needed for line numbering in the current range.
|
||||
// Necessary when the amount of digits of the line numbering grows:
|
||||
// 999 | asdf
|
||||
// 1000 | asdjadfjsa
|
||||
const maxLineNum = String(end).length;
|
||||
const padding = " ".repeat(maxLineNum);
|
||||
|
||||
// Normalize all indentation (=tabs) to use 2 spaces. We need to
|
||||
// apply the difference to the marker position to move it back in
|
||||
// place.
|
||||
const spaceLines: string[] = [];
|
||||
let maxLineLen = 0;
|
||||
for (let i = start; i < end; i++) {
|
||||
const line = tabs2Spaces(lines[i]);
|
||||
spaceLines.push(line);
|
||||
|
||||
if (line.length > maxLineLen) maxLineLen = line.length;
|
||||
}
|
||||
|
||||
const activeLine = spaceLines[lineNum - start];
|
||||
// Move marker into correct place by taking the amount of
|
||||
// normalized tabs into account
|
||||
const count = Math.max(
|
||||
0,
|
||||
activeLine.length - lines[lineNum].length + columnNum,
|
||||
);
|
||||
|
||||
const sep = "|";
|
||||
let out = "";
|
||||
|
||||
for (let i = 0; i < spaceLines.length; i++) {
|
||||
const line = spaceLines[i];
|
||||
const currentLine = (padding + (i + start + 1)).slice(-maxLineNum);
|
||||
|
||||
// Line where the error occurred
|
||||
if (i === lineNum - start) {
|
||||
out += ">" + ` ${currentLine} ${sep} ${line}\n`;
|
||||
|
||||
const columnMarker = "^";
|
||||
out += ` ${padding} ${sep} ${" ".repeat(count)}${columnMarker}\n`;
|
||||
} else {
|
||||
out += ` ${currentLine} ${sep} ${line}\n`;
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
const STACK_FRAME = /^\s*at\s+(?:(.*)\s+)?\((.*):(\d+):(\d+)\)$/;
|
||||
export interface StackFrame {
|
||||
fnName: string;
|
||||
file: string;
|
||||
line: number;
|
||||
column: number;
|
||||
}
|
||||
function getFirstUserFile(
|
||||
stack: string,
|
||||
rootDir: string,
|
||||
): StackFrame | undefined {
|
||||
const lines = stack.split("\n");
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const match = lines[i].match(STACK_FRAME);
|
||||
if (match) {
|
||||
const fnName = match[1] ?? "";
|
||||
const file = match[2];
|
||||
const line = +match[3];
|
||||
const column = +match[4];
|
||||
|
||||
if (file.startsWith("file://")) {
|
||||
const filePath = path.fromFileUrl(file);
|
||||
if (path.relative(rootDir, filePath).startsWith(".")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
return {
|
||||
fnName,
|
||||
file,
|
||||
line,
|
||||
column,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function getCodeFrame(stack: string, rootDir: string) {
|
||||
const file = getFirstUserFile(stack, rootDir);
|
||||
if (file) {
|
||||
try {
|
||||
const filePath = path.fromFileUrl(file.file);
|
||||
const text = Deno.readTextFileSync(filePath);
|
||||
return createCodeFrame(
|
||||
text,
|
||||
file.line - 1,
|
||||
file.column - 1,
|
||||
);
|
||||
} catch {
|
||||
// Ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { DEV_ERROR_OVERLAY_URL } from "../../../constants.ts";
|
||||
import { HttpError } from "../../../error.ts";
|
||||
import type { Middleware } from "../../../middlewares/mod.ts";
|
||||
import { FreshScripts } from "../../../runtime/server/preact_hooks.tsx";
|
||||
import { ErrorOverlay } from "./overlay.tsx";
|
||||
|
||||
export function devErrorOverlay<T>(): Middleware<T> {
|
||||
return async (ctx) => {
|
||||
const { config, url } = ctx;
|
||||
if (url.pathname === config.basePath + DEV_ERROR_OVERLAY_URL) {
|
||||
return ctx.render(<ErrorOverlay url={url} />);
|
||||
}
|
||||
|
||||
try {
|
||||
return await ctx.next();
|
||||
} catch (err) {
|
||||
if (ctx.req.headers.get("accept")?.includes("text/html")) {
|
||||
let init: ResponseInit | undefined;
|
||||
if (err instanceof HttpError) {
|
||||
if (err.status < 500) throw err;
|
||||
init = { status: err.status };
|
||||
}
|
||||
|
||||
// At this point we're pretty sure to have a server error
|
||||
// deno-lint-ignore no-console
|
||||
console.error(err);
|
||||
|
||||
return ctx.render(<FreshScripts />, init);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import { expect } from "@std/expect";
|
||||
import { App } from "../../../app.ts";
|
||||
import { FakeServer } from "../../../test_utils.ts";
|
||||
import { devErrorOverlay } from "./middleware.tsx";
|
||||
import { HttpError } from "../../../error.ts";
|
||||
|
||||
Deno.test("error overlay - show when error is thrown", async () => {
|
||||
const app = new App();
|
||||
app.use(devErrorOverlay());
|
||||
app.config.mode = "development";
|
||||
|
||||
app.get("/", () => {
|
||||
throw new Error("fail");
|
||||
});
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
const res = await server.get("/", {
|
||||
headers: {
|
||||
accept: "text/html",
|
||||
},
|
||||
});
|
||||
const content = await res.text();
|
||||
expect(content).toContain("fresh-error-overlay");
|
||||
});
|
||||
|
||||
Deno.test("error overlay - should not be visible for HttpError <500", async () => {
|
||||
const app = new App();
|
||||
app.use(devErrorOverlay());
|
||||
app.config.mode = "development";
|
||||
|
||||
app
|
||||
.get("/", () => {
|
||||
throw new HttpError(404);
|
||||
})
|
||||
.get("/500", () => {
|
||||
throw new HttpError(500);
|
||||
});
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
let res = await server.get("/", {
|
||||
headers: {
|
||||
accept: "text/html",
|
||||
},
|
||||
});
|
||||
let content = await res.text();
|
||||
expect(content).not.toContain("fresh-error-overlay");
|
||||
expect(res.status).toEqual(404);
|
||||
|
||||
res = await server.get("/500", {
|
||||
headers: {
|
||||
accept: "text/html",
|
||||
},
|
||||
});
|
||||
content = await res.text();
|
||||
expect(content).toContain("fresh-error-overlay");
|
||||
expect(res.status).toEqual(500);
|
||||
});
|
||||
|
||||
Deno.test(
|
||||
"error overlay - should not be visible for HttpError <500 #2",
|
||||
async () => {
|
||||
const app = new App();
|
||||
app.use(devErrorOverlay());
|
||||
app.config.mode = "development";
|
||||
app
|
||||
.use(async (ctx) => {
|
||||
try {
|
||||
return await ctx.next();
|
||||
} catch {
|
||||
return ctx.render(<p>ok</p>);
|
||||
}
|
||||
})
|
||||
.get("/", () => {
|
||||
throw new HttpError(404);
|
||||
});
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
const res = await server.get("/", {
|
||||
headers: {
|
||||
accept: "text/html",
|
||||
},
|
||||
});
|
||||
const content = await res.text();
|
||||
expect(content).not.toContain("fresh-error-overlay");
|
||||
},
|
||||
);
|
||||
|
||||
Deno.test("error overlay - should not be visible in prod", async () => {
|
||||
const app = new App({ mode: "production" });
|
||||
app.use(devErrorOverlay());
|
||||
|
||||
app.get("/", () => {
|
||||
throw new HttpError(500);
|
||||
});
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
const res = await server.get("/", {
|
||||
headers: {
|
||||
accept: "text/html",
|
||||
},
|
||||
});
|
||||
const content = await res.text();
|
||||
expect(content).not.toContain("fresh-error-overlay");
|
||||
expect(res.status).toEqual(500);
|
||||
});
|
||||
@@ -0,0 +1,177 @@
|
||||
import type { ComponentChildren } from "preact";
|
||||
|
||||
// Just to get some syntax highlighting
|
||||
const css = (arr: TemplateStringsArray, ...exts: never[]) => {
|
||||
if (exts.length) throw new Error("Not allowed");
|
||||
return arr[0];
|
||||
};
|
||||
|
||||
export const errorCss = css`
|
||||
:root {
|
||||
--bg: #fff;
|
||||
--bg-code-frame: rgb(255, 0, 32, 0.1);
|
||||
--bg-active-line: #fbcecc;
|
||||
--text: #222;
|
||||
--text2: #444;
|
||||
--title: #e84644;
|
||||
--code: #333;
|
||||
font-family: sans-serif;
|
||||
line-height: 1.4;
|
||||
color: var(--text);
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--bg-code-frame: rgba(251, 93, 113, 0.2);
|
||||
--bg-active-line: #4f1919;
|
||||
--bg: #353535;
|
||||
--text: #f7f7f7;
|
||||
--text2: #ddd;
|
||||
--code: #fdd1d1;
|
||||
}
|
||||
}
|
||||
|
||||
.inner {
|
||||
max-width: 48rem;
|
||||
padding: 4rem 1rem;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.title {
|
||||
color: var(--title);
|
||||
font-weight: normal;
|
||||
font-size: 1.5rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.code-frame {
|
||||
overflow: auto;
|
||||
padding: 0.5rem;
|
||||
margin-bottom: 0.5rem;
|
||||
background: var(--bg-code-frame);
|
||||
color: var(--code);
|
||||
}
|
||||
.line {
|
||||
padding: 0.25rem 0.5rem;
|
||||
}
|
||||
.active-line {
|
||||
display: inline-block;
|
||||
width: 100%;
|
||||
background: var(--bg-active-line);
|
||||
}
|
||||
|
||||
.stack {
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.close-btn {
|
||||
position: absolute;
|
||||
top: 1rem;
|
||||
right: 1rem;
|
||||
color: var(--title);
|
||||
display: block;
|
||||
width: 3rem;
|
||||
height: 3rem;
|
||||
background: none;
|
||||
border: none;
|
||||
transform: translate3d(0, 0, 0);
|
||||
}
|
||||
.close-btn:active {
|
||||
transform: translate3d(0, 2px, 0);
|
||||
}
|
||||
.close-btn:hover {
|
||||
cursor: pointer;
|
||||
filter: drop-shadow(0 0 0.75rem crimson);
|
||||
}
|
||||
`;
|
||||
|
||||
function CodeFrame(props: { codeFrame: string }) {
|
||||
const lines: ComponentChildren[] = [];
|
||||
|
||||
props.codeFrame.trimEnd().split("\n").forEach(
|
||||
(line, i, arr) => {
|
||||
const vnode = (
|
||||
<span
|
||||
class={"line" + (line.startsWith(">") ? " active-line" : "")}
|
||||
>
|
||||
{line}
|
||||
</span>
|
||||
);
|
||||
|
||||
lines.push(vnode);
|
||||
if (i < arr.length - 1) lines.push("\n");
|
||||
},
|
||||
);
|
||||
return (
|
||||
<pre class="code-frame">
|
||||
<code>{lines}</code>
|
||||
</pre>
|
||||
);
|
||||
}
|
||||
|
||||
const DEFAULT_MESSAGE = "Internal Server Error";
|
||||
|
||||
export function ErrorOverlay(props: { url: URL }) {
|
||||
const url = props.url;
|
||||
const title = url.searchParams.get("message") || DEFAULT_MESSAGE;
|
||||
const stack = url.searchParams.get("stack");
|
||||
const codeFrame = url.searchParams.get("code-frame");
|
||||
|
||||
if (title === DEFAULT_MESSAGE && !stack && !codeFrame) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div class="frsh-error-page">
|
||||
<style
|
||||
// deno-lint-ignore react-no-danger
|
||||
dangerouslySetInnerHTML={{ __html: errorCss }}
|
||||
/>
|
||||
<div class="inner">
|
||||
<div class="header">
|
||||
<button
|
||||
type="button"
|
||||
class="close-btn"
|
||||
aria-label="close"
|
||||
id="close-btn"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
strokeWidth={1.5}
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M9.75 9.75l4.5 4.5m0-4.5l-4.5 4.5M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<div>
|
||||
<h1 class="title">{title}</h1>
|
||||
{codeFrame ? <CodeFrame codeFrame={codeFrame} /> : null}
|
||||
{stack ? <pre class="stack">{stack}</pre> : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script
|
||||
// deno-lint-ignore react-no-danger
|
||||
dangerouslySetInnerHTML={{
|
||||
__html:
|
||||
`document.querySelector("#close-btn").addEventListener("click", () => parent.postMessage("close-error-overlay"));`,
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { Middleware } from "../../middlewares/mod.ts";
|
||||
import { ALIVE_URL } from "../../constants.ts";
|
||||
|
||||
// Live reload: Send updates to browser
|
||||
export function liveReload<T>(): Middleware<T> {
|
||||
const revision = Date.now();
|
||||
|
||||
return (ctx) => {
|
||||
const { config, req, url } = ctx;
|
||||
|
||||
const aliveUrl = config.basePath + ALIVE_URL;
|
||||
|
||||
if (url.pathname === aliveUrl) {
|
||||
if (req.headers.get("upgrade") !== "websocket") {
|
||||
return new Response(null, { status: 501 });
|
||||
}
|
||||
|
||||
// TODO: When a change is made the Deno server restarts,
|
||||
// so for now the WebSocket connection is only used for
|
||||
// the client to know when the server is back up. Once we
|
||||
// have HMR we'll actively start sending messages back
|
||||
// and forth.
|
||||
const { response, socket } = Deno.upgradeWebSocket(req);
|
||||
|
||||
socket.addEventListener("open", () => {
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: "initial-state",
|
||||
revision,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
return ctx.next();
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
export {
|
||||
Builder,
|
||||
type BuildOptions,
|
||||
type ResolvedBuildConfig,
|
||||
} from "./builder.ts";
|
||||
export {
|
||||
type OnTransformArgs,
|
||||
type OnTransformOptions,
|
||||
type TransformFn,
|
||||
} from "./file_transformer.ts";
|
||||
@@ -0,0 +1,148 @@
|
||||
import * as semver from "@std/semver";
|
||||
import * as colors from "@std/fmt/colors";
|
||||
import * as path from "@std/path";
|
||||
import { CURRENT_FRESH_VERSION } from "../otel.ts";
|
||||
|
||||
export interface CheckFile {
|
||||
last_checked: string;
|
||||
last_shown?: string;
|
||||
latest_version: string;
|
||||
current_version: string;
|
||||
}
|
||||
|
||||
function getHomeDir(): string | null {
|
||||
switch (Deno.build.os) {
|
||||
case "linux": {
|
||||
const xdg = Deno.env.get("XDG_CACHE_HOME");
|
||||
if (xdg) return xdg;
|
||||
|
||||
const home = Deno.env.get("HOME");
|
||||
if (home) return `${home}/.cache`;
|
||||
break;
|
||||
}
|
||||
|
||||
case "darwin": {
|
||||
const home = Deno.env.get("HOME");
|
||||
if (home) return `${home}/Library/Caches`;
|
||||
break;
|
||||
}
|
||||
|
||||
case "windows":
|
||||
return Deno.env.get("LOCALAPPDATA") ?? null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function getFreshCacheDir(): string | null {
|
||||
const home = getHomeDir();
|
||||
if (home) return path.join(home, "fresh");
|
||||
return null;
|
||||
}
|
||||
|
||||
async function fetchLatestVersion() {
|
||||
const res = await fetch("https://dl.deno.land/fresh/release-latest.txt");
|
||||
if (res.ok) {
|
||||
return (await res.text()).trim().replace(/^v/, "");
|
||||
}
|
||||
|
||||
throw new Error(`Could not fetch latest version.`);
|
||||
}
|
||||
|
||||
function readCurrentVersion() {
|
||||
return CURRENT_FRESH_VERSION;
|
||||
}
|
||||
|
||||
export async function updateCheck(
|
||||
interval: number,
|
||||
getCacheDir = getFreshCacheDir,
|
||||
getLatestVersion = fetchLatestVersion,
|
||||
getCurrentVersion = readCurrentVersion,
|
||||
) {
|
||||
// Skip update checks on CI or Deno Deploy
|
||||
if (
|
||||
Deno.env.get("CI") === "true" ||
|
||||
Deno.env.get("FRESH_NO_UPDATE_CHECK") === "true" ||
|
||||
Deno.env.get("DENO_DEPLOYMENT_ID")
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const home = getCacheDir();
|
||||
if (!home) return;
|
||||
const filePath = path.join(home, "latest.json");
|
||||
try {
|
||||
await Deno.mkdir(home, { recursive: true });
|
||||
} catch (err) {
|
||||
if (!(err instanceof Deno.errors.AlreadyExists)) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
const version = await getCurrentVersion();
|
||||
|
||||
let checkFile: CheckFile = {
|
||||
current_version: version,
|
||||
latest_version: version,
|
||||
last_checked: new Date(0).toISOString(),
|
||||
};
|
||||
try {
|
||||
const text = await Deno.readTextFile(filePath);
|
||||
checkFile = JSON.parse(text);
|
||||
} catch (err) {
|
||||
if (!(err instanceof Deno.errors.NotFound)) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// Update current version
|
||||
checkFile.current_version = version;
|
||||
|
||||
// Only check in the specified interval
|
||||
if (Date.now() >= new Date(checkFile.last_checked).getTime() + interval) {
|
||||
try {
|
||||
checkFile.latest_version = await getLatestVersion();
|
||||
checkFile.last_checked = new Date().toISOString();
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
// Update check is optional and shouldn't abort the program.
|
||||
// deno-lint-ignore no-console
|
||||
console.error(
|
||||
colors.red(` Update check failed: `) + message,
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Only show update message if current version is smaller than latest
|
||||
const currentVersion = semver.parse(checkFile.current_version);
|
||||
const latestVersion = semver.parse(checkFile.latest_version);
|
||||
if (
|
||||
(!checkFile.last_shown ||
|
||||
Date.now() >= new Date(checkFile.last_shown).getTime() + interval) &&
|
||||
semver.lessThan(currentVersion, latestVersion)
|
||||
) {
|
||||
checkFile.last_shown = new Date().toISOString();
|
||||
|
||||
const current = colors.bold(colors.rgb8(checkFile.current_version, 208));
|
||||
const latest = colors.bold(colors.rgb8(checkFile.latest_version, 121));
|
||||
// deno-lint-ignore no-console
|
||||
console.log(
|
||||
` Fresh ${latest} is available. You're on ${current}`,
|
||||
);
|
||||
// deno-lint-ignore no-console
|
||||
console.log(
|
||||
` To upgrade, run: deno run -A -r https://fresh.deno.dev/update`,
|
||||
);
|
||||
// deno-lint-ignore no-console
|
||||
console.log();
|
||||
}
|
||||
|
||||
// Migrate old format to current
|
||||
if (!checkFile.last_shown) {
|
||||
checkFile.last_shown = new Date().toISOString();
|
||||
}
|
||||
|
||||
const raw = JSON.stringify(checkFile, null, 2);
|
||||
await Deno.writeTextFile(filePath, raw);
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
import * as path from "@std/path";
|
||||
import denoJson from "../../deno.json" with { type: "json" };
|
||||
import { getStdOutput } from "../../tests/test_utils.tsx";
|
||||
import { expect } from "@std/expect";
|
||||
import { withTmpDir } from "../test_utils.ts";
|
||||
import type { CheckFile } from "./update_check.ts";
|
||||
import { WEEK } from "../constants.ts";
|
||||
|
||||
const CURRENT_VERSION = denoJson.version;
|
||||
|
||||
const cwd = import.meta.dirname!;
|
||||
|
||||
Deno.test("stores update check file in $HOME/fresh", async () => {
|
||||
await using tmp = await withTmpDir();
|
||||
const filePath = path.join(tmp.dir, "latest.json");
|
||||
|
||||
await new Deno.Command(Deno.execPath(), {
|
||||
args: [
|
||||
"run",
|
||||
"-A",
|
||||
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
|
||||
],
|
||||
cwd,
|
||||
env: {
|
||||
CI: "false",
|
||||
TEST_HOME: tmp.dir,
|
||||
},
|
||||
}).output();
|
||||
|
||||
const text = JSON.parse(await Deno.readTextFile(filePath));
|
||||
expect(text).toEqual({
|
||||
current_version: CURRENT_VERSION,
|
||||
latest_version: "99.99.999",
|
||||
last_checked: text.last_checked,
|
||||
last_shown: text.last_shown,
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("skips update check on specific environment variables", async (t) => {
|
||||
const envs = ["FRESH_NO_UPDATE_CHECK", "CI", "DENO_DEPLOYMENT_ID"];
|
||||
|
||||
for (const env of envs) {
|
||||
await t.step(`checking ${env}`, async () => {
|
||||
await using tmp = await withTmpDir();
|
||||
const out = await new Deno.Command(Deno.execPath(), {
|
||||
args: [
|
||||
"run",
|
||||
"-A",
|
||||
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
|
||||
],
|
||||
cwd,
|
||||
env: {
|
||||
[env]: "true",
|
||||
TEST_HOME: tmp.dir,
|
||||
LATEST_VERSION: "1.30.0",
|
||||
},
|
||||
stderr: "piped",
|
||||
stdout: "piped",
|
||||
}).output();
|
||||
|
||||
const { stdout } = getStdOutput(out);
|
||||
expect(stdout).not.toMatch(/Fresh 1\.30\.0 is available/);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
Deno.test("shows update message on version mismatch", async () => {
|
||||
await using tmp = await withTmpDir();
|
||||
const filePath = path.join(tmp.dir, "latest.json");
|
||||
|
||||
await Deno.writeTextFile(
|
||||
filePath,
|
||||
JSON.stringify({
|
||||
current_version: "1.1.0",
|
||||
latest_version: "1.1.0",
|
||||
last_checked: new Date(0).toISOString(),
|
||||
}),
|
||||
);
|
||||
|
||||
const out = await new Deno.Command(Deno.execPath(), {
|
||||
args: [
|
||||
"run",
|
||||
"-A",
|
||||
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
|
||||
],
|
||||
cwd,
|
||||
env: {
|
||||
CI: "false",
|
||||
TEST_HOME: tmp.dir,
|
||||
LATEST_VERSION: "999.999.0",
|
||||
},
|
||||
stderr: "piped",
|
||||
stdout: "piped",
|
||||
}).output();
|
||||
|
||||
const { stdout } = getStdOutput(out);
|
||||
expect(stdout).toMatch(/Fresh 999\.999\.0 is available/);
|
||||
|
||||
// Updates check file
|
||||
const text = JSON.parse(await Deno.readTextFile(filePath));
|
||||
expect(text).toEqual({
|
||||
current_version: CURRENT_VERSION,
|
||||
latest_version: "999.999.0",
|
||||
last_checked: text.last_checked,
|
||||
last_shown: text.last_shown,
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("only fetch new version defined by interval", async (t) => {
|
||||
await using tmp = await withTmpDir();
|
||||
|
||||
await t.step("fetches latest version initially", async () => {
|
||||
const out = await new Deno.Command(Deno.execPath(), {
|
||||
args: [
|
||||
"run",
|
||||
"-A",
|
||||
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
|
||||
],
|
||||
cwd,
|
||||
env: {
|
||||
CI: "false",
|
||||
UPDATE_INTERVAL: "100000",
|
||||
TEST_HOME: tmp.dir,
|
||||
LATEST_VERSION: "1.30.0",
|
||||
},
|
||||
stderr: "piped",
|
||||
stdout: "piped",
|
||||
}).output();
|
||||
|
||||
const { stdout } = getStdOutput(out);
|
||||
expect(stdout).toMatch(/fetching latest version/);
|
||||
});
|
||||
|
||||
await t.step("should not fetch if interval has not passed", async () => {
|
||||
const out = await new Deno.Command(Deno.execPath(), {
|
||||
args: [
|
||||
"run",
|
||||
"-A",
|
||||
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
|
||||
],
|
||||
cwd,
|
||||
env: {
|
||||
CI: "false",
|
||||
UPDATE_INTERVAL: "100000",
|
||||
TEST_HOME: tmp.dir,
|
||||
LATEST_VERSION: "1.30.0",
|
||||
},
|
||||
stderr: "piped",
|
||||
stdout: "piped",
|
||||
}).output();
|
||||
|
||||
const { stdout } = getStdOutput(out);
|
||||
expect(stdout).not.toMatch(/fetching latest version/);
|
||||
});
|
||||
|
||||
await t.step("fetches if interval has passed", async () => {
|
||||
const out = await new Deno.Command(Deno.execPath(), {
|
||||
args: [
|
||||
"run",
|
||||
"-A",
|
||||
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
|
||||
],
|
||||
cwd,
|
||||
env: {
|
||||
CI: "false",
|
||||
UPDATE_INTERVAL: "1 ",
|
||||
TEST_HOME: tmp.dir,
|
||||
LATEST_VERSION: "1.30.0",
|
||||
},
|
||||
}).output();
|
||||
|
||||
const { stdout } = getStdOutput(out);
|
||||
expect(stdout).toMatch(/fetching latest version/);
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("updates current version in cache file", async () => {
|
||||
await using tmp = await withTmpDir();
|
||||
|
||||
const checkFile: CheckFile = {
|
||||
current_version: "1.2.0",
|
||||
latest_version: "1.2.0",
|
||||
last_checked: new Date(Date.now() - WEEK).toISOString(),
|
||||
};
|
||||
|
||||
await Deno.writeTextFile(
|
||||
path.join(tmp.dir, "latest.json"),
|
||||
JSON.stringify(checkFile, null, 2),
|
||||
);
|
||||
|
||||
const out = await new Deno.Command(Deno.execPath(), {
|
||||
args: [
|
||||
"run",
|
||||
"-A",
|
||||
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
|
||||
],
|
||||
cwd,
|
||||
env: {
|
||||
CI: "false",
|
||||
TEST_HOME: tmp.dir,
|
||||
LATEST_VERSION: CURRENT_VERSION,
|
||||
},
|
||||
stderr: "piped",
|
||||
stdout: "piped",
|
||||
}).output();
|
||||
|
||||
const { stdout } = getStdOutput(out);
|
||||
expect(stdout).not.toMatch(/Fresh .* is available/);
|
||||
});
|
||||
|
||||
Deno.test("only shows update message when current < latest", async () => {
|
||||
await using tmp = await withTmpDir();
|
||||
|
||||
const checkFile: CheckFile = {
|
||||
current_version: "9999.999.0",
|
||||
latest_version: "1.2.0",
|
||||
last_checked: new Date().toISOString(),
|
||||
};
|
||||
|
||||
await Deno.writeTextFile(
|
||||
path.join(tmp.dir, "latest.json"),
|
||||
JSON.stringify(checkFile, null, 2),
|
||||
);
|
||||
|
||||
const out = await new Deno.Command(Deno.execPath(), {
|
||||
args: [
|
||||
"run",
|
||||
"-A",
|
||||
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
|
||||
],
|
||||
cwd,
|
||||
env: {
|
||||
CI: "false",
|
||||
TEST_HOME: tmp.dir,
|
||||
LATEST_VERSION: CURRENT_VERSION,
|
||||
CURRENT_VERSION: "99999.9999.0",
|
||||
},
|
||||
stderr: "piped",
|
||||
stdout: "piped",
|
||||
}).output();
|
||||
|
||||
const { stdout } = getStdOutput(out);
|
||||
expect(stdout).not.toMatch(/Fresh .* is available/);
|
||||
});
|
||||
|
||||
Deno.test("migrates to last_shown property", async () => {
|
||||
await using tmp = await withTmpDir();
|
||||
|
||||
const checkFile: CheckFile = {
|
||||
latest_version: "1.4.0",
|
||||
current_version: "1.2.0",
|
||||
last_checked: new Date().toISOString(),
|
||||
};
|
||||
|
||||
await Deno.writeTextFile(
|
||||
path.join(tmp.dir, "latest.json"),
|
||||
JSON.stringify(checkFile, null, 2),
|
||||
);
|
||||
|
||||
const out = await new Deno.Command(Deno.execPath(), {
|
||||
args: [
|
||||
"run",
|
||||
"-A",
|
||||
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
|
||||
],
|
||||
cwd,
|
||||
env: {
|
||||
CI: "false",
|
||||
TEST_HOME: tmp.dir,
|
||||
CURRENT_VERSION: "1.2.0",
|
||||
LATEST_VERSION: "99999.9999.0",
|
||||
},
|
||||
stderr: "piped",
|
||||
stdout: "piped",
|
||||
}).output();
|
||||
|
||||
const { stdout } = getStdOutput(out);
|
||||
expect(stdout).toMatch(/Fresh .* is available/);
|
||||
|
||||
const checkFileAfter = JSON.parse(
|
||||
await Deno.readTextFile(
|
||||
path.join(tmp.dir, "latest.json"),
|
||||
),
|
||||
);
|
||||
|
||||
// Check if last version was written
|
||||
expect(typeof checkFileAfter.last_shown).toEqual("string");
|
||||
});
|
||||
|
||||
Deno.test("doesn't show update if last_shown + interval >= today", async () => {
|
||||
await using tmp = await withTmpDir();
|
||||
|
||||
const todayMinus1Hour = new Date();
|
||||
todayMinus1Hour.setHours(todayMinus1Hour.getHours() - 1);
|
||||
|
||||
const checkFile: CheckFile = {
|
||||
current_version: "1.2.0",
|
||||
latest_version: "1.6.0",
|
||||
last_checked: new Date().toISOString(),
|
||||
last_shown: todayMinus1Hour.toISOString(),
|
||||
};
|
||||
|
||||
await Deno.writeTextFile(
|
||||
path.join(tmp.dir, "latest.json"),
|
||||
JSON.stringify(checkFile, null, 2),
|
||||
);
|
||||
|
||||
const out = await new Deno.Command(Deno.execPath(), {
|
||||
args: [
|
||||
"run",
|
||||
"-A",
|
||||
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
|
||||
],
|
||||
cwd,
|
||||
env: {
|
||||
CI: "false",
|
||||
TEST_HOME: tmp.dir,
|
||||
CURRENT_VERSION: "1.2.0",
|
||||
LATEST_VERSION: "99999.9999.0",
|
||||
},
|
||||
stderr: "piped",
|
||||
stdout: "piped",
|
||||
}).output();
|
||||
|
||||
const { stdout } = getStdOutput(out);
|
||||
expect(stdout).not.toMatch(/Fresh .* is available/);
|
||||
});
|
||||
|
||||
Deno.test(
|
||||
"shows update if last_shown + interval < today",
|
||||
async () => {
|
||||
await using tmp = await withTmpDir();
|
||||
|
||||
const yesterday = new Date();
|
||||
yesterday.setDate(yesterday.getDate() - 1);
|
||||
|
||||
const checkFile: CheckFile = {
|
||||
current_version: "1.2.0",
|
||||
latest_version: "99.999.99",
|
||||
last_checked: new Date().toISOString(),
|
||||
last_shown: yesterday.toISOString(),
|
||||
};
|
||||
|
||||
await Deno.writeTextFile(
|
||||
path.join(tmp.dir, "latest.json"),
|
||||
JSON.stringify(checkFile, null, 2),
|
||||
);
|
||||
|
||||
const out = await new Deno.Command(Deno.execPath(), {
|
||||
args: [
|
||||
"run",
|
||||
"-A",
|
||||
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
|
||||
],
|
||||
cwd,
|
||||
env: {
|
||||
CI: "false",
|
||||
TEST_HOME: tmp.dir,
|
||||
CURRENT_VERSION: CURRENT_VERSION,
|
||||
LATEST_VERSION: "99999.9999.0",
|
||||
},
|
||||
stderr: "piped",
|
||||
stdout: "piped",
|
||||
}).output();
|
||||
|
||||
const { stdout } = getStdOutput(out);
|
||||
expect(stdout).toMatch(/Fresh .* is available/);
|
||||
|
||||
const checkFileAfter = JSON.parse(
|
||||
await Deno.readTextFile(
|
||||
path.join(tmp.dir, "latest.json"),
|
||||
),
|
||||
);
|
||||
|
||||
expect(checkFileAfter.last_shown).not.toEqual(yesterday.toISOString());
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,78 @@
|
||||
import { type ErrorStatus, STATUS_TEXT } from "@std/http/status";
|
||||
|
||||
export type { ErrorStatus };
|
||||
|
||||
/**
|
||||
* Error that's thrown when a request fails. Correlates to a
|
||||
* {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status | HTTP status}.
|
||||
*
|
||||
* @property status The HTTP status code.
|
||||
*
|
||||
* @example Basic usage
|
||||
* ```ts
|
||||
* import { App, HttpError } from "fresh";
|
||||
* import { expect } from "@std/expect";
|
||||
*
|
||||
* const app = new App()
|
||||
* .get("/", () => new Response("ok"))
|
||||
* .get("/not-found", () => {
|
||||
* throw new HttpError(404, "Nothing here");
|
||||
* });
|
||||
*
|
||||
* const handler = app.handler();
|
||||
*
|
||||
* try {
|
||||
* await handler(new Request("http://localhost/not-found"))
|
||||
* } catch (error) {
|
||||
* expect(error).toBeInstanceOf(HttpError);
|
||||
* expect(error.status).toBe(404);
|
||||
* expect(error.message).toBe("Nothing here");
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
export class HttpError extends Error {
|
||||
/**
|
||||
* The HTTP status code.
|
||||
*
|
||||
* @example Basic usage
|
||||
* ```ts
|
||||
* import { App, HttpError } from "fresh";
|
||||
* import { expect } from "@std/expect";
|
||||
*
|
||||
* const app = new App()
|
||||
* .get("/", () => new Response("ok"))
|
||||
* .get("/not-found", () => {
|
||||
* throw new HttpError(404, "Nothing here");
|
||||
* });
|
||||
*
|
||||
* const handler = app.handler();
|
||||
*
|
||||
* try {
|
||||
* await handler(new Request("http://localhost/not-found"))
|
||||
* } catch (error) {
|
||||
* expect(error).toBeInstanceOf(HttpError);
|
||||
* expect(error.status).toBe(404);
|
||||
* expect(error.message).toBe("Nothing here");
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
status: ErrorStatus;
|
||||
|
||||
/**
|
||||
* Constructs a new instance.
|
||||
*
|
||||
* @param status The HTTP status code.
|
||||
* @param message The error message. Defaults to the status text of the given
|
||||
* status code.
|
||||
* @param options Optional error options.
|
||||
*/
|
||||
constructor(
|
||||
status: ErrorStatus,
|
||||
message: string = STATUS_TEXT[status],
|
||||
options?: ErrorOptions,
|
||||
) {
|
||||
super(message, options);
|
||||
this.name = this.constructor.name;
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { expect } from "@std/expect";
|
||||
import { HttpError } from "./error.ts";
|
||||
|
||||
Deno.test("HttpError", () => {
|
||||
const err = new HttpError(404);
|
||||
expect(err.status).toEqual(404);
|
||||
expect(err.message).toEqual("Not Found");
|
||||
expect(typeof err.stack).toEqual("string");
|
||||
|
||||
const err2 = new HttpError(500);
|
||||
expect(err2.status).toEqual(500);
|
||||
expect(err2.message).toEqual("Internal Server Error");
|
||||
expect(typeof err2.stack).toEqual("string");
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import * as pathPosix from "@std/path/posix";
|
||||
import * as path from "@std/path";
|
||||
|
||||
export type FileUrl = string & { readonly __brand: unique symbol };
|
||||
|
||||
export function pathToFileUrl(str: string): FileUrl {
|
||||
if (str.startsWith("file://")) {
|
||||
// all good
|
||||
} else if (path.isAbsolute(str)) {
|
||||
str = path.toFileUrl(str).href;
|
||||
} else {
|
||||
throw new Error(`Cannot convert "${str}" to file:// url`);
|
||||
}
|
||||
|
||||
return str as FileUrl;
|
||||
}
|
||||
|
||||
export function relativeUrl(from: FileUrl, to: FileUrl): string {
|
||||
return pathPosix.relative(from, to);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { expect } from "@std/expect";
|
||||
import { pathToFileUrl, relativeUrl } from "./file_url.ts";
|
||||
|
||||
Deno.test("pathToFileUrl", () => {
|
||||
expect(pathToFileUrl("file:///foo/bar")).toEqual("file:///foo/bar");
|
||||
expect(pathToFileUrl("/foo/bar")).toEqual("file:///foo/bar");
|
||||
});
|
||||
|
||||
Deno.test("relativeUrl", () => {
|
||||
const a = pathToFileUrl("file://foo/bar");
|
||||
const b = pathToFileUrl("file://foo/baz");
|
||||
|
||||
expect(relativeUrl(a, b)).toEqual("../baz");
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import { walk, type WalkEntry, type WalkOptions } from "@std/fs/walk";
|
||||
|
||||
export interface FsAdapter {
|
||||
cwd(): string;
|
||||
walk(
|
||||
root: string | URL,
|
||||
options?: WalkOptions,
|
||||
): AsyncIterableIterator<WalkEntry>;
|
||||
isDirectory(path: string | URL): Promise<boolean>;
|
||||
mkdirp(dir: string): Promise<void>;
|
||||
readFile(path: string | URL): Promise<Uint8Array>;
|
||||
readTextFile(path: string | URL): Promise<string>;
|
||||
}
|
||||
|
||||
export const fsAdapter: FsAdapter = {
|
||||
walk,
|
||||
cwd: Deno.cwd,
|
||||
async isDirectory(path) {
|
||||
try {
|
||||
const stat = await Deno.stat(path);
|
||||
return stat.isDirectory;
|
||||
} catch (err) {
|
||||
if (err instanceof Deno.errors.NotFound) return false;
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
async mkdirp(dir: string) {
|
||||
try {
|
||||
await Deno.mkdir(dir, { recursive: true });
|
||||
} catch (err) {
|
||||
if (!(err instanceof Deno.errors.AlreadyExists)) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
},
|
||||
readFile: Deno.readFile,
|
||||
readTextFile: Deno.readTextFile,
|
||||
};
|
||||
@@ -0,0 +1,326 @@
|
||||
import type { AnyComponent } from "preact";
|
||||
import type { MaybeLazy, Route, RouteConfig } from "./types.ts";
|
||||
import type { HandlerByMethod, RouteHandler } from "./handlers.ts";
|
||||
import type { Middleware } from "./middlewares/mod.ts";
|
||||
import type { AsyncAnyComponent } from "./render.ts";
|
||||
import { type HandlerFn, isHandlerByMethod } from "./handlers.ts";
|
||||
import type { PageProps } from "./render.ts";
|
||||
import {
|
||||
type Command,
|
||||
CommandType,
|
||||
newAppCmd,
|
||||
newErrorCmd,
|
||||
newLayoutCmd,
|
||||
newMiddlewareCmd,
|
||||
newNotFoundCmd,
|
||||
newRouteCmd,
|
||||
} from "./commands.ts";
|
||||
import { isLazy } from "./utils.ts";
|
||||
|
||||
export interface FreshFsMod<State> {
|
||||
config?: RouteConfig;
|
||||
handler?: RouteHandler<unknown, State> | HandlerFn<unknown, State>[];
|
||||
handlers?: RouteHandler<unknown, State>;
|
||||
default?:
|
||||
| AnyComponent<PageProps<unknown, State>>
|
||||
| AsyncAnyComponent<PageProps<unknown, State>>;
|
||||
}
|
||||
|
||||
export interface FsRouteFile<State> {
|
||||
id: string;
|
||||
filePath: string;
|
||||
mod: MaybeLazy<FreshFsMod<State>>;
|
||||
pattern: string;
|
||||
type: CommandType;
|
||||
routePattern: string;
|
||||
overrideConfig: RouteConfig | undefined;
|
||||
}
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
function isFreshFile<State>(mod: any): mod is FreshFsMod<State> {
|
||||
if (mod === null || typeof mod !== "object") return false;
|
||||
|
||||
return typeof mod.default === "function" ||
|
||||
typeof mod.config === "object" || typeof mod.handlers === "object" ||
|
||||
typeof mod.handlers === "function" || typeof mod.handler === "object" ||
|
||||
typeof mod.handler === "function";
|
||||
}
|
||||
|
||||
export interface FsRoutesOptions {
|
||||
/**
|
||||
* Parent directory for the `/routes` and `/islands` folders.
|
||||
*
|
||||
* By default, the `root` config option of the provided app is used.
|
||||
* @default app.config.root
|
||||
*/
|
||||
dir?: string;
|
||||
ignoreFilePattern?: RegExp[];
|
||||
loadRoute: (path: string) => Promise<unknown>;
|
||||
}
|
||||
|
||||
export function fsItemsToCommands<State>(
|
||||
items: FsRouteFile<State>[],
|
||||
): Command<State>[] {
|
||||
const commands: Command<State>[] = [];
|
||||
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const item = items[i];
|
||||
const { filePath, type, mod: rawMod, pattern, routePattern } = item;
|
||||
|
||||
switch (type) {
|
||||
case CommandType.Middleware: {
|
||||
if (isLazy(rawMod)) continue;
|
||||
const { handlers, mod } = validateFsMod(filePath, rawMod);
|
||||
|
||||
let middlewares = (handlers ?? mod.default) as unknown as
|
||||
| Middleware<State>
|
||||
| Middleware<State>[]
|
||||
| HandlerByMethod<unknown, State> ??
|
||||
null;
|
||||
if (middlewares === null) continue;
|
||||
|
||||
if (isHandlerByMethod(middlewares)) {
|
||||
warnInvalidRoute(
|
||||
`Middleware does not support object handlers with GET, POST, etc. in ${filePath}`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!Array.isArray(middlewares)) {
|
||||
middlewares = [middlewares];
|
||||
}
|
||||
|
||||
commands.push(newMiddlewareCmd(pattern, middlewares, true));
|
||||
continue;
|
||||
}
|
||||
case CommandType.Layout: {
|
||||
const { handlers, mod } = validateFsMod<State>(filePath, rawMod);
|
||||
if (handlers !== null) {
|
||||
warnInvalidRoute("Layout does not support handlers");
|
||||
}
|
||||
if (!mod.default) continue;
|
||||
|
||||
commands.push(newLayoutCmd(pattern, mod.default, mod.config, true));
|
||||
continue;
|
||||
}
|
||||
case CommandType.Error: {
|
||||
const { handlers, mod } = validateFsMod<State>(filePath, rawMod);
|
||||
commands.push(newErrorCmd(
|
||||
pattern,
|
||||
{
|
||||
component: mod.default ?? undefined,
|
||||
config: mod.config ?? undefined,
|
||||
// deno-lint-ignore no-explicit-any
|
||||
handler: (handlers as any) ?? undefined,
|
||||
},
|
||||
true,
|
||||
));
|
||||
continue;
|
||||
}
|
||||
case CommandType.NotFound: {
|
||||
const { handlers, mod } = validateFsMod<State>(filePath, rawMod);
|
||||
commands.push(newNotFoundCmd({
|
||||
config: mod.config,
|
||||
component: mod.default,
|
||||
// deno-lint-ignore no-explicit-any
|
||||
handler: handlers as any ?? undefined,
|
||||
}));
|
||||
continue;
|
||||
}
|
||||
case CommandType.App: {
|
||||
const { mod } = validateFsMod<State>(filePath, rawMod);
|
||||
if (mod.default === undefined) continue;
|
||||
|
||||
commands.push(newAppCmd(mod.default));
|
||||
continue;
|
||||
}
|
||||
case CommandType.Route: {
|
||||
let normalized;
|
||||
// Merge configs
|
||||
let config: RouteConfig = {};
|
||||
if (isLazy(rawMod)) {
|
||||
normalized = async () => {
|
||||
const result = await rawMod();
|
||||
return normalizeRoute(filePath, result, routePattern);
|
||||
};
|
||||
|
||||
config.methods = item.overrideConfig?.methods ?? "ALL";
|
||||
config.routeOverride = item.overrideConfig?.routeOverride ??
|
||||
routePattern;
|
||||
} else {
|
||||
normalized = normalizeRoute(filePath, rawMod, routePattern);
|
||||
if (rawMod.config) {
|
||||
config = rawMod.config;
|
||||
}
|
||||
}
|
||||
|
||||
commands.push(
|
||||
newRouteCmd(pattern, normalized, config, false),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
case CommandType.Handler:
|
||||
throw new Error(`Not supported`);
|
||||
case CommandType.FsRoute:
|
||||
throw new Error(`Nested FsRoutes are not supported`);
|
||||
default:
|
||||
throw new Error(`Unknown command type: ${type}`);
|
||||
}
|
||||
}
|
||||
|
||||
return commands;
|
||||
}
|
||||
|
||||
function warnInvalidRoute(message: string) {
|
||||
// deno-lint-ignore no-console
|
||||
console.warn(
|
||||
`🍋 %c[WARNING] Unsupported route config: ${message}`,
|
||||
"color:rgb(251, 184, 0)",
|
||||
);
|
||||
}
|
||||
|
||||
const APP_REG = /_app(?!\.[tj]sx?)?$/;
|
||||
|
||||
/**
|
||||
* Sort route paths where special Fresh files like `_app`,
|
||||
* `_layout` and `_middleware` are sorted in front.
|
||||
*/
|
||||
export function sortRoutePaths(a: string, b: string) {
|
||||
// The `_app` route should always be the first
|
||||
if (APP_REG.test(a)) return -1;
|
||||
else if (APP_REG.test(b)) return 1;
|
||||
|
||||
const aLen = a.length;
|
||||
const bLen = b.length;
|
||||
|
||||
let segment = false;
|
||||
let aIdx = 0;
|
||||
let bIdx = 0;
|
||||
for (; aIdx < aLen && bIdx < bLen; aIdx++, bIdx++) {
|
||||
const charA = a.charAt(aIdx);
|
||||
const charB = b.charAt(bIdx);
|
||||
|
||||
// When comparing a grouped route with a non-grouped one, we
|
||||
// need to skip over the group name to effectively compare the
|
||||
// actual route.
|
||||
if (charA === "(" && charB !== "(") {
|
||||
if (charB == "[") return -1;
|
||||
return 1;
|
||||
} else if (charB === "(" && charA !== "(") {
|
||||
if (charA == "[") return 1;
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (charA === "/" || charB === "/") {
|
||||
segment = true;
|
||||
|
||||
// If the other path doesn't close the segment
|
||||
// then we don't need to continue
|
||||
if (charA !== "/") return 1;
|
||||
if (charB !== "/") return -1;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (segment) {
|
||||
segment = false;
|
||||
|
||||
const scoreA = getRoutePathScore(charA, a, aIdx);
|
||||
const scoreB = getRoutePathScore(charB, b, bIdx);
|
||||
if (scoreA === scoreB) {
|
||||
if (charA !== charB) {
|
||||
// TODO: Do we need localeSort here or is this good enough?
|
||||
return charA < charB ? 0 : 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
return scoreA > scoreB ? -1 : 1;
|
||||
}
|
||||
|
||||
if (charA !== charB) {
|
||||
// TODO: Do we need localeSort here or is this good enough?
|
||||
return charA < charB ? 0 : 1;
|
||||
}
|
||||
|
||||
// If we're at the end of A or B, then we assume that the longer
|
||||
// path is more specific
|
||||
if (aIdx === aLen - 1 && bIdx < bLen - 1) {
|
||||
return 1;
|
||||
} else if (bIdx === bLen - 1 && aIdx < aLen - 1) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Assign a score based on the first two characters of a path segment.
|
||||
* The goal is to sort `_middleware` and `_layout` in front of everything
|
||||
* and `[` or `[...` last respectively.
|
||||
*/
|
||||
function getRoutePathScore(char: string, s: string, i: number): number {
|
||||
if (char === "_") {
|
||||
if (i + 1 < s.length) {
|
||||
if (s[i + 1] === "e") return 4;
|
||||
if (s[i + 1] === "m") return 6;
|
||||
}
|
||||
return 5;
|
||||
} else if (char === "[") {
|
||||
if (i + 1 < s.length && s[i + 1] === ".") {
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (
|
||||
i + 4 === s.length - 1 && char === "i" && s[i + 1] === "n" &&
|
||||
s[i + 2] === "d" && s[i + 3] === "e" && s[i + 4] === "x"
|
||||
) {
|
||||
return 3;
|
||||
}
|
||||
|
||||
return 2;
|
||||
}
|
||||
|
||||
export function validateFsMod<State>(
|
||||
filePath: string,
|
||||
mod: unknown,
|
||||
): {
|
||||
handlers: RouteHandler<unknown, State> | HandlerFn<unknown, State>[] | null;
|
||||
mod: FreshFsMod<State>;
|
||||
} {
|
||||
if (!isFreshFile<State>(mod)) {
|
||||
throw new Error(
|
||||
`Expected a route, middleware, layout or error template, but couldn't find relevant exports in: ${filePath}`,
|
||||
);
|
||||
}
|
||||
|
||||
const handlers = mod.handlers ?? mod.handler ?? null;
|
||||
if (typeof handlers === "function" && handlers.length > 1) {
|
||||
throw new Error(
|
||||
`Handlers must only have one argument but found more than one. Check the function signature in: ${filePath}`,
|
||||
);
|
||||
}
|
||||
|
||||
return { handlers, mod };
|
||||
}
|
||||
|
||||
function normalizeRoute<State>(
|
||||
filePath: string,
|
||||
rawMod: FreshFsMod<State>,
|
||||
routePattern: string,
|
||||
): Route<State> {
|
||||
const { handlers, mod } = validateFsMod<State>(filePath, rawMod);
|
||||
|
||||
return {
|
||||
config: {
|
||||
...mod.config,
|
||||
routeOverride: mod.config?.routeOverride ?? routePattern,
|
||||
},
|
||||
// deno-lint-ignore no-explicit-any
|
||||
handler: (handlers as any) ?? undefined,
|
||||
component: mod.default,
|
||||
};
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,212 @@
|
||||
import type { Context } from "./context.ts";
|
||||
import type { Method } from "./router.ts";
|
||||
|
||||
export interface PageResponse<T> {
|
||||
data: T;
|
||||
headers?: HeadersInit;
|
||||
status?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a {@link PageResponse} object that can be returned from a route
|
||||
* handler. This will cause the page component to be rendered with the specified
|
||||
* data and response options.
|
||||
*
|
||||
* ```ts
|
||||
* export const handlers = define.handlers({
|
||||
* GET: (ctx) => {
|
||||
* return page({ message: "Hello, world!" }, {
|
||||
* headers: { "Cache-Control": "public, max-age=3600" },
|
||||
* status: 201,
|
||||
* });
|
||||
* },
|
||||
* });
|
||||
*
|
||||
* export default define.page<typeof handlers>(({ data }) => {
|
||||
* return <h1>{data.message}</h1>;
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @param data The data to pass to the page component to be rendered.
|
||||
* @param options Additional options to use when constructing the response object.
|
||||
* @returns A {@link PageResponse} object that should be returned from a route handler.
|
||||
*/
|
||||
export function page<T>(data: T, options?: {
|
||||
headers?: HeadersInit;
|
||||
status?: number;
|
||||
}): PageResponse<T>;
|
||||
export function page(): PageResponse<undefined>;
|
||||
export function page<T>(data?: T, options?: {
|
||||
headers?: HeadersInit;
|
||||
status?: number;
|
||||
}): PageResponse<T> {
|
||||
return {
|
||||
data: data ?? undefined as T,
|
||||
headers: options?.headers,
|
||||
status: options?.status,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A handler function that can be used to specify how a given route should
|
||||
* handle requests.
|
||||
*
|
||||
* The handler function can either return a {@link Response} object, or some
|
||||
* data that can be rendered by a page component. See {@link HandlerFn} for more
|
||||
* information.
|
||||
*
|
||||
* ### Per method handlers
|
||||
*
|
||||
* A route handler can be specific to a given HTTP method (GET, POST, PUT,
|
||||
* DELETE, etc). To define a method-specific handler, specify an object that
|
||||
* maps method names to functions that conform to the {@link HandlerFn}
|
||||
* signature.
|
||||
*
|
||||
* ```ts
|
||||
* export const handlers = define.handlers({
|
||||
* GET: (ctx) => {
|
||||
* return new Response("Hello from a GET request!");
|
||||
* },
|
||||
* POST: (ctx) => {
|
||||
* return new Response("Hello from a POST request!");
|
||||
* }
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* Any requests to methods not specified in the handler object will result in a
|
||||
* 405 Method Not Allowed response. If you want to handle these requests, you
|
||||
* can define a catch-all handler.
|
||||
*
|
||||
* If a GET handler is specified, but no HEAD handler is specified, a HEAD
|
||||
* handler will automatically be generated that calls the GET handler and
|
||||
* strips the response body.
|
||||
*
|
||||
* ### Catch-all handlers
|
||||
*
|
||||
* A route handler can also catch all requests in a route. To define a catch-all
|
||||
* handler, specify a function that conforms to the {@link HandlerFn} signature.
|
||||
* This function will be called for all requests, regardless of the method.
|
||||
*
|
||||
* ```ts
|
||||
* export const handlers = define.handlers((ctx) => {
|
||||
* return new Response(`Hello from a ${ctx.req.method} request!`);
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export type RouteHandler<Data, State> =
|
||||
| HandlerFn<Data, State>
|
||||
| HandlerByMethod<Data, State>;
|
||||
|
||||
export function isHandlerByMethod<D, S>(
|
||||
handler: RouteHandler<D, S> | RouteHandler<D, S>[] | null,
|
||||
): handler is HandlerByMethod<D, S> {
|
||||
return handler !== null && !Array.isArray(handler) &&
|
||||
typeof handler === "object";
|
||||
}
|
||||
|
||||
/**
|
||||
* A handler function that is invoked when a request is made to a route. The
|
||||
* handler function is passed a {@link Context} object that contains the
|
||||
* original request object, as well as any state related to the current request.
|
||||
*
|
||||
* The handler function can either return a {@link Response} object, which will
|
||||
* be sent back to the client, or some data that will be passed to the routes'
|
||||
* page component for rendering.
|
||||
*
|
||||
* ### Returning a Response
|
||||
*
|
||||
* If the handler function returns a {@link Response} object, the response will
|
||||
* be sent back to the client. This can be used to send back static content, or
|
||||
* to redirect the client to another URL.
|
||||
*
|
||||
* ```ts
|
||||
* export const handler = define.handlers((ctx) => {
|
||||
* return new Response("Hello, world!");
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* ### Returning data
|
||||
*
|
||||
* If the handler function returns an object with a `data` property, the data
|
||||
* will be passed to the page component, where it can be rendered into HTML.
|
||||
*
|
||||
* ```ts
|
||||
* export const handler = define.handlers((ctx) => {
|
||||
* return { data: { message: "Hello, world!" } };
|
||||
* });
|
||||
*
|
||||
* export default definePage<typeof handler>(({ data }) => {
|
||||
* return <h1>{data.message}</h1>;
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* When returning data, you can also specify additional properties that will be
|
||||
* used when constructing the response object from the HTML generated by the
|
||||
* page component. For example, you can specify custom headers, a custom status
|
||||
* code, or a list of elements to include in the `<head>`.
|
||||
*
|
||||
* ```tsx
|
||||
* export const handler = define.handlers((ctx) => {
|
||||
* return {
|
||||
* data: { message: "Hello, world!" },
|
||||
* headers: { "Cache-Control": "public, max-age=3600" },
|
||||
* status: 201,
|
||||
* head: [<title>Hello, world!</title>],
|
||||
* };
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* ### Asynchronous handlers
|
||||
*
|
||||
* The handler function can also be asynchronous. This can be useful if you need
|
||||
* to fetch data from an external source, or perform some other asynchronous
|
||||
* operation before returning a response.
|
||||
*
|
||||
* ```ts
|
||||
* export const handler = define.handlers(async (ctx) => {
|
||||
* const resp = await fetch("https://api.example.com/data").;
|
||||
* if (!resp.ok) {
|
||||
* throw new Error("Failed to fetch data");
|
||||
* }
|
||||
* const data = await resp.json();
|
||||
* return { data };
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* If you initiate multiple asynchronous operations in a handler, you can use
|
||||
* `Promise.all` to wait for all of them to complete at the same time. This can
|
||||
* speed up the response time of your handler, as it allows you to perform
|
||||
* multiple operations concurrently.
|
||||
*
|
||||
* ```ts
|
||||
* export const handler = define.handlers(async (ctx) => {
|
||||
* const [resp1, resp2] = await Promise.all([
|
||||
* fetch("https://api.example.com/data1")
|
||||
* .then((resp) => resp.json()),
|
||||
* fetch("https://api.example.com/data2")
|
||||
* .then((resp) => resp.json()),
|
||||
* ]);
|
||||
* return { data: { data1, data2 } };
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export interface HandlerFn<Data, State> {
|
||||
(ctx: Context<State>):
|
||||
| Response
|
||||
| PageResponse<Data>
|
||||
| Promise<Response | PageResponse<Data>>;
|
||||
}
|
||||
|
||||
/**
|
||||
* A set of handler functions that routes requests based on the HTTP method.
|
||||
*
|
||||
* See {@link RouteHandler} for more information on how to use this type.
|
||||
*/
|
||||
export type HandlerByMethod<Data, State> = {
|
||||
[M in Method]?: HandlerFn<Data, State>;
|
||||
};
|
||||
|
||||
export type RouteData<
|
||||
Handler extends RouteHandler<unknown, unknown>,
|
||||
> = Handler extends (RouteHandler<infer Data, unknown>) ? Data
|
||||
: never;
|
||||
@@ -0,0 +1,5 @@
|
||||
import * as path from "@std/path";
|
||||
|
||||
export { setBuildCache } from "./app.ts";
|
||||
export { IslandPreparer, ProdBuildCache } from "./build_cache.ts";
|
||||
export { path };
|
||||
@@ -0,0 +1,11 @@
|
||||
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";
|
||||
@@ -0,0 +1,57 @@
|
||||
export const snapshot = {};
|
||||
|
||||
snapshot[`round trip - undefined 1`] = `"-1"`;
|
||||
|
||||
snapshot[`round trip - null 1`] = `"-2"`;
|
||||
|
||||
snapshot[`round trip - 1 1`] = `"[1]"`;
|
||||
|
||||
snapshot[`round trip - 2 1`] = `"[2]"`;
|
||||
|
||||
snapshot[`round trip - -2 1`] = `"[-2]"`;
|
||||
|
||||
snapshot[`round trip - Infinity 1`] = `"-4"`;
|
||||
|
||||
snapshot[`round trip - -Infinity 1`] = `"-5"`;
|
||||
|
||||
snapshot[`round trip - 0 1`] = `"[0]"`;
|
||||
|
||||
snapshot[`round trip - -0 1`] = `"-6"`;
|
||||
|
||||
snapshot[`round trip - NaN 1`] = `"-3"`;
|
||||
|
||||
snapshot[`round trip - 0 2`] = `"[0]"`;
|
||||
|
||||
snapshot[`round trip - true 1`] = `"[true]"`;
|
||||
|
||||
snapshot[`round trip - false 1`] = `"[false]"`;
|
||||
|
||||
snapshot[`round trip - 'abc' 1`] = `'["abc"]'`;
|
||||
|
||||
snapshot[`round trip - 1n 1`] = `'[["BigInt","1"]]'`;
|
||||
|
||||
snapshot[`round trip - -1n 1`] = `'[["BigInt","-1"]]'`;
|
||||
|
||||
snapshot[`round trip - [ 1, 2, 3 ] 1`] = `"[[1,2,3],1,2,3]"`;
|
||||
|
||||
snapshot[`round trip - [ null, undefined, -2 ] 1`] = `"[[-2,-1,1],-2]"`;
|
||||
|
||||
snapshot[`round trip - { a: 1, b: null, c: -2 } 1`] = `'[{"a":1,"b":-2,"c":2},1,-2]'`;
|
||||
|
||||
snapshot[`round trip - Uint8Array(3) [ 1, 2, 3 ] 1`] = `'[["Uint8Array","AQID"]]'`;
|
||||
|
||||
snapshot[`round trip - URL {\\n href: 'https://fresh.deno.dev/',\\n origin: 'https://fresh.deno.dev',\\n protocol: 'https:',\\n username: '',\\n password: '',\\n host: 'fresh.deno.dev',\\n hostname: 'fresh.deno.dev',\\n port: '',\\n pathname: '/',\\n hash: '',\\n search: ''\\n} 1`] = `'[["URL","https://fresh.deno.dev/"]]'`;
|
||||
|
||||
snapshot[`round trip - 1990-05-31T00:00:00.000Z 1`] = `'[["Date","1990-05-31T00:00:00.000Z"]]'`;
|
||||
|
||||
snapshot[`round trip - Map(2) { 1 => null, undefined => -2 } 1`] = `'[["Map",[1,-2,-1,2]],1,-2]'`;
|
||||
|
||||
snapshot[`round trip - Set(5) { 1, 2, null, -2, NaN } 1`] = `'[["Set",[1,2,-2,3,-3]],1,2,-2]'`;
|
||||
|
||||
snapshot[`round trip - [ 1, <1 empty item>, 3 ] 1`] = `"[[1,-7,2],1,3]"`;
|
||||
|
||||
snapshot[`round trip - /foo["]/ 1`] = `'[["RegExp","foo[\\\\"]", ""]]'`;
|
||||
|
||||
snapshot[`round trip - { a: { foo: 123 }, b: [ { foo: 123 }, { foo: 123 } ] } 1`] = `'[{"a":1,"b":3},{"foo":2},123,[1,1]]'`;
|
||||
|
||||
snapshot[`round trip - <ref *1> { a: 1, b: [Circular *1] } 1`] = `'[{"a":1,"b":0},1]'`;
|
||||
@@ -0,0 +1,7 @@
|
||||
export const UNDEFINED = -1;
|
||||
export const NULL = -2;
|
||||
export const NAN = -3;
|
||||
export const INFINITY_POS = -4;
|
||||
export const INFINITY_NEG = -5;
|
||||
export const ZERO_NEG = -6;
|
||||
export const HOLE = -7;
|
||||
@@ -0,0 +1,93 @@
|
||||
import { expect } from "@std/expect";
|
||||
import { parse } from "./parse.ts";
|
||||
import { stringify } from "./stringify.ts";
|
||||
import { Signal, signal } from "@preact/signals";
|
||||
|
||||
Deno.test("custom parse - Point", () => {
|
||||
class Point {
|
||||
constructor(public x: number, public y: number) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
}
|
||||
|
||||
const str = stringify(new Point(30, 40), {
|
||||
Point: (value) =>
|
||||
value instanceof Point ? { value: [value.x, value.y] } : undefined,
|
||||
});
|
||||
|
||||
expect(str).toEqual('[["Point",1],[2,3],30,40]');
|
||||
|
||||
const point = parse(str, {
|
||||
Point: ([x, y]: [number, number]) => new Point(x, y),
|
||||
});
|
||||
expect(point).toEqual(new Point(30, 40));
|
||||
});
|
||||
|
||||
Deno.test("custom parse - Signals", () => {
|
||||
const res = parse<Signal>('[["Signal",1],2]', {
|
||||
Signal: (value) => signal(value),
|
||||
});
|
||||
expect(res).toBeInstanceOf(Signal);
|
||||
expect(res.peek()).toEqual(2);
|
||||
});
|
||||
|
||||
Deno.test("custom stringify - Signals", () => {
|
||||
const s = signal(2);
|
||||
expect(stringify(s, {
|
||||
Signal: (s2: unknown) => {
|
||||
return s2 instanceof Signal ? { value: s2.peek() } : undefined;
|
||||
},
|
||||
})).toEqual(
|
||||
'[["Signal",1],2]',
|
||||
);
|
||||
});
|
||||
|
||||
Deno.test("custom parse - Signals with null value", () => {
|
||||
const res = parse<Signal>('[["Signal",-2]]', {
|
||||
Signal: (value) => signal(value),
|
||||
});
|
||||
expect(res).toBeInstanceOf(Signal);
|
||||
expect(res.peek()).toEqual(null);
|
||||
});
|
||||
|
||||
Deno.test("custom stringify - Signals with null value", () => {
|
||||
const s = signal(null);
|
||||
expect(stringify(s, {
|
||||
Signal: (s2: unknown) => {
|
||||
return s2 instanceof Signal ? { value: s2.peek() } : undefined;
|
||||
},
|
||||
})).toEqual(
|
||||
'[["Signal",-2]]',
|
||||
);
|
||||
});
|
||||
|
||||
Deno.test("custom parse - Signals with undefined value", () => {
|
||||
const res = parse<Signal>('[["Signal",-1]]', {
|
||||
Signal: (value) => signal(value),
|
||||
});
|
||||
expect(res).toBeInstanceOf(Signal);
|
||||
expect(res.peek()).toEqual(undefined);
|
||||
});
|
||||
|
||||
Deno.test("custom stringify - Signals with undefined value", () => {
|
||||
const s = signal(undefined);
|
||||
expect(stringify(s, {
|
||||
Signal: (s2: unknown) => {
|
||||
return s2 instanceof Signal ? { value: s2.peek() } : undefined;
|
||||
},
|
||||
})).toEqual(
|
||||
'[["Signal",-1]]',
|
||||
);
|
||||
});
|
||||
|
||||
Deno.test("custom stringify - referenced Signals", () => {
|
||||
const s = signal(2);
|
||||
expect(stringify([s, s], {
|
||||
Signal: (s2: unknown) => {
|
||||
return s2 instanceof Signal ? { value: s2.peek() } : undefined;
|
||||
},
|
||||
})).toEqual(
|
||||
'[[1,1],["Signal",2],2]',
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,132 @@
|
||||
import {
|
||||
HOLE,
|
||||
INFINITY_NEG,
|
||||
INFINITY_POS,
|
||||
NAN,
|
||||
NULL,
|
||||
UNDEFINED,
|
||||
ZERO_NEG,
|
||||
} from "./constants.ts";
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export type CustomParser = Record<string, (value: any) => unknown>;
|
||||
|
||||
export function parse<T = unknown>(
|
||||
value: string,
|
||||
custom?: CustomParser | undefined,
|
||||
): T {
|
||||
const data = JSON.parse(value);
|
||||
if (!Array.isArray(data)) return unpack([], [], data, custom) as T;
|
||||
const hydrated = new Array(data.length);
|
||||
unpack(data, hydrated, 0, custom);
|
||||
return hydrated[0];
|
||||
}
|
||||
|
||||
function unpack(
|
||||
arr: unknown[],
|
||||
hydrated: unknown[],
|
||||
idx: number,
|
||||
custom: CustomParser | undefined,
|
||||
): unknown {
|
||||
switch (idx) {
|
||||
case UNDEFINED:
|
||||
return undefined;
|
||||
case NULL:
|
||||
return null;
|
||||
case NAN:
|
||||
return NaN;
|
||||
case INFINITY_POS:
|
||||
return Infinity;
|
||||
case INFINITY_NEG:
|
||||
return -Infinity;
|
||||
case ZERO_NEG:
|
||||
return -0;
|
||||
}
|
||||
|
||||
if (idx in hydrated) return hydrated[idx];
|
||||
|
||||
const current = arr[idx];
|
||||
if (typeof current === "number") {
|
||||
return hydrated[idx] = current;
|
||||
} else if (
|
||||
typeof current === "string" || typeof current === "boolean" ||
|
||||
current === null
|
||||
) {
|
||||
return hydrated[idx] = current;
|
||||
} else if (Array.isArray(current)) {
|
||||
if (current.length > 0 && typeof current[0] === "string") {
|
||||
const name = current[0];
|
||||
if (custom !== undefined && name in custom) {
|
||||
const fn = custom[name];
|
||||
const ref = current[1];
|
||||
const value = unpack(arr, hydrated, ref, custom);
|
||||
return hydrated[idx] = fn(value);
|
||||
}
|
||||
switch (name) {
|
||||
case "BigInt":
|
||||
return hydrated[idx] = BigInt(current[1]);
|
||||
case "URL":
|
||||
return hydrated[idx] = new URL(current[1]);
|
||||
case "Date":
|
||||
return hydrated[idx] = new Date(current[1]);
|
||||
case "RegExp":
|
||||
return hydrated[idx] = new RegExp(current[1], current[2]);
|
||||
case "Set": {
|
||||
const set = new Set();
|
||||
for (let i = 0; i < current[1].length; i++) {
|
||||
const ref = current[1][i];
|
||||
set.add(unpack(arr, hydrated, ref, custom));
|
||||
}
|
||||
return hydrated[idx] = set;
|
||||
}
|
||||
case "Map": {
|
||||
const set = new Map();
|
||||
for (let i = 0; i < current[1].length; i++) {
|
||||
const refKey = current[1][i++];
|
||||
const key = unpack(arr, hydrated, refKey, custom);
|
||||
const refValue = current[1][i];
|
||||
const value = unpack(arr, hydrated, refValue, custom);
|
||||
|
||||
set.set(key, value);
|
||||
}
|
||||
return hydrated[idx] = set;
|
||||
}
|
||||
case "Uint8Array":
|
||||
return hydrated[idx] = b64decode(current[1]);
|
||||
}
|
||||
} else {
|
||||
const actual = new Array(current.length);
|
||||
hydrated[idx] = actual;
|
||||
for (let i = 0; i < current.length; i++) {
|
||||
const ref = current[i];
|
||||
if (ref === HOLE) {
|
||||
continue;
|
||||
} else {
|
||||
actual[i] = unpack(arr, hydrated, ref, custom);
|
||||
}
|
||||
}
|
||||
return actual;
|
||||
}
|
||||
} else if (typeof current === "object") {
|
||||
const actual: Record<string, unknown> = {};
|
||||
hydrated[idx] = actual;
|
||||
const keys = Object.keys(current);
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const key = keys[i];
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const ref = (current as any)[key];
|
||||
actual[key] = unpack(arr, hydrated, ref, custom);
|
||||
}
|
||||
return actual;
|
||||
}
|
||||
}
|
||||
|
||||
function b64decode(b64: string): Uint8Array {
|
||||
const binString = atob(b64);
|
||||
const size = binString.length;
|
||||
const bytes = new Uint8Array(size);
|
||||
for (let i = 0; i < size; i++) {
|
||||
bytes[i] = binString.charCodeAt(i);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { expect } from "@std/expect";
|
||||
import { parse } from "./parse.ts";
|
||||
import { assertSnapshot } from "@std/testing/snapshot";
|
||||
import { inspect } from "node:util";
|
||||
import { stringify } from "./stringify.ts";
|
||||
|
||||
const inner = { foo: 123 };
|
||||
const references = { a: inner, b: [inner, inner] };
|
||||
|
||||
const circular = { a: 1, b: null as unknown };
|
||||
circular.b = circular;
|
||||
|
||||
const TESTS = [
|
||||
undefined,
|
||||
null,
|
||||
1,
|
||||
2,
|
||||
-2,
|
||||
Infinity,
|
||||
-Infinity,
|
||||
0,
|
||||
-0,
|
||||
NaN,
|
||||
1.2 -
|
||||
1.2,
|
||||
true,
|
||||
false,
|
||||
"abc",
|
||||
1n,
|
||||
-1n,
|
||||
[1, 2, 3],
|
||||
[null, undefined, -2],
|
||||
{ a: 1, b: null, c: -2 },
|
||||
new Uint8Array([1, 2, 3]),
|
||||
new URL("https://fresh.deno.dev"),
|
||||
new Date("1990-05-31"),
|
||||
new Map([[1, null], [undefined, -2]]),
|
||||
new Set([1, 2, null, -2, NaN]),
|
||||
[1, , 3],
|
||||
/foo["]/,
|
||||
references,
|
||||
circular,
|
||||
];
|
||||
|
||||
for (const value of TESTS) {
|
||||
Deno.test(`round trip - ${inspect(value)}`, async (t) => {
|
||||
const str = stringify(value);
|
||||
await assertSnapshot(t, str);
|
||||
const parsed = parse(str);
|
||||
expect(parsed).toEqual(value);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
import {
|
||||
INFINITY_NEG,
|
||||
INFINITY_POS,
|
||||
NAN,
|
||||
NULL,
|
||||
UNDEFINED,
|
||||
ZERO_NEG,
|
||||
} from "./constants.ts";
|
||||
import { HOLE } from "./constants.ts";
|
||||
|
||||
export type Stringifiers = Record<
|
||||
string,
|
||||
// deno-lint-ignore no-explicit-any
|
||||
(value: any) => { value: any } | undefined
|
||||
>;
|
||||
|
||||
/**
|
||||
* Serializes the following:
|
||||
*
|
||||
* - `null`
|
||||
* - `undefined`
|
||||
* - `boolean`
|
||||
* - `number`
|
||||
* - `bigint`
|
||||
* - `string`
|
||||
* - `array`
|
||||
* - `object` (no prototypes)
|
||||
* - `Uint8Array`
|
||||
* - `URL`
|
||||
* - `Date`
|
||||
* - `RegExp`
|
||||
* - `Set`
|
||||
* - `Map`
|
||||
*
|
||||
* Circular references are supported and objects with the same reference are
|
||||
* serialized only once.
|
||||
*/
|
||||
export function stringify(data: unknown, custom?: Stringifiers): string {
|
||||
const out: string[] = [];
|
||||
const indexes = new Map<unknown, number>();
|
||||
const res = serializeInner(out, indexes, data, custom);
|
||||
if (res < 0) {
|
||||
return String(res);
|
||||
}
|
||||
return `[${out.join(",")}]`;
|
||||
}
|
||||
|
||||
function serializeInner(
|
||||
out: string[],
|
||||
indexes: Map<unknown, number>,
|
||||
value: unknown,
|
||||
custom: Stringifiers | undefined,
|
||||
): number {
|
||||
const seenIdx = indexes.get(value);
|
||||
if (seenIdx !== undefined) return seenIdx;
|
||||
|
||||
if (value === undefined) return UNDEFINED;
|
||||
if (value === null) return NULL;
|
||||
if (Number.isNaN(value)) return NAN;
|
||||
if (value === Infinity) return INFINITY_POS;
|
||||
if (value === -Infinity) return INFINITY_NEG;
|
||||
if (value === 0 && 1 / value < 0) return ZERO_NEG;
|
||||
|
||||
const idx = out.length;
|
||||
out.push("");
|
||||
indexes.set(value, idx);
|
||||
|
||||
let str = "";
|
||||
|
||||
if (typeof value === "number") {
|
||||
str += String(value);
|
||||
} else if (typeof value === "boolean") {
|
||||
str += String(value);
|
||||
} else if (typeof value === "bigint") {
|
||||
str += `["BigInt","${value}"]`;
|
||||
} else if (typeof value === "string") {
|
||||
str += JSON.stringify(value);
|
||||
} else if (Array.isArray(value)) {
|
||||
str += "[";
|
||||
for (let i = 0; i < value.length; i++) {
|
||||
if (i in value) {
|
||||
str += serializeInner(out, indexes, value[i], custom);
|
||||
} else {
|
||||
str += HOLE;
|
||||
}
|
||||
|
||||
if (i < value.length - 1) {
|
||||
str += ",";
|
||||
}
|
||||
}
|
||||
str += "]";
|
||||
} else if (typeof value === "object") {
|
||||
if (custom !== undefined) {
|
||||
for (const k in custom) {
|
||||
const fn = custom[k];
|
||||
if (fn === undefined) continue;
|
||||
|
||||
const res = fn(value);
|
||||
if (res === undefined) continue;
|
||||
|
||||
const innerIdx = serializeInner(out, indexes, res.value, custom);
|
||||
str = `["${k}",${innerIdx}]`;
|
||||
out[idx] = str;
|
||||
return idx;
|
||||
}
|
||||
}
|
||||
|
||||
if (value instanceof URL) {
|
||||
str += `["URL","${value.href}"]`;
|
||||
} else if (value instanceof Date) {
|
||||
str += `["Date","${value.toISOString()}"]`;
|
||||
} else if (value instanceof RegExp) {
|
||||
str += `["RegExp",${JSON.stringify(value.source)}, "${value.flags}"]`;
|
||||
} else if (value instanceof Uint8Array) {
|
||||
str += `["Uint8Array","${b64encode(value.buffer)}"]`;
|
||||
} else if (value instanceof Set) {
|
||||
const items = new Array(value.size);
|
||||
let i = 0;
|
||||
value.forEach((v) => {
|
||||
items[i++] = serializeInner(out, indexes, v, custom);
|
||||
});
|
||||
str += `["Set",[${items.join(",")}]]`;
|
||||
} else if (value instanceof Map) {
|
||||
const items = new Array(value.size * 2);
|
||||
let i = 0;
|
||||
value.forEach((v, k) => {
|
||||
items[i++] = serializeInner(out, indexes, k, custom);
|
||||
items[i++] = serializeInner(out, indexes, v, custom);
|
||||
});
|
||||
str += `["Map",[${items.join(",")}]]`;
|
||||
} else {
|
||||
str += "{";
|
||||
const keys = Object.keys(value);
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const key = keys[i];
|
||||
str += JSON.stringify(key) + ":";
|
||||
// deno-lint-ignore no-explicit-any
|
||||
str += serializeInner(out, indexes, (value as any)[key], custom);
|
||||
|
||||
if (i < keys.length - 1) {
|
||||
str += ",";
|
||||
}
|
||||
}
|
||||
str += "}";
|
||||
}
|
||||
} else if (typeof value === "function") {
|
||||
throw new Error(`Serializing functions is not supported.`);
|
||||
}
|
||||
|
||||
out[idx] = str;
|
||||
return idx;
|
||||
}
|
||||
|
||||
// deno-fmt-ignore
|
||||
const base64abc = [
|
||||
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O",
|
||||
"P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d",
|
||||
"e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
|
||||
"t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7",
|
||||
"8", "9", "+", "/",
|
||||
];
|
||||
|
||||
/**
|
||||
* CREDIT: https://gist.github.com/enepomnyaschih/72c423f727d395eeaa09697058238727
|
||||
* Encodes a given Uint8Array, ArrayBuffer or string into RFC4648 base64 representation
|
||||
*/
|
||||
export function b64encode(buffer: ArrayBufferLike): string {
|
||||
const uint8 = new Uint8Array(buffer);
|
||||
let result = "",
|
||||
i;
|
||||
const l = uint8.length;
|
||||
for (i = 2; i < l; i += 3) {
|
||||
result += base64abc[uint8[i - 2] >> 2];
|
||||
result += base64abc[((uint8[i - 2] & 0x03) << 4) | (uint8[i - 1] >> 4)];
|
||||
result += base64abc[((uint8[i - 1] & 0x0f) << 2) | (uint8[i] >> 6)];
|
||||
result += base64abc[uint8[i] & 0x3f];
|
||||
}
|
||||
if (i === l + 1) {
|
||||
// 1 octet yet to write
|
||||
result += base64abc[uint8[i - 2] >> 2];
|
||||
result += base64abc[(uint8[i - 2] & 0x03) << 4];
|
||||
result += "==";
|
||||
}
|
||||
if (i === l) {
|
||||
// 2 octets yet to write
|
||||
result += base64abc[uint8[i - 2] >> 2];
|
||||
result += base64abc[((uint8[i - 2] & 0x03) << 4) | (uint8[i - 1] >> 4)];
|
||||
result += base64abc[(uint8[i - 1] & 0x0f) << 2];
|
||||
result += "=";
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { expect } from "@std/expect";
|
||||
import { stringify } from "./stringify.ts";
|
||||
|
||||
Deno.test("stringify - object prototype", () => {
|
||||
const obj = { __proto__: 123, foo: 1 };
|
||||
expect(stringify(obj)).toEqual(
|
||||
'[{"foo":1},1]',
|
||||
);
|
||||
});
|
||||
|
||||
Deno.test("stringify - throw serializing functions", () => {
|
||||
const fn = () => {};
|
||||
expect(() => stringify(fn)).toThrow();
|
||||
});
|
||||
@@ -0,0 +1,193 @@
|
||||
import type { Context } from "../context.ts";
|
||||
import type { Middleware } from "./mod.ts";
|
||||
|
||||
export type CORSOptions<State> = {
|
||||
/**
|
||||
* The value of [`Access-Control-Allow-Origin`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Allow-Origin) CORS header
|
||||
*/
|
||||
origin:
|
||||
| string
|
||||
| string[]
|
||||
| ((origin: string, ctx: Context<State>) => string | undefined | null);
|
||||
/**
|
||||
* Sets the permitted methods for the [`Access-Control-Allow-Methods`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Allow-Methods) CORS header.
|
||||
*/
|
||||
allowMethods?: string[];
|
||||
/**
|
||||
* Indicate the HTTP headers that can be used during the actual request. Sets the [`Access-Control-Allow-Headers`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Allow-Headers) header
|
||||
*/
|
||||
allowHeaders?: string[];
|
||||
/**
|
||||
* The value of [`Access-Control-Max-Age`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Max-Age) CORS header
|
||||
*/
|
||||
maxAge?: number;
|
||||
/**
|
||||
* The value of [`Access-Control-Allow-Credentials`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Allow-Credentials) CORS header
|
||||
*/
|
||||
credentials?: boolean;
|
||||
/**
|
||||
* The value of [`Access-Control-Expose-Headers`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Expose-Headers) CORS header
|
||||
*/
|
||||
exposeHeaders?: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* CORS Middleware to set [`Cross-Origin-Resource-Sharing`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) headers.
|
||||
*
|
||||
* @param [options] - The options for the CORS middleware.
|
||||
* @returns The Fresh middleware handler function.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* // main.ts or routes/_middleware.ts
|
||||
* import { cors } from 'fresh';
|
||||
*
|
||||
* export const handler = [
|
||||
* cors({ origin: '*' }), // Allow all origins
|
||||
* // other middlewares or main route handler
|
||||
* ];
|
||||
*
|
||||
* // Example with options:
|
||||
* // export const handler = [
|
||||
* // cors({
|
||||
* // origin: 'http://example.com',
|
||||
* // allowHeaders: ['X-Custom-Header', 'Upgrade-Insecure-Requests'],
|
||||
* // allowMethods: ['POST', 'GET', 'OPTIONS'],
|
||||
* // exposeHeaders: ['Content-Length', 'X-Kuma-Revision'],
|
||||
* // maxAge: 600,
|
||||
* // credentials: true,
|
||||
* // }),
|
||||
* // // ...
|
||||
* // ];
|
||||
* ```
|
||||
*/
|
||||
export function cors<State>(options?: CORSOptions<State>): Middleware<State> {
|
||||
const opts: CORSOptions<State> = {
|
||||
origin: "*",
|
||||
allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"],
|
||||
allowHeaders: [],
|
||||
exposeHeaders: [],
|
||||
...options,
|
||||
};
|
||||
|
||||
const addHeaderProperties = (
|
||||
headers: Headers,
|
||||
allowOrigin: string | null | undefined,
|
||||
opts: CORSOptions<State>,
|
||||
) => {
|
||||
if (allowOrigin) {
|
||||
headers.set("Access-Control-Allow-Origin", allowOrigin);
|
||||
}
|
||||
|
||||
if (opts.credentials) {
|
||||
headers.set("Access-Control-Allow-Credentials", "true");
|
||||
}
|
||||
|
||||
if (opts.exposeHeaders?.length) {
|
||||
headers.set(
|
||||
"Access-Control-Expose-Headers",
|
||||
opts.exposeHeaders.join(","),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const optsOrigin = opts.origin;
|
||||
|
||||
return async (ctx) => {
|
||||
const requestOrigin = ctx.req.headers.get("origin") || "";
|
||||
|
||||
let allowOrigin: string | null = null;
|
||||
if (typeof optsOrigin === "string") {
|
||||
if (optsOrigin === "*") {
|
||||
allowOrigin = optsOrigin;
|
||||
} else {
|
||||
allowOrigin = optsOrigin === requestOrigin ? requestOrigin : null;
|
||||
}
|
||||
} else if (typeof optsOrigin === "function") {
|
||||
allowOrigin = optsOrigin(requestOrigin, ctx) ?? null;
|
||||
} else {
|
||||
allowOrigin = optsOrigin.includes(requestOrigin) ? requestOrigin : null;
|
||||
}
|
||||
|
||||
const vary = new Set<string>();
|
||||
// Add 'Origin' to Vary if a specific origin is allowed, not '*'
|
||||
if (opts.origin !== "*" && allowOrigin && allowOrigin !== "*") {
|
||||
vary.add("Origin");
|
||||
}
|
||||
|
||||
if (ctx.req.method === "OPTIONS") {
|
||||
const headers = new Headers();
|
||||
|
||||
addHeaderProperties(
|
||||
headers,
|
||||
allowOrigin,
|
||||
opts,
|
||||
);
|
||||
|
||||
if (opts.maxAge != null) {
|
||||
headers.set("Access-Control-Max-Age", opts.maxAge.toString());
|
||||
}
|
||||
|
||||
if (opts.allowMethods?.length) {
|
||||
headers.set(
|
||||
"Access-Control-Allow-Methods",
|
||||
opts.allowMethods.join(","),
|
||||
);
|
||||
}
|
||||
|
||||
let allowHeaders = opts.allowHeaders;
|
||||
if (!allowHeaders?.length) {
|
||||
const reqHeaders = ctx.req.headers.get(
|
||||
"Access-Control-Request-Headers",
|
||||
);
|
||||
if (reqHeaders) {
|
||||
allowHeaders = reqHeaders.split(/\s*,\s*/);
|
||||
}
|
||||
}
|
||||
|
||||
if (allowHeaders?.length) {
|
||||
headers.set(
|
||||
"Access-Control-Allow-Headers",
|
||||
allowHeaders.join(","),
|
||||
);
|
||||
vary.add("Access-Control-Request-Headers");
|
||||
}
|
||||
|
||||
if (vary.size > 0) {
|
||||
headers.set("Vary", Array.from(vary).join(", "));
|
||||
} else {
|
||||
headers.delete("Vary"); // Ensure Vary is not set if no conditions met
|
||||
}
|
||||
|
||||
headers.delete("Content-Length");
|
||||
headers.delete("Content-Type");
|
||||
|
||||
return new Response(null, {
|
||||
status: 204,
|
||||
statusText: "No Content",
|
||||
headers,
|
||||
});
|
||||
}
|
||||
|
||||
// For non-OPTIONS requests
|
||||
const res = await ctx.next();
|
||||
|
||||
addHeaderProperties(
|
||||
res.headers,
|
||||
allowOrigin,
|
||||
opts,
|
||||
);
|
||||
|
||||
// Merge our calculated varyValues with any existing Vary from downstream response
|
||||
if (vary.size > 0) {
|
||||
const existing = res.headers.get("Vary");
|
||||
if (existing) {
|
||||
existing.split(/\s*,\s*/).forEach((v) => vary.add(v));
|
||||
}
|
||||
|
||||
res.headers.set("Vary", Array.from(vary).join(", "));
|
||||
}
|
||||
|
||||
return res;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
import { App } from "../app.ts";
|
||||
import { cors } from "./cors.ts";
|
||||
import { expect } from "@std/expect";
|
||||
|
||||
Deno.test("CORS - GET default", async () => {
|
||||
const handler = new App()
|
||||
.use(cors())
|
||||
.get("/", () => new Response("ok"))
|
||||
.handler();
|
||||
|
||||
const res = await handler(new Request("https://localhost/"));
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("Access-Control-Allow-Origin")).toBe("*");
|
||||
expect(res.headers.get("Vary")).toBeNull();
|
||||
});
|
||||
|
||||
Deno.test("CORS - Preflight default", async () => {
|
||||
const handler = new App()
|
||||
.use(cors())
|
||||
.get("/", () => new Response("ok"))
|
||||
.handler();
|
||||
|
||||
const req = new Request("https://localhost/", { method: "OPTIONS" });
|
||||
req.headers.append(
|
||||
"Access-Control-Request-Headers",
|
||||
"X-PINGOTHER, Content-Type",
|
||||
);
|
||||
|
||||
const res = await handler(req);
|
||||
|
||||
expect(res.status).toBe(204);
|
||||
expect(res.headers.get("Access-Control-Allow-Methods")?.split(",")[0])
|
||||
.toBe("GET");
|
||||
expect(res.headers.get("Access-Control-Allow-Headers")?.split(","))
|
||||
.toEqual(["X-PINGOTHER", "Content-Type"]);
|
||||
});
|
||||
|
||||
Deno.test("CORS - Preflight with options", async () => {
|
||||
const handler = new App()
|
||||
.use(
|
||||
cors({
|
||||
origin: "http://example.com",
|
||||
allowHeaders: ["X-Custom-Header", "Upgrade-Insecure-Requests"],
|
||||
allowMethods: ["POST", "GET", "OPTIONS"],
|
||||
exposeHeaders: ["Content-Length", "X-Kuma-Revision"],
|
||||
maxAge: 600,
|
||||
credentials: true,
|
||||
}),
|
||||
)
|
||||
.get("/", () => new Response("ok"))
|
||||
.handler();
|
||||
|
||||
const res = await handler(
|
||||
new Request("https://localhost/", {
|
||||
method: "OPTIONS",
|
||||
headers: { origin: "http://example.com" },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(res.headers.get("Access-Control-Allow-Origin")).toBe(
|
||||
"http://example.com",
|
||||
);
|
||||
expect(res.headers.get("Vary")?.split(/\s*,\s*/)).toEqual(
|
||||
expect.arrayContaining(["Origin"]),
|
||||
);
|
||||
expect(res.headers.get("Access-Control-Allow-Headers")?.split(/\s*,\s*/))
|
||||
.toEqual([
|
||||
"X-Custom-Header",
|
||||
"Upgrade-Insecure-Requests",
|
||||
]);
|
||||
expect(res.headers.get("Access-Control-Allow-Methods")?.split(/\s*,\s*/))
|
||||
.toEqual([
|
||||
"POST",
|
||||
"GET",
|
||||
"OPTIONS",
|
||||
]);
|
||||
expect(res.headers.get("Access-Control-Expose-Headers")?.split(/\s*,\s*/))
|
||||
.toEqual([
|
||||
"Content-Length",
|
||||
"X-Kuma-Revision",
|
||||
]);
|
||||
expect(res.headers.get("Access-Control-Max-Age")).toBe("600");
|
||||
expect(res.headers.get("Access-Control-Allow-Credentials")).toBe("true");
|
||||
});
|
||||
|
||||
Deno.test("CORS - Disallow an unmatched origin", async () => {
|
||||
const handler = new App()
|
||||
.use(
|
||||
cors({
|
||||
origin: "http://example.com",
|
||||
allowHeaders: ["X-Custom-Header", "Upgrade-Insecure-Requests"],
|
||||
allowMethods: ["POST", "GET", "OPTIONS"],
|
||||
exposeHeaders: ["Content-Length", "X-Kuma-Revision"],
|
||||
maxAge: 600,
|
||||
credentials: true,
|
||||
}),
|
||||
)
|
||||
.get("/", () => new Response("ok"))
|
||||
.handler();
|
||||
|
||||
const res = await handler(
|
||||
new Request("https://localhost/", {
|
||||
method: "OPTIONS",
|
||||
headers: { origin: "http://example.net" },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(res.headers.has("Access-Control-Allow-Origin")).toBeFalsy();
|
||||
});
|
||||
|
||||
Deno.test("CORS - Allow multiple origins", async () => {
|
||||
const handler = new App()
|
||||
.use(cors({
|
||||
origin: [
|
||||
"http://example.com",
|
||||
"http://example.org",
|
||||
"http://example.dev",
|
||||
],
|
||||
}))
|
||||
.get("/", () => new Response("ok"))
|
||||
.handler();
|
||||
|
||||
let res = await handler(
|
||||
new Request("http://localhost/", {
|
||||
headers: {
|
||||
Origin: "http://example.org",
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(res.headers.get("Access-Control-Allow-Origin")).toBe(
|
||||
"http://example.org",
|
||||
);
|
||||
|
||||
res = await handler(new Request("http://localhost/"));
|
||||
expect(
|
||||
res.headers.has("Access-Control-Allow-Origin"),
|
||||
"An unmatched origin should be disallowed",
|
||||
).toBeFalsy();
|
||||
|
||||
res = await handler(
|
||||
new Request("http://localhost/api3/abc", {
|
||||
headers: {
|
||||
Referer: "http://example.net/",
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
res.headers.has("Access-Control-Allow-Origin"),
|
||||
"An unmatched origin should be disallowed",
|
||||
).toBeFalsy();
|
||||
});
|
||||
|
||||
Deno.test("CORS - Allow different Vary header value", async () => {
|
||||
const handler = new App()
|
||||
.use(cors({
|
||||
origin: [
|
||||
"http://example.com",
|
||||
"http://example.org",
|
||||
"http://example.dev",
|
||||
],
|
||||
}))
|
||||
.get("/", () => new Response("ok"))
|
||||
.handler();
|
||||
|
||||
const res = await handler(
|
||||
new Request("http://localhost/", {
|
||||
headers: {
|
||||
Vary: "accept-encoding",
|
||||
Origin: "http://example.com",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("Access-Control-Allow-Origin")).toBe(
|
||||
"http://example.com",
|
||||
);
|
||||
expect(res.headers.get("Vary")).toBe("Origin");
|
||||
});
|
||||
|
||||
Deno.test("CORS - Allow origins by function", async () => {
|
||||
const handler = new App()
|
||||
.use(cors({
|
||||
origin: (
|
||||
origin,
|
||||
) => (origin.endsWith(".example.com") ? origin : "http://example.com"),
|
||||
}))
|
||||
.get("/", () => new Response("ok"))
|
||||
.handler();
|
||||
|
||||
let res = await handler(
|
||||
new Request("http://localhost/", {
|
||||
headers: {
|
||||
Origin: "http://subdomain.example.com",
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(res.headers.get("Access-Control-Allow-Origin")).toBe(
|
||||
"http://subdomain.example.com",
|
||||
);
|
||||
|
||||
res = await handler(new Request("http://localhost/"));
|
||||
expect(res.headers.get("Access-Control-Allow-Origin")).toBe(
|
||||
"http://example.com",
|
||||
);
|
||||
|
||||
res = await handler(
|
||||
new Request("http://localhost/", {
|
||||
headers: {
|
||||
Referer: "http://evil-example.com/",
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(res.headers.get("Access-Control-Allow-Origin")).toBe(
|
||||
"http://example.com",
|
||||
);
|
||||
});
|
||||
|
||||
Deno.test("CORS - With raw Response object", async () => {
|
||||
const handler = new App()
|
||||
.use(cors())
|
||||
.get("/", () => new Response("ok"))
|
||||
.handler();
|
||||
|
||||
const res = await handler(new Request("http://localhost/"));
|
||||
|
||||
expect(res.headers.get("Access-Control-Allow-Origin")).toBe("*");
|
||||
expect(res.headers.get("Vary")).toBeNull();
|
||||
});
|
||||
|
||||
Deno.test("CORS - Should not return duplicate header values", async () => {
|
||||
const handler = new App()
|
||||
.use(cors({ origin: "http://example.com" }))
|
||||
.get("/", () => new Response("ok"))
|
||||
.handler();
|
||||
|
||||
const res = await handler(
|
||||
new Request("http://localhost/", {
|
||||
headers: {
|
||||
origin: "http://example.com",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(res.headers.get("Access-Control-Allow-Origin")).toBe(
|
||||
"http://example.com",
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
import type { Context } from "../context.ts";
|
||||
import { HttpError } from "../error.ts";
|
||||
import type { Middleware } from "./mod.ts";
|
||||
|
||||
/** Options for {@linkcode csrf}. **/
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export interface CsrfOptions<State = any> {
|
||||
/**
|
||||
* origin - Specifies the allowed origin(s) for requests.
|
||||
* - string: A single allowed origin.
|
||||
* - string[]: static allowed origins.
|
||||
* - function: A function to determine if an origin is allowed.
|
||||
*/
|
||||
origin?:
|
||||
| string
|
||||
| string[]
|
||||
| ((origin: string, context: Context<State>) => boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* CSRF Protection Middleware for Fresh.
|
||||
*
|
||||
* @param options Options for the CSRF protection middleware.
|
||||
* @returns The middleware handler function.
|
||||
*
|
||||
* @example Basic usage (with defaults)
|
||||
* ```ts
|
||||
* const app = new App<State>()
|
||||
*
|
||||
* app.use(csrf())
|
||||
* ```
|
||||
*
|
||||
* @example Specifying static origins
|
||||
* ```ts
|
||||
* app.use(csrf({ origin: 'https://myapp.example.com' }))
|
||||
*
|
||||
* // string[]
|
||||
* app.use(
|
||||
* csrf({
|
||||
* origin: ['https://myapp.example.com', 'http://development.myapp.example.com'],
|
||||
* })
|
||||
* )
|
||||
* ```
|
||||
*
|
||||
* @example Specifying more complex origins
|
||||
* ```ts
|
||||
* app.use(
|
||||
* '*',
|
||||
* csrf({
|
||||
* origin: (origin) => ['https://myapp.example.com', 'http://development.myapp.example.com'].includes(origin),
|
||||
* })
|
||||
* )
|
||||
* ```
|
||||
*/
|
||||
export function csrf<State>(
|
||||
options?: CsrfOptions,
|
||||
): Middleware<State> {
|
||||
const isAllowedOrigin = (
|
||||
origin: string | null,
|
||||
ctx: Context<State>,
|
||||
) => {
|
||||
if (origin === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const optsOrigin = options?.origin;
|
||||
|
||||
if (!optsOrigin) {
|
||||
return origin === ctx.url.origin;
|
||||
}
|
||||
if (typeof optsOrigin === "string") {
|
||||
return origin === optsOrigin;
|
||||
}
|
||||
if (typeof optsOrigin === "function") {
|
||||
return optsOrigin(origin, ctx);
|
||||
}
|
||||
return Array.isArray(optsOrigin) && optsOrigin.includes(origin);
|
||||
};
|
||||
|
||||
return async (ctx) => {
|
||||
const { method, headers } = ctx.req;
|
||||
|
||||
// Safe methods
|
||||
if (method === "GET" || method === "HEAD" || method === "OPTIONS") {
|
||||
return await ctx.next();
|
||||
}
|
||||
|
||||
const secFetchSite = headers.get("Sec-Fetch-Site");
|
||||
const origin = headers.get("origin");
|
||||
|
||||
if (secFetchSite !== null) {
|
||||
if (
|
||||
secFetchSite === "same-origin" || secFetchSite === "none" ||
|
||||
isAllowedOrigin(origin, ctx)
|
||||
) {
|
||||
return await ctx.next();
|
||||
}
|
||||
|
||||
throw new HttpError(403);
|
||||
}
|
||||
|
||||
// Neither `Sec-Fetch-Site` or `Origin` is set
|
||||
if (origin === null) {
|
||||
return await ctx.next();
|
||||
}
|
||||
|
||||
if (isAllowedOrigin(origin, ctx)) {
|
||||
return await ctx.next();
|
||||
}
|
||||
|
||||
throw new HttpError(403);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { App } from "../app.ts";
|
||||
import type { Method } from "../router.ts";
|
||||
import { csrf, type CsrfOptions } from "./csrf.ts";
|
||||
import { expect } from "@std/expect";
|
||||
|
||||
function testHandler<T>(
|
||||
options?: CsrfOptions<T>,
|
||||
): (request: Request) => Promise<Response> {
|
||||
return new App<T>()
|
||||
.use(csrf(options))
|
||||
.all("/", () => new Response("hello"))
|
||||
.handler();
|
||||
}
|
||||
|
||||
function createTests(trusted: CsrfOptions["origin"]) {
|
||||
return async function runTest(
|
||||
method: Method,
|
||||
expected: 200 | 403,
|
||||
test: {
|
||||
secFetchSite?: "cross-site" | "same-origin" | "same-site" | "none";
|
||||
origin?: string;
|
||||
} = {},
|
||||
) {
|
||||
const handler = testHandler({ origin: trusted });
|
||||
|
||||
const headers = new Headers();
|
||||
if (test.secFetchSite) headers.append("Sec-Fetch-Site", test.secFetchSite);
|
||||
if (test.origin) {
|
||||
headers.append("Origin", test.origin);
|
||||
}
|
||||
|
||||
const res = await handler(
|
||||
new Request("https://example.com", { method, headers }),
|
||||
);
|
||||
await res.body?.cancel();
|
||||
expect(res.status).toEqual(expected);
|
||||
};
|
||||
}
|
||||
|
||||
Deno.test("CSRF - allow GET/HEAD/OPTIONS", async () => {
|
||||
const runTest = createTests("https://example.com");
|
||||
|
||||
await runTest("GET", 200);
|
||||
await runTest("HEAD", 200);
|
||||
await runTest("OPTIONS", 200);
|
||||
});
|
||||
|
||||
Deno.test("CSRF - Sec-Fetch-Site", async () => {
|
||||
const runTest = createTests("https://example.com");
|
||||
|
||||
await runTest("POST", 200, { secFetchSite: "same-origin" });
|
||||
await runTest("POST", 200, { secFetchSite: "none" });
|
||||
await runTest("POST", 403, { secFetchSite: "cross-site" });
|
||||
await runTest("POST", 403, { secFetchSite: "same-site" });
|
||||
|
||||
await runTest("POST", 200);
|
||||
await runTest("POST", 200, { origin: "https://example.com" });
|
||||
await runTest("POST", 403, { origin: "https://attacker.example.com" });
|
||||
await runTest("POST", 403, { origin: "null" });
|
||||
|
||||
await runTest("GET", 200, { secFetchSite: "cross-site" });
|
||||
await runTest("HEAD", 200, { secFetchSite: "cross-site" });
|
||||
await runTest("OPTIONS", 200, { secFetchSite: "cross-site" });
|
||||
await runTest("PUT", 403, { secFetchSite: "cross-site" });
|
||||
});
|
||||
|
||||
Deno.test("CSRF - cross origin", async () => {
|
||||
const runTest = createTests("https://trusted.example.com");
|
||||
|
||||
await runTest("POST", 200, { origin: "https://trusted.example.com" });
|
||||
await runTest("POST", 200, {
|
||||
origin: "https://trusted.example.com",
|
||||
secFetchSite: "cross-site",
|
||||
});
|
||||
|
||||
await runTest("POST", 403, { origin: "https://attacker.example.com" });
|
||||
await runTest("POST", 403, {
|
||||
origin: "https://attacker.example.com",
|
||||
secFetchSite: "cross-site",
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("CSRF - array origin", async () => {
|
||||
const runTest = createTests(
|
||||
["https://example.com", "https://trusted.example.com"],
|
||||
);
|
||||
|
||||
await runTest("POST", 200, { origin: "https://trusted.example.com" });
|
||||
await runTest("POST", 200, { origin: "https://example.com" });
|
||||
await runTest("POST", 403, { origin: "https://foo.example.com" });
|
||||
});
|
||||
|
||||
Deno.test("CSRF - function origin", async () => {
|
||||
const runTest = createTests(
|
||||
(origin) => origin === "https://example.com",
|
||||
);
|
||||
|
||||
await runTest("POST", 200, { origin: "https://example.com" });
|
||||
await runTest("POST", 403, { origin: "https://trusted.example.com" });
|
||||
await runTest("POST", 403, { origin: "https://foo.example.com" });
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
import { type Context, getInternals } from "../context.ts";
|
||||
import type { App as _App } from "../app.ts";
|
||||
import type { Define as _Define } from "../define.ts";
|
||||
|
||||
/**
|
||||
* A middleware function is the basic building block of Fresh. It allows you
|
||||
* to respond to an incoming request in any way you want. You can redirect
|
||||
* routes, serve files, create APIs and much more. Middlewares can be chained by
|
||||
* calling {@linkcode Context.next|ctx.next()} inside of the function.
|
||||
*
|
||||
* Middlewares can be synchronous or asynchronous. If a middleware returns a
|
||||
* {@linkcode Response} object, the response will be sent back to the client. If
|
||||
* a middleware returns a `Promise<Response>`, Fresh will wait for the promise
|
||||
* to resolve before sending the response.
|
||||
*
|
||||
* A {@linkcode Context} object is passed to the middleware function. This
|
||||
* object contains the original request object, as well as any state related to
|
||||
* the current request. The context object also contains methods to redirect
|
||||
* the client to another URL, or to call the next middleware in the chain.
|
||||
*
|
||||
* Middlewares can be defined as a single function or an array of functions.
|
||||
* When an array of middlewares is passed to
|
||||
* {@linkcode _App.prototype.use|app.use}, Fresh will call each middleware in the
|
||||
* order they are defined.
|
||||
*
|
||||
* Middlewares can also be defined using the
|
||||
* {@linkcode _Define.middleware|define.middleware} method. This
|
||||
* method is optional, but it can be useful for type checking and code
|
||||
* completion. It does not register the middleware with the app.
|
||||
*
|
||||
* ## Examples
|
||||
*
|
||||
* ### Logging middleware
|
||||
*
|
||||
* This example shows how to create a simple middleware that logs incoming
|
||||
* requests.
|
||||
*
|
||||
* ```ts
|
||||
* // Define a middleware function that logs incoming requests. Using the
|
||||
* // `define.middleware` method is optional, but it can be useful for type
|
||||
* // checking and code completion. It does not register the middleware with the
|
||||
* // app.
|
||||
* const loggerMiddleware = define.middleware((ctx) => {
|
||||
* console.log(`${ctx.req.method} ${ctx.req.url}`);
|
||||
* // Call the next middleware
|
||||
* return ctx.next();
|
||||
* });
|
||||
*
|
||||
* // To register the middleware to the app, use `app.use`.
|
||||
* app.use(loggerMiddleware)
|
||||
* ```
|
||||
*
|
||||
* ### Redirect middleware
|
||||
*
|
||||
* This example shows how to create a middleware that redirects requests from
|
||||
* one URL to another.
|
||||
*
|
||||
* ```ts
|
||||
* // Any request to a URL that starts with "/legacy/" will be redirected to
|
||||
* // "/modern".
|
||||
* const redirectMiddleware = define.middleware((ctx) => {
|
||||
* if (ctx.url.pathname.startsWith("/legacy/")) {
|
||||
* return ctx.redirect("/modern");
|
||||
* }
|
||||
*
|
||||
* // Otherwise call the next middleware
|
||||
* return ctx.next();
|
||||
* });
|
||||
*
|
||||
* // Again, register the middleware with the app.
|
||||
* app.use(redirectMiddleware);
|
||||
* ```
|
||||
*/
|
||||
export type Middleware<State> = (
|
||||
ctx: Context<State>,
|
||||
) => Response | Promise<Response>;
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode Middleware} instead.
|
||||
*/
|
||||
export type MiddlewareFn<State> = Middleware<State>;
|
||||
|
||||
/**
|
||||
* A lazy {@linkcode Middleware}
|
||||
*/
|
||||
export type MaybeLazyMiddleware<State> = (
|
||||
ctx: Context<State>,
|
||||
) => Response | Promise<Response | Middleware<State>>;
|
||||
|
||||
export function runMiddlewares<State>(
|
||||
middlewares: MaybeLazyMiddleware<State>[],
|
||||
ctx: Context<State>,
|
||||
): Promise<Response> {
|
||||
let fn = ctx.next;
|
||||
let i = middlewares.length;
|
||||
while (i--) {
|
||||
const local = fn;
|
||||
let next = middlewares[i];
|
||||
const idx = i;
|
||||
fn = async () => {
|
||||
const internals = getInternals(ctx);
|
||||
const { app: prevApp, layouts: prevLayouts } = internals;
|
||||
|
||||
ctx.next = local;
|
||||
try {
|
||||
const result = await next(ctx);
|
||||
if (typeof result === "function") {
|
||||
middlewares[idx] = result;
|
||||
next = result;
|
||||
return await result(ctx);
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (err) {
|
||||
ctx.error = err;
|
||||
throw err;
|
||||
} finally {
|
||||
internals.app = prevApp;
|
||||
internals.layouts = prevLayouts;
|
||||
}
|
||||
};
|
||||
}
|
||||
return fn();
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
import { runMiddlewares } from "./mod.ts";
|
||||
import { expect } from "@std/expect";
|
||||
import { serveMiddleware } from "../test_utils.ts";
|
||||
import type { Middleware } from "./mod.ts";
|
||||
import type { Lazy, MaybeLazy } from "../types.ts";
|
||||
|
||||
Deno.test("runMiddleware", async () => {
|
||||
const middlewares: Middleware<{ text: string }>[] = [
|
||||
(ctx) => {
|
||||
ctx.state.text = "A";
|
||||
return ctx.next();
|
||||
},
|
||||
(ctx) => {
|
||||
ctx.state.text += "B";
|
||||
return ctx.next();
|
||||
},
|
||||
async (ctx) => {
|
||||
const res = await ctx.next();
|
||||
ctx.state.text += "C"; // This should not show up
|
||||
return res;
|
||||
},
|
||||
(ctx) => {
|
||||
return new Response(ctx.state.text);
|
||||
},
|
||||
];
|
||||
|
||||
const server = serveMiddleware<{ text: string }>((ctx) =>
|
||||
runMiddlewares(middlewares, ctx)
|
||||
);
|
||||
|
||||
const res = await server.get("/");
|
||||
expect(await res.text()).toEqual("AB");
|
||||
});
|
||||
|
||||
Deno.test("runMiddleware - middlewares should only be called once", async () => {
|
||||
const A: Middleware<{ count: number }> = (ctx) => {
|
||||
if (ctx.state.count === undefined) {
|
||||
ctx.state.count = 0;
|
||||
} else {
|
||||
ctx.state.count++;
|
||||
}
|
||||
return ctx.next();
|
||||
};
|
||||
|
||||
const server = serveMiddleware<{ count: number }>((ctx) =>
|
||||
runMiddlewares(
|
||||
[A, (ctx) => new Response(String(ctx.state.count))],
|
||||
ctx,
|
||||
)
|
||||
);
|
||||
|
||||
const res = await server.get("/");
|
||||
expect(await res.text()).toEqual("0");
|
||||
});
|
||||
|
||||
Deno.test("runMiddleware - runs multiple stacks", async () => {
|
||||
type State = { text: string };
|
||||
const A: Middleware<State> = (ctx) => {
|
||||
ctx.state.text += "A";
|
||||
return ctx.next();
|
||||
};
|
||||
const B: Middleware<State> = (ctx) => {
|
||||
ctx.state.text += "B";
|
||||
return ctx.next();
|
||||
};
|
||||
const C: Middleware<State> = (ctx) => {
|
||||
ctx.state.text += "C";
|
||||
return ctx.next();
|
||||
};
|
||||
const D: Middleware<State> = (ctx) => {
|
||||
ctx.state.text += "D";
|
||||
return ctx.next();
|
||||
};
|
||||
|
||||
const server = serveMiddleware<State>((ctx) => {
|
||||
ctx.state.text = "";
|
||||
return runMiddlewares(
|
||||
[
|
||||
A,
|
||||
B,
|
||||
C,
|
||||
D,
|
||||
(ctx) => new Response(String(ctx.state.text)),
|
||||
],
|
||||
ctx,
|
||||
);
|
||||
});
|
||||
|
||||
const res = await server.get("/");
|
||||
expect(await res.text()).toEqual("ABCD");
|
||||
});
|
||||
|
||||
Deno.test("runMiddleware - throws errors", async () => {
|
||||
let thrownA: unknown = null;
|
||||
let thrownB: unknown = null;
|
||||
let thrownC: unknown = null;
|
||||
|
||||
const middlewares: Middleware<{ text: string }>[] = [
|
||||
async (ctx) => {
|
||||
try {
|
||||
return await ctx.next();
|
||||
} catch (err) {
|
||||
thrownA = err;
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
async (ctx) => {
|
||||
try {
|
||||
return await ctx.next();
|
||||
} catch (err) {
|
||||
thrownB = err;
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
async (ctx) => {
|
||||
try {
|
||||
return await ctx.next();
|
||||
} catch (err) {
|
||||
thrownC = err;
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
() => {
|
||||
throw new Error("fail");
|
||||
},
|
||||
];
|
||||
|
||||
const server = serveMiddleware<{ text: string }>((ctx) =>
|
||||
runMiddlewares(middlewares, ctx)
|
||||
);
|
||||
|
||||
try {
|
||||
await server.get("/");
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
expect(thrownA).toBeInstanceOf(Error);
|
||||
expect(thrownB).toBeInstanceOf(Error);
|
||||
expect(thrownC).toBeInstanceOf(Error);
|
||||
});
|
||||
|
||||
Deno.test("runMiddleware - lazy middlewares", async () => {
|
||||
type State = { text: string };
|
||||
|
||||
let called = 0;
|
||||
// deno-lint-ignore require-await
|
||||
const lazy: Lazy<Middleware<State>> = async () => {
|
||||
called++;
|
||||
return (ctx) => {
|
||||
ctx.state.text += "_lazy";
|
||||
return ctx.next();
|
||||
};
|
||||
};
|
||||
|
||||
const middlewares: MaybeLazy<Middleware<State>>[] = [
|
||||
async (ctx) => {
|
||||
ctx.state.text = "A";
|
||||
return await ctx.next();
|
||||
},
|
||||
lazy,
|
||||
(ctx) => {
|
||||
ctx.state.text += "_B";
|
||||
return new Response(ctx.state.text);
|
||||
},
|
||||
];
|
||||
|
||||
const server = serveMiddleware<{ text: string }>((ctx) =>
|
||||
runMiddlewares(middlewares, ctx)
|
||||
);
|
||||
|
||||
let res = await server.get("/");
|
||||
expect(await res.text()).toEqual("A_lazy_B");
|
||||
expect(called).toEqual(1);
|
||||
|
||||
// Lazy middlewares should only be initialized ones
|
||||
res = await server.get("/");
|
||||
expect(await res.text()).toEqual("A_lazy_B");
|
||||
expect(called).toEqual(1);
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
import type { Middleware } from "./mod.ts";
|
||||
import { ASSET_CACHE_BUST_KEY } from "../runtime/shared_internal.tsx";
|
||||
import { BUILD_ID } from "@fresh/build-id";
|
||||
import { tracer } from "../otel.ts";
|
||||
import { getBuildCache } from "../context.ts";
|
||||
|
||||
/**
|
||||
* Fresh middleware to serve static files from the `static/` directory.
|
||||
* ```ts
|
||||
* // Enable Fresh static file serving
|
||||
* app.use(staticFiles());
|
||||
* ```
|
||||
*/
|
||||
export function staticFiles<T>(): Middleware<T> {
|
||||
return async function freshServeStaticFiles(ctx) {
|
||||
const { req, url, config } = ctx;
|
||||
|
||||
const buildCache = getBuildCache(ctx);
|
||||
if (buildCache === null) return await ctx.next();
|
||||
|
||||
let pathname = decodeURIComponent(url.pathname);
|
||||
if (config.basePath) {
|
||||
pathname = pathname !== config.basePath
|
||||
? pathname.slice(config.basePath.length)
|
||||
: "/";
|
||||
}
|
||||
|
||||
// Fast path bail out
|
||||
const startTime = performance.now() + performance.timeOrigin;
|
||||
const file = await buildCache.readFile(pathname);
|
||||
if (pathname === "/" || file === null) {
|
||||
// Optimization: Prevent long responses for favicon.ico requests
|
||||
if (pathname === "/favicon.ico") {
|
||||
return new Response(null, { status: 404 });
|
||||
}
|
||||
return await ctx.next();
|
||||
}
|
||||
|
||||
if (req.method !== "GET" && req.method !== "HEAD") {
|
||||
file.close();
|
||||
return new Response("Method Not Allowed", { status: 405 });
|
||||
}
|
||||
|
||||
const span = tracer.startSpan("static file", {
|
||||
attributes: { "fresh.span_type": "static_file" },
|
||||
startTime,
|
||||
});
|
||||
|
||||
try {
|
||||
const cacheKey = url.searchParams.get(ASSET_CACHE_BUST_KEY);
|
||||
if (cacheKey !== null && BUILD_ID !== cacheKey) {
|
||||
url.searchParams.delete(ASSET_CACHE_BUST_KEY);
|
||||
const location = url.pathname + url.search;
|
||||
file.close();
|
||||
span.setAttribute("fresh.cache", "invalid_bust_key");
|
||||
span.setAttribute("fresh.cache_key", cacheKey);
|
||||
return new Response(null, {
|
||||
status: 307,
|
||||
headers: {
|
||||
location,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const etag = file.hash;
|
||||
const headers = new Headers({
|
||||
"Content-Type": file.contentType,
|
||||
vary: "If-None-Match",
|
||||
});
|
||||
|
||||
const ifNoneMatch = req.headers.get("If-None-Match");
|
||||
if (
|
||||
ifNoneMatch !== null &&
|
||||
(ifNoneMatch === etag || ifNoneMatch === `W/"${etag}"`)
|
||||
) {
|
||||
file.close();
|
||||
span.setAttribute("fresh.cache", "not_modified");
|
||||
return new Response(null, { status: 304, headers });
|
||||
} else if (etag !== null) {
|
||||
headers.set("Etag", `W/"${etag}"`);
|
||||
}
|
||||
|
||||
if (
|
||||
ctx.config.mode !== "development" &&
|
||||
(BUILD_ID === cacheKey ||
|
||||
url.pathname.startsWith(
|
||||
`${ctx.config.basePath}/_fresh/js/${BUILD_ID}/`,
|
||||
))
|
||||
) {
|
||||
span.setAttribute("fresh.cache", "immutable");
|
||||
headers.append("Cache-Control", "public, max-age=31536000, immutable");
|
||||
} else {
|
||||
span.setAttribute("fresh.cache", "no_cache");
|
||||
headers.append(
|
||||
"Cache-Control",
|
||||
"no-cache, no-store, max-age=0, must-revalidate",
|
||||
);
|
||||
}
|
||||
|
||||
headers.set("Content-Length", String(file.size));
|
||||
if (req.method === "HEAD") {
|
||||
file.close();
|
||||
return new Response(null, { status: 200, headers });
|
||||
}
|
||||
|
||||
return new Response(file.readable, { headers });
|
||||
} finally {
|
||||
span.end();
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
import { staticFiles } from "./static_files.ts";
|
||||
import { serveMiddleware } from "../test_utils.ts";
|
||||
import type { BuildCache, StaticFile } from "../build_cache.ts";
|
||||
import { expect } from "@std/expect";
|
||||
import { ASSET_CACHE_BUST_KEY } from "../runtime/shared_internal.tsx";
|
||||
import { BUILD_ID } from "@fresh/build-id";
|
||||
import type { Command } from "../commands.ts";
|
||||
import type { ServerIslandRegistry } from "../context.ts";
|
||||
import { getContentType } from "../dev/dev_build_cache.ts";
|
||||
|
||||
class MockBuildCache implements BuildCache {
|
||||
root = "";
|
||||
buildId = "MockId";
|
||||
files = new Map<string, StaticFile>();
|
||||
islandRegistry: ServerIslandRegistry = new Map();
|
||||
clientEntry = "";
|
||||
features = { errorOverlay: false };
|
||||
|
||||
constructor(files: Record<string, { hash: string | null; content: string }>) {
|
||||
const encoder = new TextEncoder();
|
||||
for (const [pathname, info] of Object.entries(files)) {
|
||||
const text = encoder.encode(info.content);
|
||||
|
||||
const normalized = pathname.startsWith("/") ? pathname : "/" + pathname;
|
||||
this.files.set(normalized, {
|
||||
hash: info.hash,
|
||||
size: text.byteLength,
|
||||
readable: text,
|
||||
contentType: getContentType(normalized),
|
||||
close: () => {},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
getFsRoutes(): Command<any>[] {
|
||||
return [];
|
||||
}
|
||||
|
||||
// deno-lint-ignore require-await
|
||||
async readFile(pathname: string): Promise<StaticFile | null> {
|
||||
return this.files.get(pathname) ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
Deno.test("static files - 200", async () => {
|
||||
const buildCache = new MockBuildCache({
|
||||
"foo.css": { content: "body {}", hash: null },
|
||||
});
|
||||
const server = serveMiddleware(
|
||||
staticFiles(),
|
||||
{ buildCache },
|
||||
);
|
||||
|
||||
const res = await server.get("/foo.css");
|
||||
const content = await res.text();
|
||||
expect(res.status).toEqual(200);
|
||||
expect(res.headers.get("Content-Type")).toEqual("text/css; charset=UTF-8");
|
||||
expect(res.headers.get("Content-Length")).toEqual("7");
|
||||
expect(res.headers.get("Cache-Control")).toEqual(
|
||||
"no-cache, no-store, max-age=0, must-revalidate",
|
||||
);
|
||||
expect(content).toEqual("body {}");
|
||||
});
|
||||
|
||||
Deno.test("static files - HEAD 200", async () => {
|
||||
const buildCache = new MockBuildCache({
|
||||
"foo.css": { content: "body {}", hash: null },
|
||||
});
|
||||
const server = serveMiddleware(
|
||||
staticFiles(),
|
||||
{ buildCache },
|
||||
);
|
||||
|
||||
const res = await server.head("/foo.css");
|
||||
const content = await res.text();
|
||||
expect(res.status).toEqual(200);
|
||||
expect(res.headers.get("Content-Type")).toEqual("text/css; charset=UTF-8");
|
||||
expect(res.headers.get("Content-Length")).toEqual("7");
|
||||
expect(content).toEqual("");
|
||||
});
|
||||
|
||||
Deno.test("static files - etag", async () => {
|
||||
const buildCache = new MockBuildCache({
|
||||
"foo.css": { content: "body {}", hash: "123" },
|
||||
});
|
||||
const server = serveMiddleware(
|
||||
staticFiles(),
|
||||
{ buildCache },
|
||||
);
|
||||
|
||||
const cacheUrl = `/foo.css?${ASSET_CACHE_BUST_KEY}=${BUILD_ID}`;
|
||||
let res = await server.get(cacheUrl);
|
||||
await res.body?.cancel();
|
||||
expect(res.headers.get("Etag")).toEqual('W/"123"');
|
||||
|
||||
let headers = new Headers();
|
||||
headers.append("If-None-Match", "123");
|
||||
res = await server.get(cacheUrl, { headers });
|
||||
await res.body?.cancel();
|
||||
expect(res.status).toEqual(304);
|
||||
|
||||
headers = new Headers();
|
||||
headers.append("If-None-Match", 'W/"123"');
|
||||
res = await server.get(cacheUrl, { headers });
|
||||
await res.body?.cancel();
|
||||
expect(res.status).toEqual(304);
|
||||
});
|
||||
|
||||
Deno.test("static files - 404 on missing favicon.ico", async () => {
|
||||
const buildCache = new MockBuildCache({});
|
||||
const server = serveMiddleware(
|
||||
staticFiles(),
|
||||
{ buildCache },
|
||||
);
|
||||
const res = await server.get("favicon.ico");
|
||||
await res.body?.cancel();
|
||||
expect(res.status).toEqual(404);
|
||||
});
|
||||
|
||||
Deno.test("static files - 405 on wrong HTTP method", async () => {
|
||||
const buildCache = new MockBuildCache({
|
||||
"foo.css": { content: "body {}", hash: null },
|
||||
});
|
||||
const server = serveMiddleware(
|
||||
staticFiles(),
|
||||
{ buildCache },
|
||||
);
|
||||
|
||||
for (const method of ["post", "patch", "put", "delete"]) {
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const res = await (server as any)[method]("/foo.css");
|
||||
await res.body?.cancel();
|
||||
expect(res.status).toEqual(405);
|
||||
}
|
||||
});
|
||||
|
||||
Deno.test("static files - disables caching in development", async () => {
|
||||
const buildCache = new MockBuildCache({
|
||||
"foo.css": { content: "body {}", hash: null },
|
||||
});
|
||||
const server = serveMiddleware(
|
||||
staticFiles(),
|
||||
{
|
||||
buildCache,
|
||||
config: {
|
||||
root: "",
|
||||
basePath: "",
|
||||
mode: "development",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const res = await server.get("/foo.css");
|
||||
await res.body?.cancel();
|
||||
expect(res.status).toEqual(200);
|
||||
expect(res.headers.get("Cache-Control")).toEqual(
|
||||
"no-cache, no-store, max-age=0, must-revalidate",
|
||||
);
|
||||
});
|
||||
|
||||
Deno.test("static files - enables caching in production", async () => {
|
||||
const buildCache = new MockBuildCache({
|
||||
"foo.css": { content: "body {}", hash: null },
|
||||
});
|
||||
const server = serveMiddleware(
|
||||
staticFiles(),
|
||||
{
|
||||
buildCache,
|
||||
config: {
|
||||
root: "",
|
||||
basePath: "",
|
||||
mode: "production",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const res = await server.get(`/foo.css?${ASSET_CACHE_BUST_KEY}=${BUILD_ID}`);
|
||||
await res.body?.cancel();
|
||||
expect(res.status).toEqual(200);
|
||||
expect(res.headers.get("Cache-Control")).toEqual(
|
||||
"public, max-age=31536000, immutable",
|
||||
);
|
||||
});
|
||||
|
||||
Deno.test("static files - decoded pathname", async () => {
|
||||
const buildCache = new MockBuildCache({
|
||||
"C#.svg": { content: "body {}", hash: null },
|
||||
"西安市.png": { content: "body {}", hash: null },
|
||||
"인천.avif": { content: "body {}", hash: null },
|
||||
});
|
||||
const server = serveMiddleware(
|
||||
staticFiles(),
|
||||
{ buildCache },
|
||||
);
|
||||
|
||||
for (
|
||||
const path of [
|
||||
"C%23.svg",
|
||||
"%E8%A5%BF%E5%AE%89%E5%B8%82.png",
|
||||
"%EC%9D%B8%EC%B2%9C.avif",
|
||||
]
|
||||
) {
|
||||
const res = await server.get("/" + path);
|
||||
await res.body?.cancel();
|
||||
expect(res.status).toEqual(200);
|
||||
}
|
||||
});
|
||||
|
||||
Deno.test("static files - fallthrough", async () => {
|
||||
const buildCache = new MockBuildCache({
|
||||
"foo.css": { content: "body {}", hash: null },
|
||||
});
|
||||
|
||||
const server = serveMiddleware(
|
||||
staticFiles(),
|
||||
{ buildCache, next: () => Promise.resolve(new Response("it works")) },
|
||||
);
|
||||
|
||||
let res = await server.get("foo.css");
|
||||
let text = await res.text();
|
||||
expect(text).toEqual("body {}");
|
||||
|
||||
res = await server.get("/");
|
||||
text = await res.text();
|
||||
expect(text).toEqual("it works");
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { Middleware } from "./mod.ts";
|
||||
|
||||
/**
|
||||
* Fresh middleware to force URLs to end with a slash or never end with one.
|
||||
*
|
||||
* ```ts
|
||||
* // Always add trailing slash
|
||||
* app.use(trailingSlashes("always"));
|
||||
* // Never add trailing slashes to URLs and remove them if present
|
||||
* app.use(trailingSlashes("never"));
|
||||
* ```
|
||||
*/
|
||||
export function trailingSlashes<State>(
|
||||
mode: "always" | "never",
|
||||
): Middleware<State> {
|
||||
return function trailingSlashesMiddleware(ctx) {
|
||||
const url = ctx.url;
|
||||
if (url.pathname !== "/") {
|
||||
if (mode === "always" && !url.pathname.endsWith("/")) {
|
||||
return ctx.redirect(`${url.pathname}/${url.search}`);
|
||||
} else if (
|
||||
mode === "never" && url.pathname.endsWith("/")
|
||||
) {
|
||||
return ctx.redirect(`${url.pathname.slice(0, -1)}${url.search}`);
|
||||
}
|
||||
}
|
||||
return ctx.next();
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// deno-lint-ignore-file require-await
|
||||
import { trailingSlashes } from "./trailing_slashes.ts";
|
||||
import { expect } from "@std/expect";
|
||||
import { serveMiddleware } from "../test_utils.ts";
|
||||
|
||||
Deno.test("trailingSlashes - always", async () => {
|
||||
const middleware = trailingSlashes("always");
|
||||
const server = serveMiddleware(middleware, {
|
||||
next: async () => new Response("ok"),
|
||||
});
|
||||
|
||||
let res = await server.get("/");
|
||||
await res.body?.cancel();
|
||||
expect(res.status).toEqual(200);
|
||||
expect(res.headers.get("Location")).toEqual(null);
|
||||
|
||||
res = await server.get("/foo");
|
||||
await res.body?.cancel();
|
||||
expect(res.status).toEqual(302);
|
||||
expect(res.headers.get("Location")).toEqual("/foo/");
|
||||
|
||||
res = await server.get("/foo/bar");
|
||||
await res.body?.cancel();
|
||||
expect(res.status).toEqual(302);
|
||||
expect(res.headers.get("Location")).toEqual("/foo/bar/");
|
||||
|
||||
res = await server.get("/foo/bar/");
|
||||
await res.body?.cancel();
|
||||
expect(res.status).toEqual(200);
|
||||
expect(res.headers.get("Location")).toEqual(null);
|
||||
});
|
||||
|
||||
Deno.test("trailingSlashes - never", async () => {
|
||||
const middleware = trailingSlashes("never");
|
||||
const server = serveMiddleware(middleware, {
|
||||
next: async () => new Response("ok"),
|
||||
});
|
||||
|
||||
let res = await server.get("/");
|
||||
await res.body?.cancel();
|
||||
expect(res.status).toEqual(200);
|
||||
expect(res.headers.get("Location")).toEqual(null);
|
||||
|
||||
res = await server.get("/foo");
|
||||
await res.body?.cancel();
|
||||
expect(res.status).toEqual(200);
|
||||
expect(res.headers.get("Location")).toEqual(null);
|
||||
|
||||
res = await server.get("/foo/");
|
||||
await res.body?.cancel();
|
||||
expect(res.status).toEqual(302);
|
||||
expect(res.headers.get("Location")).toEqual("/foo");
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
export { App, type ListenOptions } from "./app.ts";
|
||||
export { trailingSlashes } from "./middlewares/trailing_slashes.ts";
|
||||
export {
|
||||
type HandlerByMethod,
|
||||
type HandlerFn,
|
||||
page,
|
||||
type PageResponse,
|
||||
type RouteData,
|
||||
type RouteHandler,
|
||||
} from "./handlers.ts";
|
||||
export type { LayoutConfig, Lazy, MaybeLazy, RouteConfig } from "./types.ts";
|
||||
export type { Middleware, MiddlewareFn } from "./middlewares/mod.ts";
|
||||
export { staticFiles } from "./middlewares/static_files.ts";
|
||||
export { csrf, type CsrfOptions } from "./middlewares/csrf.ts";
|
||||
export { cors, type CORSOptions } from "./middlewares/cors.ts";
|
||||
export type { FreshConfig, ResolvedFreshConfig } from "./config.ts";
|
||||
export type { Context, FreshContext, Island } from "./context.ts";
|
||||
export { createDefine, type Define } from "./define.ts";
|
||||
export type { Method } from "./router.ts";
|
||||
export { HttpError } from "./error.ts";
|
||||
export type { PageProps } from "./render.ts";
|
||||
@@ -0,0 +1,18 @@
|
||||
import { type Span, SpanStatusCode, trace } from "@opentelemetry/api";
|
||||
import denoJson from "../deno.json" with { type: "json" };
|
||||
|
||||
export const CURRENT_FRESH_VERSION = denoJson.version;
|
||||
|
||||
export const tracer = trace.getTracer("fresh", CURRENT_FRESH_VERSION);
|
||||
export { trace };
|
||||
|
||||
export function recordSpanError(span: Span, err: unknown) {
|
||||
if (err instanceof Error) {
|
||||
span.recordException(err);
|
||||
} else {
|
||||
span.setStatus({
|
||||
code: SpanStatusCode.ERROR,
|
||||
message: String(err),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
import {
|
||||
type AnyComponent,
|
||||
type FunctionComponent,
|
||||
h,
|
||||
type RenderableProps,
|
||||
type VNode,
|
||||
} from "preact";
|
||||
import {
|
||||
FreshScripts,
|
||||
type RenderState,
|
||||
setRenderState,
|
||||
} from "./runtime/server/preact_hooks.tsx";
|
||||
import type { Context } from "./context.ts";
|
||||
import { recordSpanError, tracer } from "./otel.ts";
|
||||
import { DEV_ERROR_OVERLAY_URL } from "./constants.ts";
|
||||
import { renderToString } from "preact-render-to-string";
|
||||
|
||||
export type AsyncAnyComponent<P> = {
|
||||
(
|
||||
props: RenderableProps<P>,
|
||||
// deno-lint-ignore no-explicit-any
|
||||
context?: any,
|
||||
// deno-lint-ignore no-explicit-any
|
||||
): Promise<VNode<any> | Response | null>;
|
||||
displayName?: string;
|
||||
defaultProps?: Partial<P> | undefined;
|
||||
};
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export function isAsyncAnyComponent(fn: any): fn is AsyncAnyComponent<any> {
|
||||
return typeof fn === "function" && fn.constructor.name === "AsyncFunction";
|
||||
}
|
||||
|
||||
export async function renderAsyncAnyComponent<Props>(
|
||||
fn: AsyncAnyComponent<Props>,
|
||||
props: RenderableProps<Props>,
|
||||
) {
|
||||
return await tracer.startActiveSpan(
|
||||
"invoke async component",
|
||||
async (span) => {
|
||||
span.setAttribute("fresh.span_type", "fs_routes/async_component");
|
||||
try {
|
||||
const result = (await fn(props)) as VNode | Response;
|
||||
span.setAttribute(
|
||||
"fresh.component_response",
|
||||
result instanceof Response ? "http" : "jsx",
|
||||
);
|
||||
return result;
|
||||
} catch (err) {
|
||||
recordSpanError(span, err);
|
||||
throw err;
|
||||
} finally {
|
||||
span.end();
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export function preactRender<State, Data>(
|
||||
vnode: VNode,
|
||||
ctx: PageProps<Data, State>,
|
||||
state: RenderState,
|
||||
headers: Headers,
|
||||
) {
|
||||
try {
|
||||
let res = renderToString(vnode);
|
||||
// We require a the full outer DOM structure so that browser put
|
||||
// comment markers in the right place in the DOM.
|
||||
if (!state.renderedHtmlBody) {
|
||||
let scripts = "";
|
||||
if (ctx.url.pathname !== ctx.config.basePath + DEV_ERROR_OVERLAY_URL) {
|
||||
scripts = renderToString(h(FreshScripts, null));
|
||||
}
|
||||
res = `<body>${res}${scripts}</body>`;
|
||||
}
|
||||
if (!state.renderedHtmlHead) {
|
||||
res = `<head><meta charset="utf-8"></head>${res}`;
|
||||
}
|
||||
if (!state.renderedHtmlTag) {
|
||||
res = `<html>${res}</html>`;
|
||||
}
|
||||
|
||||
return `<!DOCTYPE html>${res}`;
|
||||
} finally {
|
||||
// Add preload headers
|
||||
const basePath = ctx.config.basePath;
|
||||
const runtimeUrl = state.buildCache.clientEntry.startsWith(".")
|
||||
? state.buildCache.clientEntry.slice(1)
|
||||
: state.buildCache.clientEntry;
|
||||
let link = `<${
|
||||
encodeURI(`${basePath}${runtimeUrl}`)
|
||||
}>; rel="modulepreload"; as="script"`;
|
||||
state.islands.forEach((island) => {
|
||||
const specifier = `${basePath}${
|
||||
island.file.startsWith(".") ? island.file.slice(1) : island.file
|
||||
}`;
|
||||
link += `, <${encodeURI(specifier)}>; rel="modulepreload"; as="script"`;
|
||||
});
|
||||
|
||||
if (link !== "") {
|
||||
headers.append("Link", link);
|
||||
}
|
||||
|
||||
state.clear();
|
||||
setRenderState(null);
|
||||
}
|
||||
}
|
||||
|
||||
export type PageProps<Data = unknown, T = unknown> =
|
||||
& Pick<
|
||||
Context<T>,
|
||||
| "config"
|
||||
| "url"
|
||||
| "req"
|
||||
| "params"
|
||||
| "info"
|
||||
| "state"
|
||||
| "isPartial"
|
||||
| "Component"
|
||||
| "error"
|
||||
>
|
||||
& { data: Data };
|
||||
|
||||
export interface ComponentDef<Data, State> {
|
||||
props: PageProps<Data, State> | null;
|
||||
component: AnyComponent<PageProps<Data, State>>;
|
||||
}
|
||||
|
||||
export async function renderRouteComponent<State>(
|
||||
ctx: Context<State>,
|
||||
def: ComponentDef<unknown, State>,
|
||||
child: FunctionComponent,
|
||||
): Promise<VNode | Response> {
|
||||
const vnodeProps: PageProps<unknown, State> = {
|
||||
Component: child,
|
||||
config: ctx.config,
|
||||
data: def.props,
|
||||
error: ctx.error,
|
||||
info: ctx.info,
|
||||
isPartial: ctx.isPartial,
|
||||
params: ctx.params,
|
||||
req: ctx.req,
|
||||
state: ctx.state,
|
||||
url: ctx.url,
|
||||
};
|
||||
|
||||
if (isAsyncAnyComponent(def.component)) {
|
||||
const result = await renderAsyncAnyComponent(def.component, vnodeProps);
|
||||
if (result instanceof Response) {
|
||||
return result;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
return h(def.component, vnodeProps) as VNode;
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
export type Method =
|
||||
| "HEAD"
|
||||
| "GET"
|
||||
| "POST"
|
||||
| "PATCH"
|
||||
| "PUT"
|
||||
| "DELETE"
|
||||
| "OPTIONS";
|
||||
|
||||
export type RouteByMethod<T> = {
|
||||
[m in Method]: T[];
|
||||
};
|
||||
|
||||
export interface StaticRouteDef<T> {
|
||||
pattern: string | URLPattern;
|
||||
byMethod: RouteByMethod<T>;
|
||||
}
|
||||
|
||||
export interface DynamicRouteDef<T> {
|
||||
pattern: URLPattern;
|
||||
byMethod: RouteByMethod<T>;
|
||||
}
|
||||
|
||||
function newByMethod<T>(): RouteByMethod<T> {
|
||||
return {
|
||||
GET: [],
|
||||
POST: [],
|
||||
PATCH: [],
|
||||
DELETE: [],
|
||||
PUT: [],
|
||||
HEAD: [],
|
||||
OPTIONS: [],
|
||||
};
|
||||
}
|
||||
|
||||
export interface RouteResult<T> {
|
||||
params: Record<string, string>;
|
||||
handlers: T[];
|
||||
methodMatch: boolean;
|
||||
pattern: string | null;
|
||||
}
|
||||
|
||||
export interface Router<T> {
|
||||
add(
|
||||
method: Method | "OPTIONS" | "ALL",
|
||||
pathname: string,
|
||||
handlers: T[],
|
||||
): void;
|
||||
match(method: Method, url: URL, init?: T[]): RouteResult<T>;
|
||||
getAllowedMethods(pattern: string): string[];
|
||||
}
|
||||
|
||||
export const IS_PATTERN = /[*:{}+?()]/;
|
||||
|
||||
const EMPTY: string[] = [];
|
||||
|
||||
export class UrlPatternRouter<T> implements Router<T> {
|
||||
#statics = new Map<string, StaticRouteDef<T>>();
|
||||
#dynamics = new Map<string, DynamicRouteDef<T>>();
|
||||
#dynamicArr: DynamicRouteDef<T>[] = [];
|
||||
#allowed = new Map<string, Set<string>>();
|
||||
|
||||
getAllowedMethods(pattern: string): string[] {
|
||||
const allowed = this.#allowed.get(pattern);
|
||||
if (allowed === undefined) return EMPTY;
|
||||
return Array.from(allowed);
|
||||
}
|
||||
|
||||
add(
|
||||
method: Method,
|
||||
pathname: string,
|
||||
handlers: T[],
|
||||
) {
|
||||
let allowed = this.#allowed.get(pathname);
|
||||
if (allowed === undefined) {
|
||||
allowed = new Set();
|
||||
this.#allowed.set(pathname, allowed);
|
||||
}
|
||||
|
||||
allowed.add(method);
|
||||
|
||||
let byMethod: RouteByMethod<T>;
|
||||
if (IS_PATTERN.test(pathname)) {
|
||||
let def = this.#dynamics.get(pathname);
|
||||
if (def === undefined) {
|
||||
def = {
|
||||
pattern: new URLPattern({ pathname }),
|
||||
byMethod: newByMethod(),
|
||||
};
|
||||
this.#dynamics.set(pathname, def);
|
||||
this.#dynamicArr.push(def);
|
||||
}
|
||||
|
||||
byMethod = def.byMethod;
|
||||
} else {
|
||||
let def = this.#statics.get(pathname);
|
||||
if (def === undefined) {
|
||||
def = {
|
||||
pattern: pathname,
|
||||
byMethod: newByMethod(),
|
||||
};
|
||||
this.#statics.set(pathname, def);
|
||||
}
|
||||
|
||||
byMethod = def.byMethod;
|
||||
}
|
||||
|
||||
byMethod[method].push(...handlers);
|
||||
}
|
||||
|
||||
match(method: Method, url: URL, init: T[] = []): RouteResult<T> {
|
||||
const result: RouteResult<T> = {
|
||||
params: Object.create(null),
|
||||
handlers: init,
|
||||
methodMatch: false,
|
||||
pattern: null,
|
||||
};
|
||||
|
||||
const staticMatch = this.#statics.get(url.pathname);
|
||||
if (staticMatch !== undefined) {
|
||||
result.pattern = url.pathname;
|
||||
|
||||
const handlers = staticMatch.byMethod[method];
|
||||
if (handlers.length > 0) {
|
||||
result.methodMatch = true;
|
||||
result.handlers.push(...handlers);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
for (let i = 0; i < this.#dynamicArr.length; i++) {
|
||||
const route = this.#dynamicArr[i];
|
||||
|
||||
const match = route.pattern.exec(url);
|
||||
if (match === null) continue;
|
||||
|
||||
result.pattern = route.pattern.pathname;
|
||||
|
||||
const handlers = route.byMethod[method];
|
||||
if (handlers.length > 0) {
|
||||
result.methodMatch = true;
|
||||
result.handlers.push(...handlers);
|
||||
|
||||
// Decode matched params
|
||||
for (const [key, value] of Object.entries(match.pathname.groups)) {
|
||||
result.params[key] = value === undefined ? "" : decodeURI(value);
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform a filesystem URL path to a `path-to-regex` style matcher.
|
||||
*/
|
||||
export function pathToPattern(
|
||||
path: string,
|
||||
options?: { keepGroups: boolean },
|
||||
): string {
|
||||
const parts = path.split("/");
|
||||
if (parts[parts.length - 1] === "index") {
|
||||
if (parts.length === 1) {
|
||||
return "/";
|
||||
}
|
||||
parts.pop();
|
||||
}
|
||||
|
||||
let route = "";
|
||||
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const part = parts[i];
|
||||
|
||||
// Case: /[...foo].tsx
|
||||
if (part.startsWith("[...") && part.endsWith("]")) {
|
||||
route += `/:${part.slice(4, part.length - 1)}*`;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Route groups like /foo/(bar) should not be included in URL
|
||||
// matching. They are transparent and need to be removed here.
|
||||
// Case: /foo/(bar) -> /foo
|
||||
// Case: /foo/(bar)/bob -> /foo/bob
|
||||
// Case: /(foo)/bar -> /bar
|
||||
if (!options?.keepGroups && part.startsWith("(") && part.endsWith(")")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Disallow neighbouring params like `/[id][bar].tsx` because
|
||||
// it's ambiguous where the `id` param ends and `bar` begins.
|
||||
if (part.includes("][")) {
|
||||
throw new SyntaxError(
|
||||
`Invalid route pattern: "${path}". A parameter cannot be followed by another parameter without any characters in between.`,
|
||||
);
|
||||
}
|
||||
|
||||
// Case: /[[id]].tsx
|
||||
// Case: /[id].tsx
|
||||
// Case: /[id]@[bar].tsx
|
||||
// Case: /[id]-asdf.tsx
|
||||
// Case: /[id]-asdf[bar].tsx
|
||||
// Case: /asdf[bar].tsx
|
||||
let pattern = "";
|
||||
let groupOpen = 0;
|
||||
let optional = false;
|
||||
for (let j = 0; j < part.length; j++) {
|
||||
const char = part[j];
|
||||
if (char === "[") {
|
||||
if (part[j + 1] === "[") {
|
||||
// Disallow optional dynamic params like `foo-[[bar]]`
|
||||
if (part[j - 1] !== "/" && !!part[j - 1]) {
|
||||
throw new SyntaxError(
|
||||
`Invalid route pattern: "${path}". An optional parameter needs to be a full segment.`,
|
||||
);
|
||||
}
|
||||
groupOpen++;
|
||||
optional = true;
|
||||
pattern += "{/";
|
||||
j++;
|
||||
}
|
||||
pattern += ":";
|
||||
groupOpen++;
|
||||
} else if (char === "]") {
|
||||
if (part[j + 1] === "]") {
|
||||
// Disallow optional dynamic params like `[[foo]]-bar`
|
||||
if (part[j + 2] !== "/" && !!part[j + 2]) {
|
||||
throw new SyntaxError(
|
||||
`Invalid route pattern: "${path}". An optional parameter needs to be a full segment.`,
|
||||
);
|
||||
}
|
||||
groupOpen--;
|
||||
pattern += "}?";
|
||||
j++;
|
||||
}
|
||||
if (--groupOpen < 0) {
|
||||
throw new SyntaxError(`Invalid route pattern: "${path}"`);
|
||||
}
|
||||
} else {
|
||||
pattern += char;
|
||||
}
|
||||
}
|
||||
|
||||
route += (optional ? "" : "/") + pattern;
|
||||
}
|
||||
|
||||
// Case: /(group)/index.tsx
|
||||
if (route === "") {
|
||||
route = "/";
|
||||
}
|
||||
|
||||
return route;
|
||||
}
|
||||
|
||||
export function patternToSegments(
|
||||
path: string,
|
||||
root: string,
|
||||
includeLast: boolean = false,
|
||||
): string[] {
|
||||
const out: string[] = [root];
|
||||
|
||||
if (path === "/" || path === "*" || path === "/*") return out;
|
||||
|
||||
let start = -1;
|
||||
for (let i = 0; i < path.length; i++) {
|
||||
const ch = path[i];
|
||||
|
||||
if (ch === "/") {
|
||||
if (i > 0) {
|
||||
const raw = path.slice(start + 1, i);
|
||||
out.push(raw);
|
||||
}
|
||||
start = i;
|
||||
}
|
||||
}
|
||||
|
||||
if (includeLast && start < path.length - 1) {
|
||||
out.push(path.slice(start + 1));
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
export function mergePath(basePath: string, path: string): string {
|
||||
if (basePath.endsWith("*")) basePath = basePath.slice(0, -1);
|
||||
if (basePath === "/") basePath = "";
|
||||
|
||||
if (path === "*") path = "";
|
||||
else if (path === "/*") path = "/*";
|
||||
|
||||
const s = (basePath !== "" && path === "/") ? "" : path;
|
||||
return basePath + s;
|
||||
}
|
||||
|
||||
export function toRoutePath(path: string): string {
|
||||
if (path === "") return "*";
|
||||
return path;
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
import { expect } from "@std/expect";
|
||||
import {
|
||||
IS_PATTERN,
|
||||
mergePath,
|
||||
pathToPattern,
|
||||
patternToSegments,
|
||||
UrlPatternRouter,
|
||||
} from "./router.ts";
|
||||
|
||||
Deno.test("IS_PATTERN", () => {
|
||||
expect(IS_PATTERN.test("/foo")).toEqual(false);
|
||||
expect(IS_PATTERN.test("/foo/bar/baz.jpg")).toEqual(false);
|
||||
expect(IS_PATTERN.test("/foo/:path")).toEqual(true);
|
||||
expect(IS_PATTERN.test("/foo/*")).toEqual(true);
|
||||
expect(IS_PATTERN.test("/foo{/bar}?")).toEqual(true);
|
||||
expect(IS_PATTERN.test("/foo/(\\d+)")).toEqual(true);
|
||||
expect(IS_PATTERN.test("/foo/(a)")).toEqual(true);
|
||||
});
|
||||
|
||||
Deno.test("UrlPatternRouter - GET extract params", () => {
|
||||
const router = new UrlPatternRouter();
|
||||
const A = () => {};
|
||||
router.add("GET", "/:foo/:bar/c", [A]);
|
||||
|
||||
let res = router.match("GET", new URL("/a/b/c", "http://localhost"));
|
||||
expect(res).toEqual({
|
||||
params: { foo: "a", bar: "b" },
|
||||
handlers: [A],
|
||||
methodMatch: true,
|
||||
pattern: "/:foo/:bar/c",
|
||||
});
|
||||
|
||||
// Decode params
|
||||
res = router.match("GET", new URL("/a%20a/b/c", "http://localhost"));
|
||||
expect(res).toEqual({
|
||||
params: { foo: "a a", bar: "b" },
|
||||
handlers: [A],
|
||||
methodMatch: true,
|
||||
pattern: "/:foo/:bar/c",
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("UrlPatternRouter - Wrong method match", () => {
|
||||
const router = new UrlPatternRouter();
|
||||
const A = () => {};
|
||||
router.add("GET", "/foo", [A]);
|
||||
|
||||
const res = router.match("POST", new URL("/foo", "http://localhost"));
|
||||
expect(res).toEqual({
|
||||
params: Object.create(null),
|
||||
handlers: [],
|
||||
methodMatch: false,
|
||||
pattern: "/foo",
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("UrlPatternRouter - wrong + correct method", () => {
|
||||
const router = new UrlPatternRouter();
|
||||
const A = () => {};
|
||||
const B = () => {};
|
||||
router.add("GET", "/foo", [A]);
|
||||
router.add("POST", "/foo", [B]);
|
||||
|
||||
const res = router.match("POST", new URL("/foo", "http://localhost"));
|
||||
expect(res).toEqual({
|
||||
params: Object.create(null),
|
||||
handlers: [B],
|
||||
methodMatch: true,
|
||||
pattern: "/foo",
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("UrlPatternRouter - convert patterns automatically", () => {
|
||||
const router = new UrlPatternRouter();
|
||||
const A = () => {};
|
||||
router.add("GET", "/books/:id", [A]);
|
||||
|
||||
const res = router.match("GET", new URL("/books/foo", "http://localhost"));
|
||||
expect(res).toEqual({
|
||||
params: {
|
||||
id: "foo",
|
||||
},
|
||||
handlers: [A],
|
||||
methodMatch: true,
|
||||
pattern: "/books/:id",
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("pathToPattern", async (t) => {
|
||||
await t.step("creates pattern", () => {
|
||||
expect(pathToPattern("foo/bar")).toEqual("/foo/bar");
|
||||
});
|
||||
|
||||
await t.step("parses index routes", () => {
|
||||
expect(pathToPattern("foo/index")).toEqual("/foo");
|
||||
});
|
||||
|
||||
await t.step("parses parameters", () => {
|
||||
expect(pathToPattern("foo/[name]")).toEqual("/foo/:name");
|
||||
expect(pathToPattern("foo/[name]/bar/[bob]")).toEqual(
|
||||
"/foo/:name/bar/:bob",
|
||||
);
|
||||
});
|
||||
|
||||
await t.step("parses catchall", () => {
|
||||
expect(pathToPattern("foo/[...name]")).toEqual("/foo/:name*");
|
||||
});
|
||||
|
||||
await t.step("parses multiple params in same part", () => {
|
||||
expect(pathToPattern("foo/[mod]@[version]")).toEqual("/foo/:mod@:version");
|
||||
expect(pathToPattern("foo/[bar].json")).toEqual("/foo/:bar.json");
|
||||
expect(pathToPattern("foo/foo[bar]")).toEqual("/foo/foo:bar");
|
||||
});
|
||||
|
||||
await t.step("parses optional params", () => {
|
||||
expect(pathToPattern("foo/[[name]]")).toEqual("/foo{/:name}?");
|
||||
expect(pathToPattern("foo/[name]/[[bob]]")).toEqual("/foo/:name{/:bob}?");
|
||||
expect(pathToPattern("foo/[[name]]/bar")).toEqual("/foo{/:name}?/bar");
|
||||
expect(
|
||||
pathToPattern("foo/[[name]]/bar/[[bob]]"),
|
||||
).toEqual(
|
||||
"/foo{/:name}?/bar{/:bob}?",
|
||||
);
|
||||
});
|
||||
|
||||
await t.step("throws on invalid patterns", () => {
|
||||
expect(() => pathToPattern("foo/[foo][bar]")).toThrow();
|
||||
expect(() => pathToPattern("foo/foo]")).toThrow();
|
||||
expect(() => pathToPattern("foo/[foo]]")).toThrow();
|
||||
expect(() => pathToPattern("foo/foo-[[name]]-bar/baz")).toThrow();
|
||||
expect(() => pathToPattern("foo/[[name]]-bar/baz")).toThrow();
|
||||
expect(() => pathToPattern("foo/foo-[[name]]/baz")).toThrow();
|
||||
expect(() => pathToPattern("foo/foo-[[name]]")).toThrow();
|
||||
expect(() => pathToPattern("foo/[[name]]-bar")).toThrow();
|
||||
});
|
||||
|
||||
await t.step("keep groups", () => {
|
||||
expect(pathToPattern("foo/(foo)/bar", { keepGroups: true })).toEqual(
|
||||
"/foo/(foo)/bar",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("patternToSegments", () => {
|
||||
expect(patternToSegments("/", "")).toEqual([""]);
|
||||
expect(patternToSegments("/foo", "")).toEqual([""]);
|
||||
expect(patternToSegments("/foo/bar", "")).toEqual(["", "foo"]);
|
||||
|
||||
expect(patternToSegments("/:foo", "")).toEqual([""]);
|
||||
expect(patternToSegments("/:foo/:bar", "")).toEqual(["", ":foo"]);
|
||||
expect(patternToSegments("/:foo-:bar/foo", "")).toEqual(["", ":foo-:bar"]);
|
||||
expect(patternToSegments("/foo/", "")).toEqual(["", "foo"]);
|
||||
|
||||
expect(patternToSegments("/foo/bar", "", true)).toEqual(["", "foo", "bar"]);
|
||||
});
|
||||
|
||||
Deno.test("mergePath", () => {
|
||||
expect(mergePath("", "/foo")).toEqual("/foo");
|
||||
expect(mergePath("/", "/foo")).toEqual("/foo");
|
||||
expect(mergePath("/foo/bar", "/")).toEqual("/foo/bar");
|
||||
expect(mergePath("/foo/bar", "/baz")).toEqual("/foo/bar/baz");
|
||||
expect(mergePath("*", "/baz")).toEqual("/baz");
|
||||
expect(mergePath("/*", "/baz")).toEqual("/baz");
|
||||
expect(mergePath("/foo", "*")).toEqual("/foo");
|
||||
expect(mergePath("/foo", "/*")).toEqual("/foo/*");
|
||||
});
|
||||
@@ -0,0 +1,136 @@
|
||||
import "preact/debug";
|
||||
export * from "./mod.tsx";
|
||||
import { IS_BROWSER } from "../shared.ts";
|
||||
|
||||
let ws: WebSocket;
|
||||
let revision = 0;
|
||||
|
||||
let reconnectTimer: number;
|
||||
const backoff = [
|
||||
// Wait 100ms initially, because we could also be
|
||||
// disconnected because of a form submit.
|
||||
100,
|
||||
150,
|
||||
200,
|
||||
250,
|
||||
300,
|
||||
350,
|
||||
400,
|
||||
450,
|
||||
500,
|
||||
500,
|
||||
605,
|
||||
750,
|
||||
1000,
|
||||
1250,
|
||||
1500,
|
||||
1750,
|
||||
2000,
|
||||
];
|
||||
let backoffIdx = 0;
|
||||
function reconnect() {
|
||||
if (ws.readyState !== ws.CLOSED) return;
|
||||
|
||||
reconnectTimer = setTimeout(() => {
|
||||
if (backoffIdx === 0) {
|
||||
// deno-lint-ignore no-console
|
||||
console.log(
|
||||
`%c Fresh %c Connection closed. Trying to reconnect...`,
|
||||
"background-color: #86efac; color: black",
|
||||
"color: inherit",
|
||||
);
|
||||
}
|
||||
backoffIdx++;
|
||||
|
||||
try {
|
||||
connect();
|
||||
clearTimeout(reconnectTimer);
|
||||
} catch (_err) {
|
||||
reconnect();
|
||||
}
|
||||
}, backoff[Math.min(backoffIdx, backoff.length - 1)]);
|
||||
}
|
||||
|
||||
function onOpenWs() {
|
||||
backoffIdx = 0;
|
||||
}
|
||||
|
||||
function onCloseWs() {
|
||||
disconnect();
|
||||
reconnect();
|
||||
}
|
||||
|
||||
function connect() {
|
||||
const url = new URL("/_frsh/alive", location.origin.replace("http", "ws"));
|
||||
ws = new WebSocket(
|
||||
url,
|
||||
);
|
||||
|
||||
ws.addEventListener("open", onOpenWs);
|
||||
ws.addEventListener("close", onCloseWs);
|
||||
ws.addEventListener("message", handleMessage);
|
||||
ws.addEventListener("error", handleError);
|
||||
}
|
||||
|
||||
function disconnect() {
|
||||
ws.removeEventListener("open", onOpenWs);
|
||||
ws.removeEventListener("close", onCloseWs);
|
||||
ws.removeEventListener("message", handleMessage);
|
||||
ws.removeEventListener("error", handleError);
|
||||
ws.close();
|
||||
}
|
||||
|
||||
function handleMessage(e: MessageEvent) {
|
||||
const data = JSON.parse(e.data);
|
||||
switch (data.type) {
|
||||
case "initial-state": {
|
||||
if (revision === 0) {
|
||||
// deno-lint-ignore no-console
|
||||
console.log(
|
||||
`%c Fresh %c Connected to development server.`,
|
||||
"background-color: #86efac; color: black",
|
||||
"color: inherit",
|
||||
);
|
||||
}
|
||||
|
||||
if (revision === 0) {
|
||||
revision = data.revision;
|
||||
} else if (revision < data.revision) {
|
||||
disconnect();
|
||||
// Needs reload
|
||||
location.reload();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function handleError(e: Event) {
|
||||
// TODO
|
||||
// deno-lint-ignore no-explicit-any
|
||||
if (e && (e as any).code === "ECONNREFUSED") {
|
||||
setTimeout(connect, 1000);
|
||||
}
|
||||
}
|
||||
|
||||
if (IS_BROWSER) {
|
||||
connect();
|
||||
|
||||
addEventListener("message", (ev) => {
|
||||
if (ev.origin !== location.origin) return;
|
||||
if (typeof ev.data !== "string" || ev.data !== "close-error-overlay") {
|
||||
return;
|
||||
}
|
||||
|
||||
document.querySelector("#fresh-error-overlay")?.remove();
|
||||
});
|
||||
|
||||
// Disconnect when the tab becomes inactive and re-connect when it
|
||||
// becomes active again
|
||||
addEventListener("visibilitychange", () => {
|
||||
if (document.hidden) {
|
||||
disconnect();
|
||||
} else {
|
||||
connect();
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import "./polyfills.ts";
|
||||
import "./preact_hooks_client.ts";
|
||||
import "./partials.ts";
|
||||
export { asset, IS_BROWSER, Partial, type PartialProps } from "../shared.ts";
|
||||
export { boot, revive } from "./reviver.ts";
|
||||
@@ -0,0 +1,520 @@
|
||||
import { type ComponentChildren, h } from "preact";
|
||||
import {
|
||||
CLIENT_NAV_ATTR,
|
||||
DATA_ANCESTOR,
|
||||
DATA_CURRENT,
|
||||
matchesUrl,
|
||||
PartialMode,
|
||||
UrlMatchKind,
|
||||
} from "../shared_internal.tsx";
|
||||
import {
|
||||
ACTIVE_PARTIALS,
|
||||
copyOldChildren,
|
||||
CUSTOM_PARSER,
|
||||
type DeserializedProps,
|
||||
domToVNode,
|
||||
ISLAND_REGISTRY,
|
||||
Marker,
|
||||
maybeHideMarker,
|
||||
PartialComp,
|
||||
} from "./reviver.ts";
|
||||
import { createRootFragment, isCommentNode, isElementNode } from "./reviver.ts";
|
||||
import type { PartialStateJson } from "../server/preact_hooks.tsx";
|
||||
import { parse } from "../../jsonify/parse.ts";
|
||||
import { INTERNAL_PREFIX, PARTIAL_SEARCH_PARAM } from "../../constants.ts";
|
||||
|
||||
export const PARTIAL_ATTR = "f-partial";
|
||||
|
||||
class NoPartialsError extends Error {}
|
||||
|
||||
// Fresh partials history updates set the fClientNav flag
|
||||
// and prevent reloads in the popstate handler when
|
||||
// user-code triggers history navigation events.
|
||||
export interface FreshHistoryState {
|
||||
fClientNav: boolean;
|
||||
index: number;
|
||||
scrollX: number;
|
||||
scrollY: number;
|
||||
}
|
||||
|
||||
function checkClientNavEnabled(el: HTMLElement) {
|
||||
const setting = el.closest(`[${CLIENT_NAV_ATTR}]`);
|
||||
if (setting === null) return false;
|
||||
return setting.getAttribute(CLIENT_NAV_ATTR) !== "false";
|
||||
}
|
||||
|
||||
// Keep track of history state to apply forward or backward animations
|
||||
let index = history.state?.index || 0;
|
||||
if (!history.state) {
|
||||
const state: FreshHistoryState = {
|
||||
fClientNav: true,
|
||||
index,
|
||||
scrollX,
|
||||
scrollY,
|
||||
};
|
||||
history.replaceState(state, document.title);
|
||||
}
|
||||
|
||||
function maybeUpdateHistory(nextUrl: URL) {
|
||||
// Only add history entry when URL is new. Still apply
|
||||
// the partials because sometimes users click a link to
|
||||
// "refresh" the current page.
|
||||
if (nextUrl.href !== globalThis.location.href) {
|
||||
const state: FreshHistoryState = {
|
||||
fClientNav: true,
|
||||
index,
|
||||
scrollX: globalThis.scrollX,
|
||||
scrollY: globalThis.scrollY,
|
||||
};
|
||||
|
||||
// Store current scroll position
|
||||
history.replaceState({ ...state }, "", location.href);
|
||||
|
||||
// Now store the new position
|
||||
index++;
|
||||
state.scrollX = 0;
|
||||
state.scrollY = 0;
|
||||
history.pushState(state, "", nextUrl.href);
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener("click", async (e) => {
|
||||
let el = e.target;
|
||||
if (el && (el instanceof HTMLElement || el instanceof SVGElement)) {
|
||||
const originalEl = el;
|
||||
|
||||
// Check if we clicked inside an anchor link
|
||||
if (el.nodeName !== "A") {
|
||||
el = el.closest("a");
|
||||
}
|
||||
if (el === null) {
|
||||
el = originalEl.closest("button");
|
||||
}
|
||||
|
||||
if (
|
||||
// Check that we're still dealing with an anchor tag
|
||||
el && el instanceof HTMLAnchorElement &&
|
||||
// Check if it's an internal link
|
||||
el.href && (!el.target || el.target === "_self") &&
|
||||
el.origin === location.origin &&
|
||||
// Check if it was a left click and not a right click
|
||||
e.button === 0 &&
|
||||
// Check that the user doesn't press a key combo to open the
|
||||
// link in a new tab or something
|
||||
!(e.ctrlKey || e.metaKey || e.altKey || e.shiftKey || e.button) &&
|
||||
// Check that the event isn't aborted already
|
||||
!e.defaultPrevented
|
||||
) {
|
||||
const partial = el.getAttribute(PARTIAL_ATTR);
|
||||
|
||||
// Check if the user opted out of client side navigation or if
|
||||
// we're doing a fragment navigation.
|
||||
if (
|
||||
el.getAttribute("href")?.startsWith("#") ||
|
||||
!checkClientNavEnabled(el)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const indicator = (el as any)._freshIndicator;
|
||||
if (indicator !== undefined) {
|
||||
indicator.value = true;
|
||||
}
|
||||
|
||||
e.preventDefault();
|
||||
|
||||
const nextUrl = new URL(el.href);
|
||||
try {
|
||||
maybeUpdateHistory(nextUrl);
|
||||
|
||||
const partialUrl = new URL(
|
||||
partial ? partial : nextUrl.href,
|
||||
location.href,
|
||||
);
|
||||
await fetchPartials(nextUrl, partialUrl);
|
||||
updateLinks(nextUrl);
|
||||
scrollTo({ left: 0, top: 0, behavior: "instant" });
|
||||
} finally {
|
||||
if (indicator !== undefined) {
|
||||
indicator.value = false;
|
||||
}
|
||||
}
|
||||
} else if (
|
||||
el && el instanceof HTMLButtonElement &&
|
||||
(el.type !== "submit" || el.form === null)
|
||||
) {
|
||||
const partial = el.getAttribute(PARTIAL_ATTR);
|
||||
|
||||
// Check if the user opted out of client side navigation.
|
||||
if (partial === null || !checkClientNavEnabled(el)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const partialUrl = new URL(
|
||||
partial,
|
||||
location.href,
|
||||
);
|
||||
await fetchPartials(partialUrl, partialUrl);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
addEventListener("popstate", async (e) => {
|
||||
// When state is `null` then the browser navigated to a document
|
||||
// fragment. In this case we do nothing.
|
||||
if (e.state === null) {
|
||||
// Reset to browser default
|
||||
if (history.scrollRestoration) {
|
||||
history.scrollRestoration = "auto";
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Do nothing if Fresh navigation is not explicitly opted-in.
|
||||
// Other applications might manage scrollRestoration individually.
|
||||
if (!e.state.fClientNav) return;
|
||||
|
||||
const state: FreshHistoryState = history.state;
|
||||
const nextIdx = state.index ?? index + 1;
|
||||
index = nextIdx;
|
||||
|
||||
const setting = document.querySelector(`[${CLIENT_NAV_ATTR}]`);
|
||||
if (setting === null || setting.getAttribute(CLIENT_NAV_ATTR) === "false") {
|
||||
location.reload();
|
||||
return;
|
||||
}
|
||||
|
||||
// We need to keep track of that ourselves since we do client side
|
||||
// navigation.
|
||||
if (history.scrollRestoration) {
|
||||
history.scrollRestoration = "manual";
|
||||
}
|
||||
|
||||
const url = new URL(location.href, location.origin);
|
||||
try {
|
||||
await fetchPartials(url, url);
|
||||
updateLinks(url);
|
||||
scrollTo({
|
||||
left: state.scrollX ?? 0,
|
||||
top: state.scrollY ?? 0,
|
||||
behavior: "instant",
|
||||
});
|
||||
} catch (err) {
|
||||
// If the response didn't contain a partial, then we can only
|
||||
// do a reload.
|
||||
if (err instanceof NoPartialsError) {
|
||||
location.reload();
|
||||
return;
|
||||
}
|
||||
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
// Form submit
|
||||
document.addEventListener("submit", async (e) => {
|
||||
const el = e.target;
|
||||
if (el !== null && el instanceof HTMLFormElement && !e.defaultPrevented) {
|
||||
if (
|
||||
// Check if form has client nav enabled
|
||||
!checkClientNavEnabled(el) ||
|
||||
// Bail out if submitter is set and client nav is disabled
|
||||
(e.submitter !== null && !checkClientNavEnabled(e.submitter))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const lowerMethod =
|
||||
e.submitter?.getAttribute("formmethod")?.toLowerCase() ??
|
||||
el.method.toLowerCase();
|
||||
if (lowerMethod !== "get" && lowerMethod !== "post") {
|
||||
return;
|
||||
}
|
||||
|
||||
const rawPartialUrl = e.submitter?.getAttribute(PARTIAL_ATTR) ??
|
||||
e.submitter?.getAttribute("formaction") ??
|
||||
el.getAttribute(PARTIAL_ATTR) ?? el.action;
|
||||
const rawActionUrl = e.submitter?.getAttribute("formaction") ?? el.action;
|
||||
|
||||
if (rawPartialUrl !== "") {
|
||||
e.preventDefault();
|
||||
|
||||
const partialUrl = new URL(rawPartialUrl, location.href);
|
||||
const actionUrl = new URL(rawActionUrl, location.href);
|
||||
|
||||
let init: RequestInit | undefined;
|
||||
|
||||
// GET method appends form data via url search params
|
||||
if (lowerMethod === "get") {
|
||||
// TODO: Looks like constructor type for URLSearchParam is wrong
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const qs = new URLSearchParams(new FormData(el, e.submitter) as any);
|
||||
qs.forEach((value, key) => partialUrl.searchParams.append(key, value));
|
||||
} else {
|
||||
init = { body: new FormData(el, e.submitter), method: lowerMethod };
|
||||
}
|
||||
|
||||
await fetchPartials(actionUrl, partialUrl, init);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
function updateLinks(url: URL) {
|
||||
document.querySelectorAll("a").forEach((link) => {
|
||||
const match = matchesUrl(url.pathname, link.href);
|
||||
|
||||
if (match === UrlMatchKind.Current) {
|
||||
link.setAttribute(DATA_CURRENT, "true");
|
||||
link.setAttribute("aria-current", "page");
|
||||
link.removeAttribute(DATA_ANCESTOR);
|
||||
} else if (match === UrlMatchKind.Ancestor) {
|
||||
link.setAttribute(DATA_ANCESTOR, "true");
|
||||
link.setAttribute("aria-current", "true");
|
||||
link.removeAttribute(DATA_CURRENT);
|
||||
} else {
|
||||
link.removeAttribute(DATA_CURRENT);
|
||||
link.removeAttribute(DATA_ANCESTOR);
|
||||
link.removeAttribute("aria-current");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function fetchPartials(
|
||||
actualUrl: URL,
|
||||
partialUrl: URL,
|
||||
init: RequestInit = {},
|
||||
) {
|
||||
init.redirect = "follow";
|
||||
partialUrl = new URL(partialUrl);
|
||||
partialUrl.searchParams.set(PARTIAL_SEARCH_PARAM, "true");
|
||||
const res = await fetch(partialUrl, init);
|
||||
|
||||
if (res.redirected) {
|
||||
const nextUrl = new URL(res.url);
|
||||
if (nextUrl.origin === actualUrl.origin) {
|
||||
actualUrl = nextUrl;
|
||||
}
|
||||
}
|
||||
|
||||
maybeUpdateHistory(actualUrl);
|
||||
await applyPartials(res);
|
||||
}
|
||||
|
||||
interface PartialReviveCtx {
|
||||
foundPartials: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply partials from a HTML response
|
||||
*/
|
||||
export async function applyPartials(res: Response): Promise<void> {
|
||||
const contentType = res.headers.get("Content-Type");
|
||||
if (contentType !== "text/html; charset=utf-8") {
|
||||
throw new Error(`Unable to process partial response.`);
|
||||
}
|
||||
|
||||
const id = res.headers.get("X-Fresh-Id");
|
||||
|
||||
const resText = await res.text();
|
||||
const doc = new DOMParser().parseFromString(resText, "text/html") as Document;
|
||||
|
||||
const state = doc.querySelector(`#__FRSH_STATE_${id}`);
|
||||
let allProps: DeserializedProps = [];
|
||||
if (state !== null) {
|
||||
const json = JSON.parse(state.textContent!) as PartialStateJson;
|
||||
const promises: Promise<void>[] = [];
|
||||
|
||||
allProps = parse<DeserializedProps>(json.props, CUSTOM_PARSER);
|
||||
|
||||
for (let i = 0; i < json.islands.length; i++) {
|
||||
const island = json.islands[i];
|
||||
promises.push(
|
||||
import(/* @vite-ignore */ island.chunk).then((mod) => {
|
||||
ISLAND_REGISTRY.set(island.name, mod[island.exportName]);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
await Promise.all(promises);
|
||||
}
|
||||
|
||||
const ctx: PartialReviveCtx = {
|
||||
foundPartials: 0,
|
||||
};
|
||||
|
||||
if (doc.title) {
|
||||
document.title = doc.title;
|
||||
}
|
||||
|
||||
// Needs to be converted to an array otherwise somehow <link>-tags
|
||||
// are missing.
|
||||
Array.from(doc.head.childNodes).forEach((childNode) => {
|
||||
const child = childNode as HTMLElement;
|
||||
|
||||
if (child.nodeName === "TITLE") return;
|
||||
if (child.nodeName === "META") {
|
||||
const meta = child as HTMLMetaElement;
|
||||
|
||||
// Ignore charset which is usually set site wide anyway
|
||||
if (meta.hasAttribute("charset")) return;
|
||||
|
||||
const name = meta.name;
|
||||
if (name !== "") {
|
||||
const existing = document.head.querySelector(`meta[name="${name}"]`) as
|
||||
| HTMLMetaElement
|
||||
| null;
|
||||
if (existing !== null) {
|
||||
if (existing.content !== meta.content) {
|
||||
existing.content = meta.content;
|
||||
}
|
||||
} else {
|
||||
document.head.appendChild(meta);
|
||||
}
|
||||
} else {
|
||||
const property = child.getAttribute("property");
|
||||
const existing = document.head.querySelector(
|
||||
`meta[property="${property}"]`,
|
||||
) as HTMLMetaElement | null;
|
||||
if (existing !== null) {
|
||||
if (existing.content !== meta.content) {
|
||||
existing.content = meta.content;
|
||||
}
|
||||
} else {
|
||||
document.head.appendChild(meta);
|
||||
}
|
||||
}
|
||||
} else if (child.nodeName === "LINK") {
|
||||
const link = child as HTMLLinkElement;
|
||||
if (link.rel === "modulepreload") return;
|
||||
if (link.rel === "stylesheet") {
|
||||
// The `href` attribute may be root relative. This ensures
|
||||
// that they both have the same format
|
||||
const existing = Array.from(document.head.querySelectorAll("link"))
|
||||
.find((existingLink) => existingLink.href === link.href);
|
||||
if (existing === undefined) {
|
||||
document.head.appendChild(link);
|
||||
}
|
||||
}
|
||||
} else if (child.nodeName === "SCRIPT") {
|
||||
const script = child as HTMLScriptElement;
|
||||
if (script.src === `${INTERNAL_PREFIX}/fresh-runtime.js`) return;
|
||||
// TODO: What to do with script tags?
|
||||
} else if (child.nodeName === "STYLE") {
|
||||
const style = child as HTMLStyleElement;
|
||||
// TODO: Do we need a smarter merging strategy?
|
||||
// Don't overwrie existing style sheets that are flagged as unique
|
||||
if (style.id === "") {
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
revivePartials(ctx, allProps, doc.body);
|
||||
|
||||
if (ctx.foundPartials === 0) {
|
||||
throw new NoPartialsError(
|
||||
`Found no partials in HTML response. Please make sure to render at least one partial. Requested url: ${res.url}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function revivePartials(
|
||||
ctx: PartialReviveCtx,
|
||||
allProps: DeserializedProps,
|
||||
node: Element,
|
||||
) {
|
||||
let startNode = null;
|
||||
let sib: ChildNode | null = node.firstChild;
|
||||
let partialCount = 0;
|
||||
let partialName = "";
|
||||
let partialKey = "";
|
||||
let partialMode = PartialMode.Replace;
|
||||
while (sib !== null) {
|
||||
if (isCommentNode(sib)) {
|
||||
const comment = sib.data;
|
||||
const parts = comment.split(":");
|
||||
if (parts[0] === "frsh") {
|
||||
sib = maybeHideMarker(sib);
|
||||
}
|
||||
|
||||
if (parts[0] === "frsh" && parts[1] === "partial") {
|
||||
if (++partialCount === 1) {
|
||||
startNode = sib;
|
||||
partialName = parts[2];
|
||||
partialMode = +parts[3] as PartialMode;
|
||||
partialKey = parts[4];
|
||||
}
|
||||
} else if (comment === "/frsh:partial") {
|
||||
ctx.foundPartials++;
|
||||
|
||||
// Skip hydrating nested partials, only hydrate the outer one
|
||||
if (--partialCount > 0) {
|
||||
sib = sib.nextSibling;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Create a fake DOM node that spans the partial we discovered.
|
||||
// We need to include the partial markers itself for _walkInner
|
||||
// to register them.
|
||||
const container = createRootFragment(
|
||||
node,
|
||||
startNode as Comment,
|
||||
sib as Comment,
|
||||
);
|
||||
|
||||
const root = h(PartialComp, {
|
||||
key: partialKey !== "" ? partialKey : undefined,
|
||||
name: partialName,
|
||||
mode: partialMode,
|
||||
children: null,
|
||||
});
|
||||
domToVNode(
|
||||
allProps,
|
||||
[root],
|
||||
[Marker.Partial],
|
||||
container,
|
||||
sib as Comment,
|
||||
);
|
||||
|
||||
const instance = ACTIVE_PARTIALS.get(partialName);
|
||||
if (instance === undefined) {
|
||||
// deno-lint-ignore no-console
|
||||
console.warn(`Partial "${partialName}" not found. Skipping...`);
|
||||
// Partial doesn't exist on the current page
|
||||
} else {
|
||||
if (partialMode === PartialMode.Replace) {
|
||||
instance.props.children = root.props.children;
|
||||
} else if (partialMode === PartialMode.Append) {
|
||||
const active = ACTIVE_PARTIALS.get(partialName);
|
||||
if (active !== undefined) {
|
||||
copyOldChildren(instance.props, active.props.children);
|
||||
|
||||
(instance.props.children as ComponentChildren[]).push(
|
||||
root.props.children,
|
||||
);
|
||||
} else {
|
||||
instance.props.children = root.props.children;
|
||||
}
|
||||
} else if (partialMode === PartialMode.Prepend) {
|
||||
const active = ACTIVE_PARTIALS.get(partialName);
|
||||
if (active !== undefined) {
|
||||
copyOldChildren(instance.props, active.props.children);
|
||||
|
||||
(instance.props.children as ComponentChildren[]).unshift(
|
||||
root.props.children,
|
||||
);
|
||||
} else {
|
||||
instance.props.children = root.props.children;
|
||||
}
|
||||
}
|
||||
instance.setState({});
|
||||
}
|
||||
}
|
||||
} else if (partialCount === 0 && isElementNode(sib)) {
|
||||
// Do not recurse if we know that we are inisde a partial
|
||||
revivePartials(ctx, allProps, sib);
|
||||
}
|
||||
|
||||
sib = sib.nextSibling;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
// deno-lint-ignore-file ban-unknown-rule-code ban-unused-ignore
|
||||
// Polyfill for old safari versions
|
||||
if (typeof globalThis === "undefined") {
|
||||
// @ts-ignore polyfill
|
||||
// deno-lint-ignore no-window
|
||||
window.globalThis = window;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { options } from "preact";
|
||||
import { assetHashingHook, CLIENT_NAV_ATTR } from "../shared_internal.tsx";
|
||||
import { BUILD_ID } from "@fresh/build-id";
|
||||
|
||||
const oldVNodeHook = options.vnode;
|
||||
options.vnode = (vnode) => {
|
||||
assetHashingHook(vnode, BUILD_ID);
|
||||
|
||||
if (typeof vnode.type === "string") {
|
||||
if (CLIENT_NAV_ATTR in vnode.props) {
|
||||
const value = vnode.props[CLIENT_NAV_ATTR];
|
||||
if (typeof value === "boolean") {
|
||||
vnode.props[CLIENT_NAV_ATTR] = String(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
oldVNodeHook?.(vnode);
|
||||
};
|
||||
@@ -0,0 +1,577 @@
|
||||
import {
|
||||
Component,
|
||||
type ComponentChildren,
|
||||
type ComponentType,
|
||||
Fragment,
|
||||
h,
|
||||
render,
|
||||
type VNode,
|
||||
} from "preact";
|
||||
import { type CustomParser, parse } from "../../jsonify/parse.ts";
|
||||
import { computed, signal } from "@preact/signals";
|
||||
import { DATA_FRESH_KEY, PartialMode } from "../shared_internal.tsx";
|
||||
|
||||
const enum RootKind {
|
||||
Island,
|
||||
Partial,
|
||||
}
|
||||
|
||||
interface IslandReq {
|
||||
kind: RootKind.Island;
|
||||
name: string;
|
||||
propsIdx: number;
|
||||
key: string | null;
|
||||
start: Comment | Text;
|
||||
end: Comment | Text | null;
|
||||
}
|
||||
interface PartialReq {
|
||||
kind: RootKind.Partial;
|
||||
name: string;
|
||||
key: string | null;
|
||||
start: Comment | Text;
|
||||
end: Comment | Text | null;
|
||||
}
|
||||
|
||||
interface ReviveContext {
|
||||
roots: Array<IslandReq | PartialReq>;
|
||||
stack: Array<PartialReq | IslandReq>;
|
||||
slots: Map<number, { name: string; start: Comment; end: Comment | null }>;
|
||||
slotIdStack: number[];
|
||||
}
|
||||
|
||||
interface SlotRef {
|
||||
kind: typeof SLOT_SYMBOL;
|
||||
name: string;
|
||||
id: number;
|
||||
}
|
||||
const SLOT_SYMBOL = Symbol.for("_FRESH_SLOT");
|
||||
function isSlotRef(x: unknown): x is SlotRef {
|
||||
return x !== null && typeof x === "object" && "kind" in x &&
|
||||
x.kind === SLOT_SYMBOL;
|
||||
}
|
||||
|
||||
export type DeserializedProps = {
|
||||
props: Record<string, unknown>;
|
||||
slots: SlotRef[];
|
||||
}[];
|
||||
|
||||
export const ACTIVE_PARTIALS = new Map<string, PartialComp>();
|
||||
|
||||
export class PartialComp extends Component<
|
||||
{ children?: ComponentChildren; mode: PartialMode; name: string }
|
||||
> {
|
||||
override componentDidMount() {
|
||||
ACTIVE_PARTIALS.set(this.props.name, this);
|
||||
}
|
||||
|
||||
render() {
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
PartialComp.displayName = "Partial";
|
||||
|
||||
export function revive(
|
||||
props: Record<string, unknown>,
|
||||
component: ComponentType,
|
||||
container: HTMLElement,
|
||||
slots: ReviveContext["slots"],
|
||||
allProps: DeserializedProps,
|
||||
) {
|
||||
const _render = () => {
|
||||
for (const propName in props) {
|
||||
const value = props[propName];
|
||||
if (isSlotRef(value)) {
|
||||
const marker = slots.get(value.id);
|
||||
if (marker !== undefined) {
|
||||
const root = h(Fragment, null);
|
||||
const slotContainer = createRootFragment(
|
||||
container,
|
||||
marker.start,
|
||||
marker.end!,
|
||||
);
|
||||
domToVNode(
|
||||
allProps,
|
||||
[root],
|
||||
[Marker.Slot],
|
||||
slotContainer,
|
||||
marker.end!,
|
||||
);
|
||||
props[propName] = root;
|
||||
} else {
|
||||
const template = document.querySelector(
|
||||
`#frsh-${value.id}-${value.name}`,
|
||||
) as HTMLTemplateElement | null;
|
||||
if (template !== null) {
|
||||
const root = h(Fragment, null);
|
||||
domToVNode(allProps, [root], [Marker.Slot], template.content, null);
|
||||
props[propName] = root;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: explore hydrate?
|
||||
render(h(component, props), container as unknown as HTMLElement);
|
||||
};
|
||||
|
||||
// deno-lint-ignore no-window
|
||||
"scheduler" in window
|
||||
// `scheduler.postTask` is async but that can easily
|
||||
// fire in the background. We don't want waiting for
|
||||
// the hydration of an island block us.
|
||||
// @ts-ignore scheduler API is not in types yet
|
||||
? scheduler!.postTask(_render)
|
||||
: setTimeout(_render, 0);
|
||||
}
|
||||
|
||||
export const ISLAND_REGISTRY = new Map<string, ComponentType>();
|
||||
|
||||
export const CUSTOM_PARSER: CustomParser = {
|
||||
Signal: (value: unknown) => signal(value),
|
||||
Computed: (value: unknown) => computed(() => value),
|
||||
Slot: (value: { name: string; id: number }): SlotRef => {
|
||||
return { kind: SLOT_SYMBOL, name: value.name, id: value.id };
|
||||
},
|
||||
};
|
||||
|
||||
export function createReviveCtx(): ReviveContext {
|
||||
return {
|
||||
roots: [],
|
||||
stack: [],
|
||||
slots: new Map(),
|
||||
slotIdStack: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function boot(
|
||||
initialIslands: Record<string, ComponentType>,
|
||||
islandProps: string,
|
||||
) {
|
||||
const ctx = createReviveCtx();
|
||||
_walkInner(ctx, document.body);
|
||||
|
||||
const keys = Object.keys(initialIslands);
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const name = keys[i];
|
||||
ISLAND_REGISTRY.set(name, initialIslands[name]);
|
||||
}
|
||||
|
||||
const allProps = parse<DeserializedProps>(
|
||||
islandProps,
|
||||
CUSTOM_PARSER,
|
||||
);
|
||||
|
||||
for (let i = 0; i < ctx.roots.length; i++) {
|
||||
const root = ctx.roots[i];
|
||||
|
||||
const container = createRootFragment(
|
||||
// deno-lint-ignore no-explicit-any
|
||||
root.start.parentNode as any,
|
||||
root.start,
|
||||
root.end!,
|
||||
);
|
||||
|
||||
if (root.kind === RootKind.Island) {
|
||||
const props = allProps[root.propsIdx].props;
|
||||
const component = ISLAND_REGISTRY.get(root.name)!;
|
||||
|
||||
revive(props, component, container, ctx.slots, allProps);
|
||||
} else if (root.kind === RootKind.Partial) {
|
||||
const props: Record<string, unknown> = {
|
||||
name: root.name,
|
||||
children: null,
|
||||
};
|
||||
|
||||
const domRoot = h(Fragment, null);
|
||||
domToVNode(allProps, [domRoot], [Marker.Partial], container, root.end!);
|
||||
props.children = domRoot.props.children;
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
revive(props, PartialComp as any, container, ctx.slots, allProps);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const SHOW_MARKERS = false;
|
||||
|
||||
interface FreshMarker extends Text {
|
||||
_frshMarker: string;
|
||||
}
|
||||
|
||||
export function isFreshMarkerText(node: Node): node is FreshMarker {
|
||||
return node.nodeType === Node.TEXT_NODE &&
|
||||
// deno-lint-ignore no-explicit-any
|
||||
typeof (node as any)._frshMarker === "string";
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace comment markers with empty text nodes to hide them
|
||||
* in DevTools. This is done to avoid user confusion.
|
||||
*/
|
||||
export function maybeHideMarker(marker: Comment): Comment | Text {
|
||||
if (SHOW_MARKERS) return marker;
|
||||
const text = new Text("") as FreshMarker;
|
||||
text._frshMarker = marker.data;
|
||||
marker.parentNode!.insertBefore(text, marker);
|
||||
marker.remove();
|
||||
return text;
|
||||
}
|
||||
|
||||
function _walkInner(
|
||||
ctx: ReviveContext,
|
||||
node: Node | Comment,
|
||||
) {
|
||||
if (isElementNode(node)) {
|
||||
// No need to traverse into <script> or <style> tags.
|
||||
// No need to traverse deeper if we found a slotStart marker.
|
||||
// We'll parse slots later when the island is revived.
|
||||
if (
|
||||
node.nodeName === "SCRIPT" || node.nodeName === "STYLE" ||
|
||||
ctx.slotIdStack.length > 0
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (let i = 0; i < node.childNodes.length; i++) {
|
||||
const child = node.childNodes[i];
|
||||
_walkInner(ctx, child);
|
||||
}
|
||||
} else if (isCommentNode(node)) {
|
||||
const comment = node.data;
|
||||
if (comment.startsWith("frsh:")) {
|
||||
node = maybeHideMarker(node);
|
||||
const parts = comment.split(":");
|
||||
const kind = parts[1];
|
||||
if (kind === "island") {
|
||||
const name = parts[2];
|
||||
const propsIdx = parts[3];
|
||||
const key = parts[4];
|
||||
const found: IslandReq = {
|
||||
kind: RootKind.Island,
|
||||
name,
|
||||
propsIdx: Number(propsIdx),
|
||||
key: key === "" ? null : key,
|
||||
start: node as Comment,
|
||||
end: null,
|
||||
};
|
||||
if (ctx.stack.length === 0) {
|
||||
ctx.roots.push(found);
|
||||
}
|
||||
ctx.stack.push(found);
|
||||
} else if (kind === "slot") {
|
||||
const id = +parts[2];
|
||||
const slotName = parts[3];
|
||||
ctx.slotIdStack.push(id);
|
||||
ctx.slots.set(id, {
|
||||
name: slotName,
|
||||
start: node as Comment,
|
||||
end: null,
|
||||
});
|
||||
} else if (kind === "partial") {
|
||||
const name = parts[2];
|
||||
const key = parts[3];
|
||||
const found: PartialReq = {
|
||||
kind: RootKind.Partial,
|
||||
name,
|
||||
key: key === "" ? null : key,
|
||||
start: node as Comment,
|
||||
end: null,
|
||||
};
|
||||
if (ctx.stack.length === 0) {
|
||||
ctx.roots.push(found);
|
||||
}
|
||||
ctx.stack.push(found);
|
||||
}
|
||||
} else if (comment === "/frsh:island" || comment === "/frsh:partial") {
|
||||
node = maybeHideMarker(node);
|
||||
const item = ctx.stack.pop();
|
||||
if (item !== undefined) {
|
||||
item.end = node as Comment;
|
||||
}
|
||||
} else if (comment === "/frsh:slot") {
|
||||
node = maybeHideMarker(node);
|
||||
const item = ctx.slotIdStack.pop();
|
||||
if (item !== undefined) {
|
||||
ctx.slots.get(item)!.end = node as Comment;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const enum Marker {
|
||||
Island,
|
||||
Partial,
|
||||
Slot,
|
||||
}
|
||||
|
||||
interface ServerSlotProps {
|
||||
name: string;
|
||||
id: number;
|
||||
children?: ComponentChildren;
|
||||
}
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
function ServerSlot(props: ServerSlotProps): any {
|
||||
return props.children;
|
||||
}
|
||||
|
||||
export function domToVNode(
|
||||
allProps: DeserializedProps,
|
||||
// deno-lint-ignore no-explicit-any
|
||||
vnodeStack: VNode<any>[],
|
||||
markerStack: Marker[],
|
||||
node: Text | Comment | Node | DocumentFragment,
|
||||
end: Text | Comment | null,
|
||||
): void {
|
||||
let sib: Node | ChildNode | null = node;
|
||||
while (sib !== null) {
|
||||
if (sib === end) return;
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
if ((sib as any)._frshRootFrag || sib instanceof DocumentFragment) {
|
||||
const firstChild = sib.firstChild;
|
||||
if (firstChild !== null) {
|
||||
domToVNode(allProps, vnodeStack, markerStack, firstChild, end);
|
||||
}
|
||||
} else if (isElementNode(sib)) {
|
||||
const props: Record<string, unknown> = {};
|
||||
for (let i = 0; i < sib.attributes.length; i++) {
|
||||
const attr = sib.attributes[i];
|
||||
|
||||
if (attr.nodeName === DATA_FRESH_KEY) {
|
||||
props.key = attr.nodeValue;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Boolean attributes are always `true` when present.
|
||||
// See: https://developer.mozilla.org/en-US/docs/Glossary/Boolean/HTML
|
||||
props[attr.nodeName] =
|
||||
// deno-lint-ignore no-explicit-any
|
||||
typeof (sib as any)[attr.nodeName] === "boolean"
|
||||
? true
|
||||
: attr.nodeValue;
|
||||
}
|
||||
|
||||
const vnode = h(sib.localName, props);
|
||||
const marker = markerStack.at(-1);
|
||||
const appendVNode = marker === Marker.Slot || marker === Marker.Partial;
|
||||
if (appendVNode) {
|
||||
addVNodeChild(vnodeStack.at(-1)!, vnode);
|
||||
vnodeStack.push(vnode);
|
||||
}
|
||||
|
||||
const firstChild = sib.firstChild;
|
||||
if (firstChild !== null) {
|
||||
domToVNode(allProps, vnodeStack, markerStack, firstChild, end);
|
||||
}
|
||||
|
||||
if (appendVNode) {
|
||||
vnodeStack.pop();
|
||||
}
|
||||
} else if (isCommentNode(sib) || isFreshMarkerText(sib)) {
|
||||
const comment = isFreshMarkerText(sib) ? sib._frshMarker : sib.data;
|
||||
if (comment.startsWith("frsh:")) {
|
||||
const parts = comment.split(":");
|
||||
|
||||
const kind = parts[1];
|
||||
if (kind === "island") {
|
||||
sib = maybeHideMarker(sib);
|
||||
markerStack.push(Marker.Island);
|
||||
|
||||
const name = parts[2];
|
||||
const propsIdx = parts[3];
|
||||
const key = parts[4];
|
||||
const island = ISLAND_REGISTRY.get(name);
|
||||
if (island === undefined) {
|
||||
throw new Error(`Encountered unknown island: ${name}`);
|
||||
}
|
||||
|
||||
const props = allProps[+propsIdx].props;
|
||||
props.key = key === "" ? undefined : key;
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const islandVNode = h<any>(island, props);
|
||||
addVNodeChild(vnodeStack.at(-1)!, islandVNode);
|
||||
vnodeStack.push(islandVNode);
|
||||
} else if (kind === "slot") {
|
||||
sib = maybeHideMarker(sib);
|
||||
markerStack.push(Marker.Slot);
|
||||
|
||||
const id = +parts[2];
|
||||
const slotName = parts[3];
|
||||
const key = parts[4];
|
||||
|
||||
const vnode = h(ServerSlot, {
|
||||
key: key === "" ? undefined : key,
|
||||
id,
|
||||
name: slotName,
|
||||
children: [],
|
||||
});
|
||||
|
||||
const parentVNode = vnodeStack.at(-1)!;
|
||||
parentVNode.props[slotName] = vnode;
|
||||
vnodeStack.push(vnode);
|
||||
} else if (kind === "partial") {
|
||||
sib = maybeHideMarker(sib);
|
||||
markerStack.push(Marker.Partial);
|
||||
|
||||
const name = parts[2];
|
||||
const mode = +parts[3] as PartialMode;
|
||||
const key = parts[4];
|
||||
// deno-lint-ignore no-explicit-any
|
||||
let vnode: VNode<any> = h(PartialComp, {
|
||||
name,
|
||||
key: key === "" ? undefined : key,
|
||||
mode,
|
||||
});
|
||||
const parentVNode = vnodeStack.at(-1);
|
||||
if (parentVNode !== undefined) {
|
||||
addVNodeChild(parentVNode, vnode);
|
||||
}
|
||||
|
||||
if (mode === PartialMode.Append) {
|
||||
const active = ACTIVE_PARTIALS.get(name);
|
||||
if (active !== undefined) {
|
||||
copyOldChildren(vnode.props, active.props.children);
|
||||
const wrapper = h(Fragment, null);
|
||||
addVNodeChild(vnode, wrapper);
|
||||
vnode = wrapper;
|
||||
}
|
||||
} else if (mode === PartialMode.Prepend) {
|
||||
const active = ACTIVE_PARTIALS.get(name);
|
||||
if (active !== undefined) {
|
||||
copyOldChildren(vnode.props, active.props.children);
|
||||
const wrapper = h(Fragment, null);
|
||||
if (!vnode.props.children) {
|
||||
vnode.props.children = [];
|
||||
}
|
||||
// deno-lint-ignore no-explicit-any
|
||||
(vnode.props.children as Array<VNode<any> | string>).unshift(
|
||||
wrapper,
|
||||
);
|
||||
vnode = wrapper;
|
||||
}
|
||||
}
|
||||
|
||||
vnodeStack.push(vnode);
|
||||
} else if (kind === "key") {
|
||||
if (!SHOW_MARKERS) {
|
||||
const current = sib;
|
||||
sib = sib.nextSibling;
|
||||
current.remove();
|
||||
}
|
||||
const vnode = h(Fragment, { key: parts[2] });
|
||||
addVNodeChild(vnodeStack.at(-1)!, vnode);
|
||||
vnodeStack.push(vnode);
|
||||
continue;
|
||||
}
|
||||
} else if (
|
||||
comment === "/frsh:island" || comment === "/frsh:slot" ||
|
||||
comment === "/frsh:partial"
|
||||
) {
|
||||
vnodeStack.pop();
|
||||
markerStack.pop();
|
||||
sib = maybeHideMarker(sib);
|
||||
} else if (comment === "/frsh:key") {
|
||||
vnodeStack.pop();
|
||||
sib = maybeHideMarker(sib);
|
||||
}
|
||||
} else if (isTextNode(sib)) {
|
||||
const marker = markerStack.at(-1);
|
||||
if (marker === Marker.Slot || marker === Marker.Partial) {
|
||||
addVNodeChild(vnodeStack.at(-1)!, sib.data);
|
||||
}
|
||||
}
|
||||
|
||||
sib = sib.nextSibling;
|
||||
}
|
||||
}
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
function addVNodeChild(parent: VNode<any>, child: VNode<any> | string) {
|
||||
if (!parent.props.children) {
|
||||
parent.props.children = [];
|
||||
}
|
||||
// deno-lint-ignore no-explicit-any
|
||||
(parent.props.children as Array<VNode<any> | string>).push(child);
|
||||
}
|
||||
|
||||
export function copyOldChildren(
|
||||
props: Record<string, unknown>,
|
||||
oldChildren: ComponentChildren,
|
||||
) {
|
||||
props.children = oldChildren !== undefined && oldChildren !== null
|
||||
? Array.isArray(oldChildren) ? oldChildren : [oldChildren]
|
||||
: [];
|
||||
}
|
||||
|
||||
export function isCommentNode(node: Node): node is Comment {
|
||||
return node.nodeType === Node.COMMENT_NODE;
|
||||
}
|
||||
export function isTextNode(node: Node): node is Text {
|
||||
return node.nodeType === Node.TEXT_NODE;
|
||||
}
|
||||
export function isElementNode(node: Node): node is HTMLElement {
|
||||
return node.nodeType === Node.ELEMENT_NODE && !("_frshRootFrag" in node);
|
||||
}
|
||||
|
||||
export function createRootFragment(
|
||||
parent: Element,
|
||||
startMarker: Text | Comment,
|
||||
// We need an end marker for islands because multiple
|
||||
// islands can share the same parent node. Since
|
||||
// islands are root-level render calls any calls to
|
||||
// `.appendChild` would lead to a wrong result.
|
||||
endMarker: Text | Comment,
|
||||
): HTMLElement & { _frshRootFrag: boolean } {
|
||||
// @ts-ignore this is fine
|
||||
const rootFrag = {
|
||||
_frshRootFrag: true,
|
||||
nodeType: 1,
|
||||
parentNode: parent,
|
||||
nextSibling: null,
|
||||
get firstChild() {
|
||||
const child = startMarker.nextSibling;
|
||||
if (child === endMarker) return null;
|
||||
return child;
|
||||
},
|
||||
get childNodes() {
|
||||
const children: ChildNode[] = [];
|
||||
|
||||
let child = startMarker.nextSibling;
|
||||
while (child !== null && child !== endMarker) {
|
||||
children.push(child);
|
||||
child = child.nextSibling;
|
||||
}
|
||||
|
||||
return children;
|
||||
},
|
||||
insertBefore(node: Node, child: Node | null) {
|
||||
parent.insertBefore(node, child ?? endMarker);
|
||||
},
|
||||
appendChild(child: Node) {
|
||||
// We cannot blindly call `.append()` as that would add
|
||||
// the new child to the very end of the parent node. This
|
||||
// leads to ordering issues when the multiple islands
|
||||
// share the same parent node.
|
||||
parent.insertBefore(child, endMarker);
|
||||
},
|
||||
removeChild(child: Node) {
|
||||
parent.removeChild(child);
|
||||
},
|
||||
contains(node: Node | null): boolean {
|
||||
if (node === null) return false;
|
||||
|
||||
const children = rootFrag.childNodes;
|
||||
for (let i = 0; i < children.length; i++) {
|
||||
if (children[i].contains(node)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
},
|
||||
};
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
return rootFrag as any;
|
||||
}
|
||||
@@ -0,0 +1,553 @@
|
||||
import {
|
||||
type Component,
|
||||
type ComponentChildren,
|
||||
type ComponentType,
|
||||
Fragment,
|
||||
h,
|
||||
isValidElement,
|
||||
type Options as PreactOptions,
|
||||
options as preactOptions,
|
||||
type VNode,
|
||||
} from "preact";
|
||||
import type { ReadonlySignal, Signal } from "@preact/signals";
|
||||
import type { Stringifiers } from "../../jsonify/stringify.ts";
|
||||
import type { PageProps } from "../../render.ts";
|
||||
import { Partial, type PartialProps } from "../shared.ts";
|
||||
import { stringify } from "../../jsonify/stringify.ts";
|
||||
import type { Island } from "../../context.ts";
|
||||
import {
|
||||
assetHashingHook,
|
||||
CLIENT_NAV_ATTR,
|
||||
DATA_FRESH_KEY,
|
||||
PartialMode,
|
||||
setActiveUrl,
|
||||
} from "../shared_internal.tsx";
|
||||
import type { BuildCache } from "../../build_cache.ts";
|
||||
import { BUILD_ID } from "@fresh/build-id";
|
||||
import {
|
||||
DEV_ERROR_OVERLAY_URL,
|
||||
PARTIAL_SEARCH_PARAM,
|
||||
} from "../../constants.ts";
|
||||
import { escape as escapeHtml } from "@std/html";
|
||||
import { HttpError } from "../../error.ts";
|
||||
import { getCodeFrame } from "../../dev/middlewares/error_overlay/code_frame.tsx";
|
||||
import { escapeScript } from "../../utils.ts";
|
||||
|
||||
const enum OptionsType {
|
||||
ATTR = "attr",
|
||||
VNODE = "vnode",
|
||||
HOOK = "__h",
|
||||
DIFF = "__b",
|
||||
RENDER = "__r",
|
||||
DIFFED = "diffed",
|
||||
ERROR = "__e",
|
||||
}
|
||||
|
||||
interface InternalPreactOptions extends PreactOptions {
|
||||
[OptionsType.ATTR](name: string, value: unknown): string | void;
|
||||
[OptionsType.VNODE](vnode: InternalVNode): void;
|
||||
[OptionsType.HOOK](component: Component, index: number, type: number): void;
|
||||
[OptionsType.DIFF](vnode: InternalVNode): void;
|
||||
[OptionsType.RENDER](vnode: InternalVNode): void;
|
||||
[OptionsType.DIFFED](vnode: InternalVNode): void;
|
||||
[OptionsType.ERROR](
|
||||
error: unknown,
|
||||
vnode: InternalVNode,
|
||||
oldVNode: InternalVNode,
|
||||
): void;
|
||||
}
|
||||
|
||||
interface InternalVNode extends VNode {
|
||||
__c: Component | null;
|
||||
__: InternalVNode | null;
|
||||
}
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const options: InternalPreactOptions = preactOptions as any;
|
||||
|
||||
export class RenderState {
|
||||
nonce: string;
|
||||
partialDepth = 0;
|
||||
partialCount = 0;
|
||||
error: Error | null = null;
|
||||
// deno-lint-ignore no-explicit-any
|
||||
slots: Array<{ id: number; name: string; vnode: VNode<any> } | null> = [];
|
||||
// deno-lint-ignore no-explicit-any
|
||||
islandProps: any[] = [];
|
||||
islands = new Set<Island>();
|
||||
// deno-lint-ignore no-explicit-any
|
||||
encounteredPartials = new Set<any>();
|
||||
owners = new Map<VNode, VNode>();
|
||||
ownerStack: InternalVNode[] = [];
|
||||
|
||||
// TODO: merge into bitmask field
|
||||
renderedHtmlTag = false;
|
||||
renderedHtmlBody = false;
|
||||
renderedHtmlHead = false;
|
||||
hasRuntimeScript = false;
|
||||
|
||||
constructor(
|
||||
// deno-lint-ignore no-explicit-any
|
||||
public ctx: PageProps<any, any>,
|
||||
public buildCache: BuildCache,
|
||||
public partialId: string,
|
||||
) {
|
||||
this.nonce = crypto.randomUUID().replace(/-/g, "");
|
||||
}
|
||||
|
||||
clear() {
|
||||
this.islands.clear();
|
||||
this.encounteredPartials.clear();
|
||||
this.owners.clear();
|
||||
this.slots = [];
|
||||
this.islandProps = [];
|
||||
this.ownerStack = [];
|
||||
}
|
||||
}
|
||||
|
||||
let RENDER_STATE: RenderState | null = null;
|
||||
export function setRenderState(state: RenderState | null) {
|
||||
RENDER_STATE = state;
|
||||
}
|
||||
|
||||
const oldVNodeHook = options[OptionsType.VNODE];
|
||||
options[OptionsType.VNODE] = (vnode) => {
|
||||
if (RENDER_STATE !== null) {
|
||||
RENDER_STATE.owners.set(vnode, RENDER_STATE!.ownerStack.at(-1)!);
|
||||
if (vnode.type === "a") {
|
||||
setActiveUrl(vnode, RENDER_STATE.ctx.url.pathname);
|
||||
}
|
||||
}
|
||||
assetHashingHook(vnode, BUILD_ID);
|
||||
|
||||
if (typeof vnode.type === "function") {
|
||||
if (vnode.type === Partial) {
|
||||
const props = vnode.props as PartialProps;
|
||||
const key = normalizeKey(vnode.key);
|
||||
const mode = !props.mode || props.mode === "replace"
|
||||
? PartialMode.Replace
|
||||
: props.mode === "append"
|
||||
? PartialMode.Append
|
||||
: PartialMode.Prepend;
|
||||
props.children = wrapWithMarker(
|
||||
props.children,
|
||||
"partial",
|
||||
`${props.name}:${mode}:${key}`,
|
||||
);
|
||||
}
|
||||
} else if (typeof vnode.type === "string") {
|
||||
if (vnode.type === "body") {
|
||||
const scripts = h(FreshScripts, null);
|
||||
if (vnode.props.children == null) {
|
||||
vnode.props.children = scripts;
|
||||
} else if (Array.isArray(vnode.props.children)) {
|
||||
vnode.props.children.push(scripts);
|
||||
} else {
|
||||
vnode.props.children = [vnode.props.children, scripts];
|
||||
}
|
||||
}
|
||||
if (CLIENT_NAV_ATTR in vnode.props) {
|
||||
vnode.props[CLIENT_NAV_ATTR] = String(vnode.props[CLIENT_NAV_ATTR]);
|
||||
}
|
||||
}
|
||||
|
||||
oldVNodeHook?.(vnode);
|
||||
};
|
||||
|
||||
const oldAttrHook = options[OptionsType.ATTR];
|
||||
options[OptionsType.ATTR] = (name, value) => {
|
||||
if (name === CLIENT_NAV_ATTR) {
|
||||
return `${CLIENT_NAV_ATTR}="${String(Boolean(value))}"`;
|
||||
} else if (name === "key") {
|
||||
return `${DATA_FRESH_KEY}="${escapeHtml(String(value))}"`;
|
||||
}
|
||||
|
||||
return oldAttrHook?.(name, value);
|
||||
};
|
||||
|
||||
const PATCHED = new WeakSet<VNode>();
|
||||
|
||||
function normalizeKey(key: unknown): string {
|
||||
const value = key ?? "";
|
||||
const s = (typeof value !== "string") ? String(value) : value;
|
||||
return s.replaceAll(":", "_");
|
||||
}
|
||||
|
||||
const oldDiff = options[OptionsType.DIFF];
|
||||
options[OptionsType.DIFF] = (vnode) => {
|
||||
if (RENDER_STATE !== null) {
|
||||
patcher: if (
|
||||
typeof vnode.type === "function" && vnode.type !== Fragment
|
||||
) {
|
||||
if (vnode.type === Partial) {
|
||||
RENDER_STATE.partialDepth++;
|
||||
|
||||
const name = (vnode.props as PartialProps).name;
|
||||
if (typeof name === "string") {
|
||||
if (RENDER_STATE.encounteredPartials.has(name)) {
|
||||
throw new Error(
|
||||
`Rendered response contains duplicate partial name: "${name}"`,
|
||||
);
|
||||
}
|
||||
|
||||
RENDER_STATE.encounteredPartials.add(name);
|
||||
}
|
||||
|
||||
if (hasIslandOwner(RENDER_STATE, vnode)) {
|
||||
throw new Error(
|
||||
`<Partial> components cannot be used inside islands.`,
|
||||
);
|
||||
}
|
||||
} else if (
|
||||
!PATCHED.has(vnode) && !hasIslandOwner(RENDER_STATE, vnode)
|
||||
) {
|
||||
const island = RENDER_STATE.buildCache.islandRegistry.get(vnode.type);
|
||||
if (island === undefined) {
|
||||
// Not an island, but we might need to preserve keys
|
||||
if (vnode.key !== undefined) {
|
||||
const key = normalizeKey(vnode.key);
|
||||
const originalType = vnode.type;
|
||||
vnode.type = (props) => {
|
||||
const child = h(originalType, props);
|
||||
PATCHED.add(child);
|
||||
return wrapWithMarker(child, "key", key);
|
||||
};
|
||||
}
|
||||
|
||||
break patcher;
|
||||
}
|
||||
|
||||
const { islands, islandProps } = RENDER_STATE;
|
||||
islands.add(island);
|
||||
|
||||
const originalType = vnode.type;
|
||||
vnode.type = (props) => {
|
||||
for (const name in props) {
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const value = (props as any)[name];
|
||||
if (
|
||||
name === "children" || (isValidElement(value) && !isSignal(value))
|
||||
) {
|
||||
const slotId = RENDER_STATE!.slots.length;
|
||||
RENDER_STATE!.slots.push({ id: slotId, name, vnode: value });
|
||||
// deno-lint-ignore no-explicit-any
|
||||
(props as any)[name] = h(Slot, {
|
||||
name,
|
||||
id: slotId,
|
||||
}, value);
|
||||
}
|
||||
}
|
||||
const propsIdx = islandProps.push({ slots: [], props }) - 1;
|
||||
|
||||
const child = h(originalType, props);
|
||||
PATCHED.add(child);
|
||||
|
||||
const key = normalizeKey(vnode.key);
|
||||
return wrapWithMarker(
|
||||
child,
|
||||
"island",
|
||||
`${island!.name}:${propsIdx}:${key}`,
|
||||
);
|
||||
};
|
||||
}
|
||||
} else if (typeof vnode.type === "string") {
|
||||
switch (vnode.type) {
|
||||
case "html":
|
||||
RENDER_STATE!.renderedHtmlTag = true;
|
||||
break;
|
||||
case "head":
|
||||
RENDER_STATE!.renderedHtmlHead = true;
|
||||
break;
|
||||
case "body":
|
||||
RENDER_STATE!.renderedHtmlBody = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if (
|
||||
vnode.key !== undefined &&
|
||||
(RENDER_STATE!.partialDepth > 0 || hasIslandOwner(RENDER_STATE!, vnode))
|
||||
) {
|
||||
(vnode.props as Record<string, unknown>)[DATA_FRESH_KEY] = String(
|
||||
vnode.key,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
oldDiff?.(vnode);
|
||||
};
|
||||
|
||||
const oldRender = options[OptionsType.RENDER];
|
||||
options[OptionsType.RENDER] = (vnode) => {
|
||||
if (
|
||||
typeof vnode.type === "function" && vnode.type !== Fragment &&
|
||||
RENDER_STATE !== null
|
||||
) {
|
||||
RENDER_STATE.ownerStack.push(vnode);
|
||||
}
|
||||
oldRender?.(vnode);
|
||||
};
|
||||
|
||||
const oldDiffed = options[OptionsType.DIFFED];
|
||||
options[OptionsType.DIFFED] = (vnode) => {
|
||||
if (
|
||||
typeof vnode.type === "function" && vnode.type !== Fragment &&
|
||||
RENDER_STATE !== null
|
||||
) {
|
||||
RENDER_STATE.ownerStack.pop();
|
||||
|
||||
if (vnode.type === Partial) {
|
||||
RENDER_STATE.partialDepth--;
|
||||
}
|
||||
}
|
||||
oldDiffed?.(vnode);
|
||||
};
|
||||
|
||||
interface SlotProps {
|
||||
name: string;
|
||||
id: number;
|
||||
children?: ComponentChildren;
|
||||
}
|
||||
function Slot(props: SlotProps) {
|
||||
if (RENDER_STATE !== null) {
|
||||
RENDER_STATE.slots[props.id] = null;
|
||||
}
|
||||
return wrapWithMarker(props.children, "slot", `${props.id}:${props.name}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the current component was rendered in an island
|
||||
*/
|
||||
function hasIslandOwner(current: RenderState, vnode: VNode): boolean {
|
||||
let tmpVNode = vnode;
|
||||
let owner;
|
||||
while ((owner = current.owners.get(tmpVNode)) !== undefined) {
|
||||
if (current.buildCache.islandRegistry.has(owner.type as ComponentType)) {
|
||||
return true;
|
||||
}
|
||||
tmpVNode = owner;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function wrapWithMarker(
|
||||
vnode: ComponentChildren,
|
||||
kind: string,
|
||||
markerText: string,
|
||||
) {
|
||||
return h(
|
||||
Fragment,
|
||||
null,
|
||||
h(Fragment, {
|
||||
// @ts-ignore unstable property is not typed
|
||||
UNSTABLE_comment: `frsh:${kind}:${markerText}`,
|
||||
}),
|
||||
vnode,
|
||||
h(Fragment, {
|
||||
// @ts-ignore unstable property is not typed
|
||||
UNSTABLE_comment: "/frsh:" + kind,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
function isSignal(x: any): x is Signal {
|
||||
return (
|
||||
x !== null &&
|
||||
typeof x === "object" &&
|
||||
typeof x.peek === "function" &&
|
||||
"value" in x
|
||||
);
|
||||
}
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
function isComputedSignal(x: any): x is ReadonlySignal {
|
||||
return isSignal(x) &&
|
||||
(("x" in x && typeof x.x === "function") ||
|
||||
"_fn" in x && typeof x._fn === "function");
|
||||
}
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
function isVNode(x: any): x is VNode {
|
||||
return x !== null && typeof x === "object" && "type" in x && "ref" in x &&
|
||||
"__k" in x &&
|
||||
isValidElement(x);
|
||||
}
|
||||
|
||||
const stringifiers: Stringifiers = {
|
||||
Computed: (value: unknown) => {
|
||||
return isComputedSignal(value) ? { value: value.peek() } : undefined;
|
||||
},
|
||||
Signal: (value: unknown) => {
|
||||
return isSignal(value) ? { value: value.peek() } : undefined;
|
||||
},
|
||||
Slot: (value: unknown) => {
|
||||
if (isVNode(value) && value.type === Slot) {
|
||||
const props = value.props as SlotProps;
|
||||
return {
|
||||
value: {
|
||||
name: props.name,
|
||||
id: props.id,
|
||||
},
|
||||
};
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
export function FreshScripts() {
|
||||
if (RENDER_STATE === null) return null;
|
||||
if (RENDER_STATE.hasRuntimeScript) {
|
||||
return null;
|
||||
}
|
||||
RENDER_STATE.hasRuntimeScript = true;
|
||||
const { slots } = RENDER_STATE;
|
||||
|
||||
// Remaining slots must be rendered before creating the Fresh runtime
|
||||
// script, so that we have the full list of islands rendered
|
||||
return (
|
||||
<>
|
||||
{slots.map((slot) => {
|
||||
if (slot === null) return null;
|
||||
return (
|
||||
<template
|
||||
key={slot.id}
|
||||
id={`frsh-${slot.id}-${slot.name}`}
|
||||
>
|
||||
{slot.vnode}
|
||||
</template>
|
||||
);
|
||||
})}
|
||||
<FreshRuntimeScript />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export interface PartialStateJson {
|
||||
islands: {
|
||||
name: string;
|
||||
chunk: string;
|
||||
exportName: string;
|
||||
}[];
|
||||
props: string;
|
||||
}
|
||||
|
||||
function FreshRuntimeScript() {
|
||||
const { islands, nonce, ctx, islandProps, partialId, buildCache } =
|
||||
RENDER_STATE!;
|
||||
const basePath = ctx.config.basePath;
|
||||
|
||||
const islandArr = Array.from(islands);
|
||||
|
||||
if (ctx.url.searchParams.has(PARTIAL_SEARCH_PARAM)) {
|
||||
const islands = islandArr.map((island) => {
|
||||
return {
|
||||
exportName: island.exportName,
|
||||
chunk: island.file,
|
||||
name: island.name,
|
||||
};
|
||||
});
|
||||
|
||||
const serializedProps = stringify(islandProps, stringifiers);
|
||||
const json: PartialStateJson = {
|
||||
islands,
|
||||
props: serializedProps,
|
||||
};
|
||||
|
||||
return (
|
||||
<script
|
||||
id={`__FRSH_STATE_${partialId}`}
|
||||
type="application/json"
|
||||
// deno-lint-ignore react-no-danger
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: escapeScript(JSON.stringify(json), { json: true }),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
} else {
|
||||
const islandImports = islandArr.map((island) => {
|
||||
const named = island.exportName === "default"
|
||||
? island.name
|
||||
: island.exportName === island.name
|
||||
? `{ ${island.exportName} }`
|
||||
: `{ ${island.exportName} as ${island.name} }`;
|
||||
|
||||
const islandSpec = island.file.startsWith(".")
|
||||
? island.file.slice(1)
|
||||
: island.file;
|
||||
return `import ${named} from "${basePath}${islandSpec}";`;
|
||||
}).join("");
|
||||
|
||||
const islandObj = "{" + islandArr.map((island) => island.name)
|
||||
.join(",") +
|
||||
"}";
|
||||
|
||||
const serializedProps = escapeScript(
|
||||
JSON.stringify(stringify(islandProps, stringifiers)),
|
||||
{ json: true },
|
||||
);
|
||||
|
||||
// const runtimeUrl = `${basePath}/_fresh/js/${BUILD_ID}/fresh-runtime.js`;
|
||||
const runtimeUrl = buildCache.clientEntry.startsWith(".")
|
||||
? buildCache.clientEntry.slice(1)
|
||||
: buildCache.clientEntry;
|
||||
const scriptContent =
|
||||
`import { boot } from "${basePath}${runtimeUrl}";${islandImports}boot(${islandObj},${serializedProps});`;
|
||||
|
||||
return (
|
||||
<>
|
||||
<script
|
||||
type="module"
|
||||
nonce={nonce}
|
||||
// deno-lint-ignore react-no-danger
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: scriptContent,
|
||||
}}
|
||||
/>
|
||||
{buildCache.features.errorOverlay ? <ShowErrorOverlay /> : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function ShowErrorOverlay() {
|
||||
if (RENDER_STATE === null) return null;
|
||||
|
||||
const { ctx } = RENDER_STATE;
|
||||
const error = ctx.error;
|
||||
|
||||
if (error === null || error === undefined) return null;
|
||||
|
||||
// Ignore HTTP errors <500
|
||||
if (error instanceof HttpError && error.status < 500) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const basePath = ctx.config.basePath;
|
||||
|
||||
const searchParams = new URLSearchParams();
|
||||
|
||||
if (typeof error === "object") {
|
||||
if ("message" in error) {
|
||||
searchParams.append("message", String(error.message));
|
||||
}
|
||||
|
||||
if ("stack" in error && typeof error.stack === "string") {
|
||||
searchParams.append("stack", error.stack);
|
||||
const codeFrame = getCodeFrame(error.stack, ctx.config.root);
|
||||
if (codeFrame !== undefined) {
|
||||
searchParams.append("code-frame", codeFrame);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
searchParams.append("message", String(error));
|
||||
}
|
||||
|
||||
return (
|
||||
<iframe
|
||||
id="fresh-error-overlay"
|
||||
src={`${basePath}${DEV_ERROR_OVERLAY_URL}?${searchParams.toString()}`}
|
||||
style="unset: all; position: fixed; top: 0; left: 0; z-index: 99999; width: 100%; height: 100%; border: none;"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { ComponentChildren, VNode } from "preact";
|
||||
import { BUILD_ID } from "@fresh/build-id";
|
||||
import { assetInternal, assetSrcSetInternal } from "./shared_internal.tsx";
|
||||
|
||||
/**
|
||||
* Returns true when the current runtime is the browser and false otherwise. This is used for guard runtime-dependent code.
|
||||
* Shorthand for the following:
|
||||
* `typeof document !== "undefined"`
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* if (IS_BROWSER) {
|
||||
* alert('This is running in the browser!');
|
||||
* } else {
|
||||
* console.log('This code is running on the server, no access to window or alert');
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Without this guard, alert pauses the server until return is pressed in the console.
|
||||
*/
|
||||
export const IS_BROWSER = typeof document !== "undefined";
|
||||
|
||||
/**
|
||||
* Create a "locked" asset path. This differs from a plain path in that it is
|
||||
* specific to the current version of the application, and as such can be safely
|
||||
* served with a very long cache lifetime (1 year).
|
||||
*/
|
||||
export function asset(path: string): string {
|
||||
return assetInternal(path, BUILD_ID);
|
||||
}
|
||||
|
||||
/** Apply the `asset` function to urls in a `srcset` attribute. */
|
||||
export function assetSrcSet(srcset: string): string {
|
||||
return assetSrcSetInternal(srcset, BUILD_ID);
|
||||
}
|
||||
|
||||
export interface PartialProps {
|
||||
children?: ComponentChildren;
|
||||
/**
|
||||
* The name of the partial. This value must be unique across partials.
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* Define how the new HTML should be applied.
|
||||
* @default {"replace"}
|
||||
*/
|
||||
mode?: "replace" | "prepend" | "append";
|
||||
}
|
||||
|
||||
export function Partial(props: PartialProps): VNode {
|
||||
// deno-lint-ignore no-explicit-any
|
||||
return props.children as any;
|
||||
}
|
||||
Partial.displayName = "Partial";
|
||||
@@ -0,0 +1,123 @@
|
||||
import type { VNode } from "preact";
|
||||
|
||||
export const DATA_CURRENT = "data-current";
|
||||
export const DATA_ANCESTOR = "data-ancestor";
|
||||
export const DATA_FRESH_KEY = "data-frsh-key";
|
||||
export const CLIENT_NAV_ATTR = "f-client-nav";
|
||||
export const ASSET_CACHE_BUST_KEY = "__frsh_c";
|
||||
|
||||
export const enum UrlMatchKind {
|
||||
None,
|
||||
Ancestor,
|
||||
Current,
|
||||
}
|
||||
|
||||
export function matchesUrl(current: string, needle: string): UrlMatchKind {
|
||||
let href = new URL(needle, "http://localhost").pathname;
|
||||
if (href !== "/" && href.endsWith("/")) {
|
||||
href = href.slice(0, -1);
|
||||
}
|
||||
|
||||
if (current !== "/" && current.endsWith("/")) {
|
||||
current = current.slice(0, -1);
|
||||
}
|
||||
|
||||
if (current === href) {
|
||||
return UrlMatchKind.Current;
|
||||
} else if (current.startsWith(href + "/") || href === "/") {
|
||||
return UrlMatchKind.Ancestor;
|
||||
}
|
||||
|
||||
return UrlMatchKind.None;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark active or ancestor link
|
||||
* Note: This function is used both on the server and the client
|
||||
*/
|
||||
export function setActiveUrl(vnode: VNode, pathname: string): void {
|
||||
const props = vnode.props as Record<string, unknown>;
|
||||
const hrefProp = props.href;
|
||||
if (typeof hrefProp === "string" && hrefProp.startsWith("/")) {
|
||||
const match = matchesUrl(pathname, hrefProp);
|
||||
if (match === UrlMatchKind.Current) {
|
||||
props[DATA_CURRENT] = "true";
|
||||
props["aria-current"] = "page";
|
||||
} else if (match === UrlMatchKind.Ancestor) {
|
||||
props[DATA_ANCESTOR] = "true";
|
||||
props["aria-current"] = "true";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const enum PartialMode {
|
||||
Replace,
|
||||
Append,
|
||||
Prepend,
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a "locked" asset path. This differs from a plain path in that it is
|
||||
* specific to the current version of the application, and as such can be safely
|
||||
* served with a very long cache lifetime (1 year).
|
||||
*/
|
||||
export function assetInternal(path: string, buildId: string): string {
|
||||
if (!path.startsWith("/") || path.startsWith("//")) return path;
|
||||
try {
|
||||
const url = new URL(path, "https://freshassetcache.local");
|
||||
if (
|
||||
url.protocol !== "https:" || url.host !== "freshassetcache.local" ||
|
||||
url.searchParams.has(ASSET_CACHE_BUST_KEY)
|
||||
) {
|
||||
return path;
|
||||
}
|
||||
url.searchParams.set(ASSET_CACHE_BUST_KEY, buildId);
|
||||
return url.pathname + url.search + url.hash;
|
||||
} catch (err) {
|
||||
// deno-lint-ignore no-console
|
||||
console.warn(
|
||||
`Failed to create asset() URL, falling back to regular path ('${path}'):`,
|
||||
err,
|
||||
);
|
||||
return path;
|
||||
}
|
||||
}
|
||||
|
||||
/** Apply the `asset` function to urls in a `srcset` attribute. */
|
||||
export function assetSrcSetInternal(srcset: string, buildId: string): string {
|
||||
if (srcset.includes("(")) return srcset; // Bail if the srcset contains complicated syntax.
|
||||
const parts = srcset.split(",");
|
||||
const constructed = [];
|
||||
for (const part of parts) {
|
||||
const trimmed = part.trimStart();
|
||||
const leadingWhitespace = part.length - trimmed.length;
|
||||
if (trimmed === "") return srcset; // Bail if the srcset is malformed.
|
||||
let urlEnd = trimmed.indexOf(" ");
|
||||
if (urlEnd === -1) urlEnd = trimmed.length;
|
||||
const leading = part.substring(0, leadingWhitespace);
|
||||
const url = trimmed.substring(0, urlEnd);
|
||||
const trailing = trimmed.substring(urlEnd);
|
||||
constructed.push(leading + assetInternal(url, buildId) + trailing);
|
||||
}
|
||||
return constructed.join(",");
|
||||
}
|
||||
|
||||
export function assetHashingHook(
|
||||
vnode: VNode<{
|
||||
src?: string;
|
||||
srcset?: string;
|
||||
["data-fresh-disable-lock"]?: boolean;
|
||||
}>,
|
||||
buildId: string,
|
||||
) {
|
||||
if (vnode.type === "img" || vnode.type === "source") {
|
||||
const { props } = vnode;
|
||||
if (props["data-fresh-disable-lock"]) return;
|
||||
if (typeof props.src === "string") {
|
||||
props.src = assetInternal(props.src, buildId);
|
||||
}
|
||||
if (typeof props.srcset === "string") {
|
||||
props.srcset = assetSrcSetInternal(props.srcset, buildId);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
import type { AnyComponent } from "preact";
|
||||
import type { MaybeLazyMiddleware, Middleware } from "./middlewares/mod.ts";
|
||||
import { type Method, patternToSegments } from "./router.ts";
|
||||
import type { LayoutConfig, Route } from "./types.ts";
|
||||
import { type Context, getInternals } from "./context.ts";
|
||||
import { recordSpanError, tracer } from "./otel.ts";
|
||||
import { isHandlerByMethod } from "./handlers.ts";
|
||||
import {
|
||||
type AsyncAnyComponent,
|
||||
type PageProps,
|
||||
renderRouteComponent,
|
||||
} from "./render.ts";
|
||||
import { HttpError } from "./error.ts";
|
||||
|
||||
export type RouteComponent<State> =
|
||||
| AsyncAnyComponent<PageProps<unknown, State>>
|
||||
| AnyComponent<PageProps<unknown, State>>;
|
||||
|
||||
export interface Segment<State> {
|
||||
pattern: string;
|
||||
middlewares: MaybeLazyMiddleware<State>[];
|
||||
layout: {
|
||||
component: RouteComponent<State>;
|
||||
config: LayoutConfig | null;
|
||||
} | null;
|
||||
errorRoute: Route<State> | null;
|
||||
notFound: Middleware<State> | null;
|
||||
app: RouteComponent<State> | null;
|
||||
children: Map<string, Segment<State>>;
|
||||
parent: Segment<State> | null;
|
||||
}
|
||||
|
||||
export function newSegment<State>(
|
||||
pattern: string,
|
||||
parent: Segment<State> | null,
|
||||
): Segment<State> {
|
||||
return {
|
||||
pattern,
|
||||
middlewares: [],
|
||||
layout: null,
|
||||
app: null,
|
||||
errorRoute: null,
|
||||
notFound: null,
|
||||
parent,
|
||||
children: new Map(),
|
||||
};
|
||||
}
|
||||
|
||||
export function getOrCreateSegment<State>(
|
||||
root: Segment<State>,
|
||||
path: string,
|
||||
includeLast: boolean,
|
||||
): Segment<State> {
|
||||
let current = root;
|
||||
|
||||
const segments = patternToSegments(path, root.pattern, includeLast);
|
||||
for (let i = 0; i < segments.length; i++) {
|
||||
const seg = segments[i];
|
||||
if (seg === root.pattern) {
|
||||
current = root;
|
||||
} else {
|
||||
let child = current.children.get(seg);
|
||||
if (child === undefined) {
|
||||
child = newSegment(seg, current);
|
||||
current.children.set(seg, child);
|
||||
}
|
||||
|
||||
current = child;
|
||||
}
|
||||
}
|
||||
|
||||
return current;
|
||||
}
|
||||
|
||||
export function segmentToMiddlewares<State>(
|
||||
segment: Segment<State>,
|
||||
): MaybeLazyMiddleware<State>[] {
|
||||
const result: MaybeLazyMiddleware<State>[] = [];
|
||||
|
||||
const stack: Segment<State>[] = [];
|
||||
let current: Segment<State> | null = segment;
|
||||
while (current !== null) {
|
||||
stack.push(current);
|
||||
current = current.parent;
|
||||
}
|
||||
|
||||
const root = stack.at(-1)!;
|
||||
|
||||
for (let i = stack.length - 1; i >= 0; i--) {
|
||||
const seg = stack[i];
|
||||
const { layout, app, errorRoute } = seg;
|
||||
|
||||
result.push(async function segmentMiddleware(ctx) {
|
||||
const internals = getInternals(ctx);
|
||||
|
||||
const prevApp = internals.app;
|
||||
const prevLayouts = internals.layouts;
|
||||
|
||||
if (app !== null) {
|
||||
internals.app = app;
|
||||
}
|
||||
|
||||
if (layout !== null) {
|
||||
if (layout.config?.skipAppWrapper) {
|
||||
internals.app = null;
|
||||
}
|
||||
|
||||
const def = { props: null, component: layout.component };
|
||||
if (layout.config?.skipInheritedLayouts) {
|
||||
internals.layouts = [def];
|
||||
} else {
|
||||
internals.layouts = [...internals.layouts, def];
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
return await ctx.next();
|
||||
} catch (err) {
|
||||
const status = err instanceof HttpError ? err.status : 500;
|
||||
if (root.notFound !== null && status === 404) {
|
||||
return await root.notFound(ctx);
|
||||
}
|
||||
|
||||
if (errorRoute !== null) {
|
||||
return await renderRoute(ctx, errorRoute, status);
|
||||
}
|
||||
|
||||
throw err;
|
||||
} finally {
|
||||
internals.app = prevApp;
|
||||
internals.layouts = prevLayouts;
|
||||
}
|
||||
});
|
||||
|
||||
if (seg.middlewares.length > 0) {
|
||||
result.push(...seg.middlewares);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function renderRoute<State>(
|
||||
ctx: Context<State>,
|
||||
route: Route<State>,
|
||||
status = 200,
|
||||
): Promise<Response> {
|
||||
const internals = getInternals(ctx);
|
||||
if (route.config?.skipAppWrapper) {
|
||||
internals.app = null;
|
||||
}
|
||||
if (route.config?.skipInheritedLayouts) {
|
||||
internals.layouts = [];
|
||||
}
|
||||
|
||||
const method = ctx.req.method as Method;
|
||||
|
||||
const handlers = route.handler;
|
||||
if (handlers === undefined) {
|
||||
throw new Error(`Unexpected missing handlers`);
|
||||
}
|
||||
|
||||
const headers = new Headers();
|
||||
headers.set("Content-Type", "text/html;charset=utf-8");
|
||||
|
||||
const res = await tracer.startActiveSpan("handler", {
|
||||
attributes: { "fresh.span_type": "fs_routes/handler" },
|
||||
}, async (span) => {
|
||||
try {
|
||||
const fn = isHandlerByMethod(handlers)
|
||||
? handlers[method] ?? null
|
||||
: handlers;
|
||||
|
||||
if (fn === null) return await ctx.next();
|
||||
|
||||
return await fn(ctx);
|
||||
} catch (err) {
|
||||
recordSpanError(span, err);
|
||||
throw err;
|
||||
} finally {
|
||||
span.end();
|
||||
}
|
||||
});
|
||||
|
||||
if (res instanceof Response) {
|
||||
return res;
|
||||
}
|
||||
|
||||
if (typeof res.status === "number") {
|
||||
status = res.status;
|
||||
}
|
||||
if (res.headers) {
|
||||
for (const [name, value] of Object.entries(res.headers)) {
|
||||
headers.set(name, value);
|
||||
}
|
||||
}
|
||||
|
||||
let vnode = null;
|
||||
if (route.component !== undefined) {
|
||||
const result = await renderRouteComponent(ctx, {
|
||||
component: route.component,
|
||||
// deno-lint-ignore no-explicit-any
|
||||
props: res.data as any,
|
||||
}, () => null);
|
||||
|
||||
if (result instanceof Response) {
|
||||
return result;
|
||||
}
|
||||
|
||||
vnode = result;
|
||||
}
|
||||
|
||||
return ctx.render(vnode, { headers, status });
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { expect } from "@std/expect";
|
||||
import { getOrCreateSegment, newSegment } from "./segments.ts";
|
||||
|
||||
Deno.test("findOrCreateSegment - root", () => {
|
||||
const root = newSegment("", null);
|
||||
const found = getOrCreateSegment(root, "", false);
|
||||
expect(found).toEqual(root);
|
||||
});
|
||||
|
||||
Deno.test("findOrCreateSegment - /foo/bar", () => {
|
||||
const root = newSegment("", null);
|
||||
const found = getOrCreateSegment(root, "/foo/bar", false);
|
||||
expect(found).toEqual(root.children.get("foo"));
|
||||
});
|
||||
|
||||
Deno.test("findOrCreateSegment - /:foo/bar/:baz", () => {
|
||||
const root = newSegment("", null);
|
||||
const found = getOrCreateSegment(root, "/:foo/bar/:baz", false);
|
||||
expect(found).toEqual(
|
||||
root.children.get(":foo")?.children.get("bar"),
|
||||
);
|
||||
});
|
||||
|
||||
Deno.test("findOrCreateSegment - /foo/bar/", () => {
|
||||
const root = newSegment("", null);
|
||||
const found = getOrCreateSegment(root, "/foo/bar/", false);
|
||||
expect(found).toEqual(root.children.get("foo")?.children.get("bar"));
|
||||
});
|
||||
|
||||
Deno.test("findOrCreateSegment - /foo/bar with last", () => {
|
||||
const root = newSegment("", null);
|
||||
const found = getOrCreateSegment(root, "/foo/bar", true);
|
||||
expect(found).toEqual(root.children.get("foo")?.children.get("bar"));
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
const LINK = "https://fresh.deno.dev/docs/concepts/ahead-of-time-builds";
|
||||
|
||||
export default function TailwindErrorPage() {
|
||||
return (
|
||||
<div class="frsh-error-page">
|
||||
<div style="max-width: 48rem; padding: 2rem 1rem; margin: 0 auto; font-family: sans-serif">
|
||||
<h1>Finish setting up Fresh</h1>
|
||||
<p style="line-height: 1.6;margin-bottom: 1rem;">
|
||||
The <b>tailwindcss</b>{" "}
|
||||
plugin requires ahead of time builds to be set up for production
|
||||
usage. To finish the setup, follow these steps:
|
||||
</p>
|
||||
<ol style="line-height: 1.6; margin-bottom: 1.5rem">
|
||||
<li>
|
||||
Go to your project in Deno Deploy and click the{" "}
|
||||
<code>Settings</code> tab.
|
||||
</li>
|
||||
<li>
|
||||
In the Git Integration section, enter <code>deno task build</code>
|
||||
{" "}
|
||||
in the <code>Build Command</code> input.
|
||||
</li>
|
||||
<li>
|
||||
Save the changes.
|
||||
</li>
|
||||
</ol>
|
||||
<p>
|
||||
See the detailed guide here: <a href={LINK}>{LINK}</a>.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
import { Context, type ServerIslandRegistry } from "./context.ts";
|
||||
import type { FsAdapter } from "./fs.ts";
|
||||
import type { BuildCache, StaticFile } from "./build_cache.ts";
|
||||
import type { ResolvedFreshConfig } from "./config.ts";
|
||||
import type { WalkEntry } from "@std/fs/walk";
|
||||
import { DEFAULT_CONN_INFO } from "./app.ts";
|
||||
import type { Command } from "./commands.ts";
|
||||
import { fsItemsToCommands, type FsRouteFile } from "./fs_routes.ts";
|
||||
import * as path from "@std/path";
|
||||
|
||||
const STUB = {} as unknown as Deno.ServeHandlerInfo;
|
||||
|
||||
export class FakeServer {
|
||||
constructor(
|
||||
public handler: (
|
||||
req: Request,
|
||||
info: Deno.ServeHandlerInfo,
|
||||
) => Response | Promise<Response>,
|
||||
) {}
|
||||
|
||||
async get(path: string, init?: RequestInit): Promise<Response> {
|
||||
const url = this.toUrl(path);
|
||||
const req = new Request(url, init);
|
||||
return await this.handler(req, STUB);
|
||||
}
|
||||
async post(path: string, body?: BodyInit): Promise<Response> {
|
||||
const url = this.toUrl(path);
|
||||
const req = new Request(url, { method: "post", body });
|
||||
return await this.handler(req, STUB);
|
||||
}
|
||||
async patch(path: string, body?: BodyInit): Promise<Response> {
|
||||
const url = this.toUrl(path);
|
||||
const req = new Request(url, { method: "patch", body });
|
||||
return await this.handler(req, STUB);
|
||||
}
|
||||
async put(path: string, body?: BodyInit): Promise<Response> {
|
||||
const url = this.toUrl(path);
|
||||
const req = new Request(url, { method: "put", body });
|
||||
return await this.handler(req, STUB);
|
||||
}
|
||||
async delete(path: string): Promise<Response> {
|
||||
const url = this.toUrl(path);
|
||||
const req = new Request(url, { method: "delete" });
|
||||
return await this.handler(req, STUB);
|
||||
}
|
||||
async head(path: string): Promise<Response> {
|
||||
const url = this.toUrl(path);
|
||||
const req = new Request(url, { method: "head" });
|
||||
return await this.handler(req, STUB);
|
||||
}
|
||||
async options(path: string): Promise<Response> {
|
||||
const url = this.toUrl(path);
|
||||
const req = new Request(url, { method: "options" });
|
||||
return await this.handler(req, STUB);
|
||||
}
|
||||
|
||||
async request(req: Request): Promise<Response> {
|
||||
return await this.handler(req, STUB);
|
||||
}
|
||||
|
||||
private toUrl(path: string) {
|
||||
return new URL(path, "http://localhost/");
|
||||
}
|
||||
}
|
||||
|
||||
const DEFAULT_CONFIG: ResolvedFreshConfig = {
|
||||
root: "",
|
||||
mode: "production",
|
||||
basePath: "",
|
||||
};
|
||||
|
||||
export function serveMiddleware<T>(
|
||||
middleware: (ctx: Context<T>) => Response | Promise<Response>,
|
||||
options: {
|
||||
config?: ResolvedFreshConfig;
|
||||
buildCache?: BuildCache<T>;
|
||||
next?: () => Promise<Response>;
|
||||
route?: string | null;
|
||||
} = {},
|
||||
): FakeServer {
|
||||
return new FakeServer(async (req) => {
|
||||
const next = options.next ??
|
||||
(() => new Response("not found", { status: 404 }));
|
||||
const config = options.config ?? DEFAULT_CONFIG;
|
||||
const buildCache = options.buildCache ??
|
||||
new MockBuildCache<T>([], options.config?.mode ?? "production");
|
||||
|
||||
const ctx = new Context<T>(
|
||||
req,
|
||||
new URL(req.url),
|
||||
DEFAULT_CONN_INFO,
|
||||
options.route ?? null,
|
||||
{},
|
||||
config,
|
||||
() => Promise.resolve(next()),
|
||||
buildCache,
|
||||
);
|
||||
return await middleware(ctx);
|
||||
});
|
||||
}
|
||||
|
||||
export function createFakeFs(files: Record<string, unknown>): FsAdapter {
|
||||
return {
|
||||
cwd: () => ".",
|
||||
async *walk(_root) {
|
||||
for (const file of Object.keys(files)) {
|
||||
const entry: WalkEntry = {
|
||||
isDirectory: false,
|
||||
isFile: true,
|
||||
isSymlink: false,
|
||||
name: file,
|
||||
path: file,
|
||||
};
|
||||
yield entry;
|
||||
}
|
||||
},
|
||||
// deno-lint-ignore require-await
|
||||
async isDirectory(dir) {
|
||||
return Object.keys(files).some((file) => file.startsWith(dir + "/"));
|
||||
},
|
||||
async mkdirp(_dir: string) {
|
||||
},
|
||||
readFile: Deno.readFile,
|
||||
// deno-lint-ignore require-await
|
||||
async readTextFile(path) {
|
||||
return String(files[String(path)]);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export const delay = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
export async function withTmpDir(
|
||||
options?: Deno.MakeTempOptions,
|
||||
): Promise<{ dir: string } & AsyncDisposable> {
|
||||
const dir = await Deno.makeTempDir(options);
|
||||
return {
|
||||
dir,
|
||||
async [Symbol.asyncDispose]() {
|
||||
try {
|
||||
await Deno.remove(dir, { recursive: true });
|
||||
} catch {
|
||||
// Ignore errors Files in tmp will be cleaned up by the OS
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export class MockBuildCache<State> implements BuildCache<State> {
|
||||
#files: FsRouteFile<State>[];
|
||||
root = "";
|
||||
clientEntry = "";
|
||||
islandRegistry: ServerIslandRegistry = new Map();
|
||||
features = { errorOverlay: false };
|
||||
|
||||
constructor(files: FsRouteFile<State>[], mode: "development" | "production") {
|
||||
this.features.errorOverlay = mode === "development";
|
||||
this.#files = files;
|
||||
}
|
||||
|
||||
getFsRoutes(): Command<State>[] {
|
||||
return fsItemsToCommands(this.#files);
|
||||
}
|
||||
|
||||
readFile(_pathname: string): Promise<StaticFile | null> {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
}
|
||||
|
||||
export async function writeFiles(dir: string, files: Record<string, string>) {
|
||||
const entries = Object.entries(files);
|
||||
await Promise.all(entries.map(async (entry) => {
|
||||
const [pathname, content] = entry;
|
||||
const fullPath = path.join(dir, pathname);
|
||||
try {
|
||||
await Deno.mkdir(path.dirname(fullPath), { recursive: true });
|
||||
await Deno.writeTextFile(fullPath, content);
|
||||
} catch (err) {
|
||||
if (!(err instanceof Deno.errors.AlreadyExists)) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import type { RouteHandler } from "./handlers.ts";
|
||||
import type { Method } from "./router.ts";
|
||||
import type { RouteComponent } from "./segments.ts";
|
||||
|
||||
export interface RouteConfig {
|
||||
/**
|
||||
* A route override for the page. This is useful for pages where the route
|
||||
* can not be expressed through the filesystem routing capabilities.
|
||||
*
|
||||
* The route override must be a path-to-regexp compatible route matcher.
|
||||
*/
|
||||
routeOverride?: string;
|
||||
|
||||
/**
|
||||
* If Content-Security-Policy should be enabled for this page. If 'true', a
|
||||
* locked down policy will be used that allows only the scripts and styles
|
||||
* that are generated by Fresh. Additional scripts and styles can be added
|
||||
* using the `useCSP` hook.
|
||||
*/
|
||||
csp?: boolean;
|
||||
|
||||
/**
|
||||
* Skip already inherited layouts
|
||||
* Default: `false`
|
||||
*/
|
||||
skipInheritedLayouts?: boolean;
|
||||
|
||||
/**
|
||||
* Skip rendering the `routes/_app` template
|
||||
* Default: `false`
|
||||
*/
|
||||
skipAppWrapper?: boolean;
|
||||
/**
|
||||
* Which method to use when loading this route lazily. This is only used
|
||||
* for lazy routes.
|
||||
* Default: `ALL`
|
||||
*/
|
||||
methods?: "ALL" | Method[];
|
||||
}
|
||||
|
||||
export interface LayoutConfig {
|
||||
/**
|
||||
* Skip already inherited layouts
|
||||
* Default: `false`
|
||||
*/
|
||||
skipInheritedLayouts?: boolean;
|
||||
|
||||
/**
|
||||
* Skip rendering the `routes/_app` template
|
||||
* Default: `false`
|
||||
*/
|
||||
skipAppWrapper?: boolean;
|
||||
}
|
||||
|
||||
export interface Route<State> {
|
||||
component?: RouteComponent<State>;
|
||||
config?: RouteConfig;
|
||||
handler?: RouteHandler<unknown, State>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lazily construct items like middlewares, handlers, etc by wrapping them
|
||||
* in a function.
|
||||
*/
|
||||
export type Lazy<T> = () => Promise<T>;
|
||||
|
||||
/**
|
||||
* Return T or lazy version of T
|
||||
*/
|
||||
export type MaybeLazy<T> = T | Lazy<T>;
|
||||
|
||||
// TODO: Uncomment once JSR supports global types
|
||||
// declare global {
|
||||
// namespace preact.createElement.JSX {
|
||||
// interface HTMLAttributes {
|
||||
// /**
|
||||
// * Alternative url to fetch partials from on `<a>` or `<form>` tags
|
||||
// */
|
||||
// "f-partial"?: string | SignalLike<string>;
|
||||
// /**
|
||||
// * Enable or disable client side navigation and partials for this
|
||||
// * particular node and its children.
|
||||
// */
|
||||
// "f-client-nav"?: boolean | SignalLike<boolean>;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
@@ -0,0 +1,108 @@
|
||||
import * as path from "@std/path";
|
||||
import type { Lazy, MaybeLazy } from "./types.ts";
|
||||
import { pathToFileUrl, relativeUrl } from "./file_url.ts";
|
||||
|
||||
export function assertInDir(
|
||||
filePath: string,
|
||||
dir: string,
|
||||
): void {
|
||||
let tmp = filePath;
|
||||
if (!path.isAbsolute(tmp)) {
|
||||
tmp = path.join(dir, filePath);
|
||||
}
|
||||
|
||||
if (path.relative(dir, tmp).startsWith(".")) {
|
||||
throw new Error(`Path "${tmp}" resolved outside of "${dir}"`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a file path to a valid JS export name.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* pathToExportName("/islands/foo.tsx"); // "foo"
|
||||
* pathToExportName("/islands/foo.v2.tsx"); // "foo_v2"
|
||||
* pathToExportName("/islands/nav-bar.tsx"); // "nav_bar"
|
||||
* pathToExportName("/islands/_.$bar.tsx"); // "_$bar"
|
||||
* pathToExportName("/islands/1.hello.tsx"); // "_hello"
|
||||
* pathToExportName("/islands/collapse...repeat_-dash.tsx");
|
||||
* // "collapse_repeat_dash"
|
||||
* ```
|
||||
*/
|
||||
export function pathToExportName(filePath: string): string {
|
||||
const name = path.basename(filePath, path.extname(filePath));
|
||||
// Regex for valid JS identifier characters
|
||||
const regex = /^[^a-z_$]|[^a-z0-9_$]/gi;
|
||||
return name.replaceAll(regex, "_").replaceAll(/_{2,}/g, "_");
|
||||
}
|
||||
|
||||
const SCRIPT_ESCAPE = /<\/(style|script)/gi;
|
||||
const COMMENT_ESCAPE = /<!--/gi;
|
||||
|
||||
// See https://html.spec.whatwg.org/multipage/scripting.html#restrictions-for-contents-of-script-elements
|
||||
export function escapeScript(
|
||||
content: string,
|
||||
options: { json?: boolean } = {},
|
||||
): string {
|
||||
return content
|
||||
.replaceAll(SCRIPT_ESCAPE, "<\\/$1")
|
||||
.replaceAll(COMMENT_ESCAPE, options.json ? "\\u003C!--" : "\\x3C!--");
|
||||
}
|
||||
|
||||
export class UniqueNamer {
|
||||
#seen = new Map<string, number>();
|
||||
|
||||
getUniqueName(name: string): string {
|
||||
const count = this.#seen.get(name);
|
||||
if (count === undefined) {
|
||||
this.#seen.set(name, 1);
|
||||
} else {
|
||||
this.#seen.set(name, count + 1);
|
||||
name = `${name}_${count}`;
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
}
|
||||
|
||||
const PATH_TO_SPEC = /[\\/]+/g;
|
||||
export function pathToSpec(outDir: string, spec: string): string {
|
||||
const outDirUrl = pathToFileUrl(outDir);
|
||||
|
||||
if (
|
||||
spec.startsWith("http:") || spec.startsWith("https:") ||
|
||||
spec.startsWith("jsr:")
|
||||
) {
|
||||
return spec;
|
||||
} else if (spec.startsWith("file://")) {
|
||||
const fileUrl = pathToFileUrl(spec);
|
||||
spec = relativeUrl(outDirUrl, fileUrl);
|
||||
return maybeDot(spec);
|
||||
}
|
||||
|
||||
spec = path.normalize(spec);
|
||||
if (path.isAbsolute(spec)) {
|
||||
const fileUrl = pathToFileUrl(spec);
|
||||
spec = relativeUrl(outDirUrl, fileUrl);
|
||||
return maybeDot(spec);
|
||||
}
|
||||
|
||||
spec = spec.replaceAll(PATH_TO_SPEC, "/");
|
||||
if (spec.startsWith("/")) {
|
||||
const fileUrl = pathToFileUrl(spec);
|
||||
spec = relativeUrl(outDirUrl, fileUrl);
|
||||
return maybeDot(spec);
|
||||
}
|
||||
|
||||
spec = maybeDot(spec);
|
||||
return spec;
|
||||
}
|
||||
|
||||
function maybeDot(spec: string): string {
|
||||
return spec.startsWith(".") ? spec : `./${spec}`;
|
||||
}
|
||||
|
||||
export function isLazy<T>(value: MaybeLazy<T>): value is Lazy<T> {
|
||||
return typeof value === "function";
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { expect } from "@std/expect";
|
||||
import { escapeScript, pathToExportName, pathToSpec } from "./utils.ts";
|
||||
|
||||
Deno.test("filenameToExportName", () => {
|
||||
expect(pathToExportName("/islands/foo.tsx")).toBe("foo");
|
||||
expect(pathToExportName("/islands/foo.v2.tsx")).toBe("foo_v2");
|
||||
expect(pathToExportName("/islands/nav-bar.tsx")).toBe("nav_bar");
|
||||
expect(pathToExportName("/islands/_.$bar.tsx")).toBe("_$bar");
|
||||
expect(pathToExportName("/islands/1.hello.tsx")).toBe("_hello");
|
||||
expect(pathToExportName("/islands/collapse...repeat_-dash.tsx")).toBe(
|
||||
"collapse_repeat_dash",
|
||||
);
|
||||
});
|
||||
|
||||
Deno.test("escapeScriptContent - closing </script> + </style>", () => {
|
||||
expect(
|
||||
escapeScript(
|
||||
"foo</script>bar</style>baz</script>foobar",
|
||||
),
|
||||
).toEqual(
|
||||
"foo<\\/script>bar<\\/style>baz<\\/script>foobar",
|
||||
);
|
||||
expect(
|
||||
escapeScript(
|
||||
"foo</ScRIpT>bar</StYLe>baz</SCRIPT>foobar",
|
||||
),
|
||||
).toEqual(
|
||||
"foo<\\/ScRIpT>bar<\\/StYLe>baz<\\/SCRIPT>foobar",
|
||||
);
|
||||
});
|
||||
|
||||
Deno.test("escapeScript - legacy <!--", () => {
|
||||
expect(escapeScript("<!--<script>")).toEqual("\\x3C!--<script>");
|
||||
expect(escapeScript("<!--</script>")).toEqual("\\x3C!--<\\/script>");
|
||||
});
|
||||
|
||||
Deno.test("escapeScript - script combined", () => {
|
||||
expect(escapeScript(`// This is a comment containing <!--
|
||||
let foo = x <!--y; // That's valid JS operators
|
||||
const s = "This is a string containing <!--";`)).toEqual(
|
||||
`// This is a comment containing \\x3C!--
|
||||
let foo = x \\x3C!--y; // That's valid JS operators
|
||||
const s = "This is a string containing \\x3C!--";`,
|
||||
);
|
||||
});
|
||||
|
||||
Deno.test("escapeScript - json", () => {
|
||||
expect(escapeScript("<!--<script>", { json: true })).toEqual(
|
||||
"\\u003C!--<script>",
|
||||
);
|
||||
expect(escapeScript("<!--</ScRIpt>", { json: true })).toEqual(
|
||||
"\\u003C!--<\\/ScRIpt>",
|
||||
);
|
||||
});
|
||||
|
||||
Deno.test("pathToSpec", () => {
|
||||
expect(pathToSpec("/foo", "/foo/bar")).toEqual("./bar");
|
||||
expect(pathToSpec("/", "/foo//bar")).toEqual("./foo/bar");
|
||||
expect(pathToSpec("/foo", "bar")).toEqual("./bar");
|
||||
expect(pathToSpec("/foo/bar", "/foo/baz")).toEqual("../baz");
|
||||
expect(pathToSpec("/foo", "file:///foo//bar")).toEqual("./bar");
|
||||
expect(pathToSpec("/foo", "http://example.com")).toEqual(
|
||||
"http://example.com",
|
||||
);
|
||||
expect(pathToSpec("/foo", "https://example.com")).toEqual(
|
||||
"https://example.com",
|
||||
);
|
||||
expect(pathToSpec("/foo", "jsr:@foo/bar")).toEqual("jsr:@foo/bar");
|
||||
});
|
||||
@@ -0,0 +1,166 @@
|
||||
import { App, staticFiles } from "fresh";
|
||||
import {
|
||||
ALL_ISLAND_DIR,
|
||||
assertNotSelector,
|
||||
assertSelector,
|
||||
buildProd,
|
||||
Doc,
|
||||
parseHtml,
|
||||
withBrowserApp,
|
||||
} from "./test_utils.tsx";
|
||||
|
||||
import { FakeServer } from "../src/test_utils.ts";
|
||||
import { Partial } from "fresh/runtime";
|
||||
|
||||
const allIslandCache = await buildProd({ islandDir: ALL_ISLAND_DIR });
|
||||
|
||||
function testApp<T>(): App<T> {
|
||||
const app = new App<T>()
|
||||
.use(staticFiles());
|
||||
|
||||
allIslandCache(app);
|
||||
return app;
|
||||
}
|
||||
|
||||
Deno.test({
|
||||
name: "active links - without client nav",
|
||||
fn: async () => {
|
||||
function View() {
|
||||
return (
|
||||
<Doc>
|
||||
<div>
|
||||
<h1>nav</h1>
|
||||
<p>
|
||||
<a href="/active_nav/foo/bar">/active_nav/foo/bar</a>
|
||||
</p>
|
||||
<p>
|
||||
<a href="/active_nav/foo">/active_nav/foo</a>
|
||||
</p>
|
||||
<p>
|
||||
<a href="/active_nav">/active_nav</a>
|
||||
</p>
|
||||
<p>
|
||||
<a href="/">/</a>
|
||||
</p>
|
||||
</div>
|
||||
</Doc>
|
||||
);
|
||||
}
|
||||
|
||||
const app = testApp()
|
||||
.get("/active_nav/foo", (ctx) => {
|
||||
return ctx.render(<View />);
|
||||
})
|
||||
.get("/active_nav", (ctx) => {
|
||||
return ctx.render(<View />);
|
||||
});
|
||||
|
||||
const server = new FakeServer(app.handler());
|
||||
let res = await server.get("/active_nav");
|
||||
let doc = parseHtml(await res.text());
|
||||
|
||||
assertSelector(doc, "a[href='/'][data-ancestor]");
|
||||
|
||||
// Current
|
||||
assertNotSelector(doc, "a[href='/active_nav'][data-ancestor]");
|
||||
assertSelector(doc, "a[href='/active_nav'][data-current]");
|
||||
assertSelector(doc, `a[href='/active_nav'][aria-current="page"]`);
|
||||
|
||||
// Unrelated links
|
||||
assertNotSelector(doc, "a[href='/active_nav/foo'][data-ancestor]");
|
||||
assertNotSelector(doc, "a[href='/active_nav/foo'][aria-current]");
|
||||
assertNotSelector(doc, "a[href='/active_nav/foo/bar'][data-ancestor]");
|
||||
assertNotSelector(doc, "a[href='/active_nav/foo/bar'][aria-current]");
|
||||
|
||||
res = await server.get(`/active_nav/foo`);
|
||||
doc = parseHtml(await res.text());
|
||||
assertSelector(doc, "a[href='/active_nav/foo'][data-current]");
|
||||
assertSelector(doc, `a[href='/active_nav/foo'][aria-current="page"]`);
|
||||
assertSelector(doc, "a[href='/active_nav'][data-ancestor]");
|
||||
assertSelector(doc, `a[href='/active_nav'][aria-current="true"]`);
|
||||
assertSelector(doc, "a[href='/'][data-ancestor]");
|
||||
assertSelector(doc, `a[href='/'][aria-current="true"]`);
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "active links - updates outside of vdom",
|
||||
fn: async () => {
|
||||
function PartialPage() {
|
||||
return (
|
||||
<div>
|
||||
<Partial name="content">
|
||||
<h1>/active_nav_partial</h1>
|
||||
</Partial>
|
||||
<p>
|
||||
<a href="/active_nav_partial/foo/bar">
|
||||
/active_nav_partial/foo/bar
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
<a href="/active_nav_partial/foo">/active_nav_partial/foo</a>
|
||||
</p>
|
||||
<p>
|
||||
<a href="/active_nav_partial">/active_nav_partial</a>
|
||||
</p>
|
||||
<p>
|
||||
<a href="/">/</a>
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const app = testApp()
|
||||
.get("/active_nav_partial/foo", (ctx) => {
|
||||
return ctx.render(<PartialPage />);
|
||||
})
|
||||
.get("/active_nav_partial", (ctx) => {
|
||||
return ctx.render(<PartialPage />);
|
||||
});
|
||||
|
||||
await withBrowserApp(app, async (page, address) => {
|
||||
await page.goto(`${address}/active_nav_partial`);
|
||||
|
||||
let doc = parseHtml(await page.content());
|
||||
assertSelector(doc, "a[href='/'][data-ancestor]");
|
||||
|
||||
// Current
|
||||
assertNotSelector(doc, "a[href='/active_nav_partial'][data-ancestor]");
|
||||
assertSelector(doc, "a[href='/active_nav_partial'][data-current]");
|
||||
assertSelector(doc, `a[href='/active_nav_partial'][aria-current="page"]`);
|
||||
|
||||
// Unrelated links
|
||||
assertNotSelector(
|
||||
doc,
|
||||
"a[href='/active_nav_partial/foo'][data-ancestor]",
|
||||
);
|
||||
assertNotSelector(
|
||||
doc,
|
||||
"a[href='/active_nav_partial/foo'][aria-current]",
|
||||
);
|
||||
assertNotSelector(
|
||||
doc,
|
||||
"a[href='/active_nav_partial/foo/bar'][data-ancestor]",
|
||||
);
|
||||
assertNotSelector(
|
||||
doc,
|
||||
"a[href='/active_nav_partial/foo/bar'][aria-current]",
|
||||
);
|
||||
|
||||
await page.goto(`${address}/active_nav_partial/foo`);
|
||||
doc = parseHtml(await page.content());
|
||||
assertSelector(doc, "a[href='/active_nav_partial/foo'][data-current]");
|
||||
assertSelector(
|
||||
doc,
|
||||
`a[href='/active_nav_partial/foo'][aria-current="page"]`,
|
||||
);
|
||||
assertSelector(doc, "a[href='/active_nav_partial'][data-ancestor]");
|
||||
assertSelector(
|
||||
doc,
|
||||
`a[href='/active_nav_partial'][data-ancestor][aria-current="true"]`,
|
||||
);
|
||||
assertSelector(doc, "a[href='/'][data-ancestor]");
|
||||
assertSelector(doc, `a[href='/'][aria-current="true"]`);
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
import twDenoJson from "../../plugin-tailwindcss/deno.json" with {
|
||||
type: "json",
|
||||
};
|
||||
import * as Marked from "marked";
|
||||
import { ensureDir, walk } from "@std/fs";
|
||||
import { dirname, join, relative } from "@std/path";
|
||||
// import { expect } from "@std/expect/expect";
|
||||
import { withTmpDir } from "../src/test_utils.ts";
|
||||
import { FRESH_VERSION, PREACT_VERSION } from "../../update/src/update.ts";
|
||||
|
||||
Deno.test("Docs Code example checks", async () => {
|
||||
await using tmp = await withTmpDir();
|
||||
|
||||
for await (const { path, code } of docsMarkdownFiles()) {
|
||||
const codePath = join(tmp.dir, path);
|
||||
await ensureDir(dirname(codePath));
|
||||
await Deno.writeTextFile(codePath, code);
|
||||
}
|
||||
|
||||
const denoJson = {
|
||||
lock: false,
|
||||
imports: {
|
||||
fresh: `jsr:@fresh/core@${FRESH_VERSION}`,
|
||||
"@fresh/plugin-tailwind-v3":
|
||||
`jsr:@fresh/plugin-tailwind@^${twDenoJson.version}`,
|
||||
"@fresh/plugin-tailwind":
|
||||
`jsr:@fresh/plugin-tailwind@^${twDenoJson.version}`,
|
||||
preact: `npm:preact@^${PREACT_VERSION}`,
|
||||
"@deno/gfm": "jsr:@deno/gfm@^0.11.0",
|
||||
"@std/expect": "jsr:@std/expect@^1.0.16",
|
||||
},
|
||||
compilerOptions: {
|
||||
lib: ["dom", "dom.asynciterable", "deno.ns", "deno.unstable"],
|
||||
jsx: "precompile",
|
||||
jsxImportSource: "preact",
|
||||
jsxPrecompileSkipElements: ["a", "img", "source", "body", "html", "head"],
|
||||
},
|
||||
};
|
||||
await Deno.writeTextFile(
|
||||
join(tmp.dir, "deno.json"),
|
||||
JSON.stringify(denoJson, undefined, 2),
|
||||
);
|
||||
|
||||
// Download and cache all dependencies (reduces `stdout` noise)
|
||||
await new Deno.Command(Deno.execPath(), {
|
||||
args: ["cache", "**/*"],
|
||||
cwd: tmp.dir,
|
||||
}).output();
|
||||
|
||||
const { stdout, stderr } = await new Deno.Command(Deno.execPath(), {
|
||||
args: ["check", "**/*"],
|
||||
cwd: tmp.dir,
|
||||
}).output();
|
||||
|
||||
const decoder = new TextDecoder();
|
||||
const output = `${decoder.decode(stdout)}\n${decoder.decode(stderr)}`;
|
||||
// Log `deno check` output (can be removed if expects below are enabled)
|
||||
// deno-lint-ignore no-console
|
||||
console.log(output);
|
||||
|
||||
// TODO: Enable after fixing docs check issues
|
||||
// expect(code).toBe(0);
|
||||
// expect(output).toBe("");
|
||||
});
|
||||
|
||||
async function* docsMarkdownFiles() {
|
||||
// Limit to checking Fresh v2 (canary) docs for now
|
||||
const docsDir = join(
|
||||
import.meta.dirname!,
|
||||
"..",
|
||||
"..",
|
||||
"..",
|
||||
"docs",
|
||||
"canary",
|
||||
);
|
||||
const docsIter = walk(docsDir, { exts: [".md"], includeDirs: false });
|
||||
|
||||
for await (const entry of docsIter) {
|
||||
for (const { file, code } of await extractTsCode(entry.path)) {
|
||||
const path = join(relative(docsDir, entry.path), file);
|
||||
yield { path, code };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function extractTsCode(path: string) {
|
||||
const code: { file: string; code: string }[] = [];
|
||||
const input = await Deno.readTextFile(path);
|
||||
let index = 0;
|
||||
|
||||
const tokens = await Marked.lexer(input, { gfm: true, async: true });
|
||||
|
||||
Marked.walkTokens(tokens, (token) => {
|
||||
// Get rid of `Marked.Tokens.Generic`
|
||||
const t = token as Marked.MarkedToken;
|
||||
if (t.type !== "code") return;
|
||||
|
||||
const result = /^([tj]sx?)\s*/.exec(t.lang ?? "");
|
||||
if (!result) return;
|
||||
|
||||
// Codeblock must be TS/JS
|
||||
index += 1;
|
||||
|
||||
// Probably a filename, but perhaps a title,
|
||||
// so get rid of non-file safe characters
|
||||
const [match, ext] = result;
|
||||
let file = t.lang!.slice(match.length)
|
||||
.toLocaleLowerCase()
|
||||
.replaceAll(/[^a-z0-9._\-\/\\]/g, "_")
|
||||
.replaceAll(/_{2,}/g, "_") || String(index);
|
||||
|
||||
if (!file.endsWith(ext)) file += `.${ext}`;
|
||||
|
||||
code.push({ file, code: t.text });
|
||||
});
|
||||
|
||||
return code;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { useSignal } from "@preact/signals";
|
||||
import { useEffect } from "preact/hooks";
|
||||
|
||||
export function Foo() {
|
||||
const active = useSignal(false);
|
||||
useEffect(() => {
|
||||
active.value = true;
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div id="foo-both" class={active.value ? "ready" : ""}>
|
||||
{active.value ? "it works" : "it doesn't work"}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { Foo } from "./(_islands)/Foo.tsx";
|
||||
import { Foo as Foo2 } from "../foo/(_islands)/Foo.tsx";
|
||||
|
||||
export default function Home() {
|
||||
return (
|
||||
<div>
|
||||
<Foo />
|
||||
<Foo2 />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { useSignal } from "@preact/signals";
|
||||
import { useEffect } from "preact/hooks";
|
||||
|
||||
export function Foo() {
|
||||
const active = useSignal(false);
|
||||
useEffect(() => {
|
||||
active.value = true;
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div id="foo" class={active.value ? "ready" : ""}>
|
||||
{active.value ? "it works" : "it doesn't work"}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Foo } from "./(_islands)/Foo.tsx";
|
||||
|
||||
export default function Home() {
|
||||
return (
|
||||
<div>
|
||||
<Foo />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export default function Home() {
|
||||
return <h1>hello world</h1>;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"workspace": [],
|
||||
"lock": false,
|
||||
"links": ["../../.."],
|
||||
"compilerOptions": {
|
||||
"jsx": "precompile",
|
||||
"jsxImportSource": "preact"
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user