feat: expose layouts and pages on App (#3086)
This PR extracts the functionality from the `fs_routes` plugin and exposes it onto `App`. These are the new APIs: - `app.layout(pattern, route)` - `app.onError(pattern, route)` - `app.notFound(pattern, route)` - `app.route(pattern, route)` This also removes the need for `.use(staticFiles())`. This line can be safely removed. Fixes https://github.com/denoland/fresh/issues/3040 Fixes https://github.com/denoland/fresh/issues/3033 Fixes https://github.com/denoland/fresh/issues/2591 Fixes https://github.com/denoland/fresh/issues/950 Fixes https://github.com/denoland/fresh/issues/1918
This commit is contained in:
+1
-3
@@ -360,13 +360,11 @@ ${GRADIENT_CSS}`;
|
|||||||
// Skip this and be silent if there is a network issue.
|
// Skip this and be silent if there is a network issue.
|
||||||
}
|
}
|
||||||
|
|
||||||
const MAIN_TS = `import { App, fsRoutes, staticFiles } from "fresh";
|
const MAIN_TS = `import { App, fsRoutes } from "fresh";
|
||||||
import { define, type State } from "./utils.ts";
|
import { define, type State } from "./utils.ts";
|
||||||
|
|
||||||
export const app = new App<State>();
|
export const app = new App<State>();
|
||||||
|
|
||||||
app.use(staticFiles());
|
|
||||||
|
|
||||||
// this is the same as the /api/:name route defined via a file. feel free to delete this!
|
// this is the same as the /api/:name route defined via a file. feel free to delete this!
|
||||||
app.get("/api2/:name", (ctx) => {
|
app.get("/api2/:name", (ctx) => {
|
||||||
const name = ctx.params.name;
|
const name = ctx.params.name;
|
||||||
|
|||||||
+259
-80
@@ -5,18 +5,32 @@ import { trace } from "@opentelemetry/api";
|
|||||||
import { DENO_DEPLOYMENT_ID } from "./runtime/build_id.ts";
|
import { DENO_DEPLOYMENT_ID } from "./runtime/build_id.ts";
|
||||||
import * as colors from "@std/fmt/colors";
|
import * as colors from "@std/fmt/colors";
|
||||||
import { type MiddlewareFn, runMiddlewares } from "./middlewares/mod.ts";
|
import { type MiddlewareFn, runMiddlewares } from "./middlewares/mod.ts";
|
||||||
import { FreshReqContext } from "./context.ts";
|
import { Context, type ServerIslandRegistry } from "./context.ts";
|
||||||
import { type Method, type Router, UrlPatternRouter } from "./router.ts";
|
import {
|
||||||
|
mergePath,
|
||||||
|
type Method,
|
||||||
|
type Router,
|
||||||
|
UrlPatternRouter,
|
||||||
|
} from "./router.ts";
|
||||||
import {
|
import {
|
||||||
type FreshConfig,
|
type FreshConfig,
|
||||||
normalizeConfig,
|
normalizeConfig,
|
||||||
type ResolvedFreshConfig,
|
type ResolvedFreshConfig,
|
||||||
} from "./config.ts";
|
} from "./config.ts";
|
||||||
import { type BuildCache, ProdBuildCache } from "./build_cache.ts";
|
import { type BuildCache, ProdBuildCache } from "./build_cache.ts";
|
||||||
import type { ServerIslandRegistry } from "./context.ts";
|
|
||||||
import { FinishSetup, ForgotBuild } from "./finish_setup.tsx";
|
import { FinishSetup, ForgotBuild } from "./finish_setup.tsx";
|
||||||
import { HttpError } from "./error.ts";
|
import { HttpError } from "./error.ts";
|
||||||
import { mergePaths, pathToExportName } from "./utils.ts";
|
import { pathToExportName } from "./utils.ts";
|
||||||
|
import type { LayoutConfig, Route } from "./types.ts";
|
||||||
|
import {
|
||||||
|
getOrCreateSegment,
|
||||||
|
newSegment,
|
||||||
|
renderRoute,
|
||||||
|
type RouteComponent,
|
||||||
|
segmentToMiddlewares,
|
||||||
|
} from "./segments.ts";
|
||||||
|
import { isHandlerByMethod, type PageResponse } from "./handlers.ts";
|
||||||
|
import { serveInternalStaticFiles } from "./middlewares/static_files.ts";
|
||||||
|
|
||||||
// TODO: Completed type clashes in older Deno versions
|
// TODO: Completed type clashes in older Deno versions
|
||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
@@ -25,12 +39,44 @@ export const DEFAULT_CONN_INFO: any = {
|
|||||||
remoteAddr: { transport: "tcp", hostname: "localhost", port: 1234 },
|
remoteAddr: { transport: "tcp", hostname: "localhost", port: 1234 },
|
||||||
};
|
};
|
||||||
|
|
||||||
const DEFAULT_NOT_FOUND = () => {
|
/** Used to group mounted apps. Only internal */
|
||||||
|
let INTERNAL_ID = 0;
|
||||||
|
|
||||||
|
const DEFAULT_RENDER = <State>(): Promise<PageResponse<State>> =>
|
||||||
|
// deno-lint-ignore no-explicit-any
|
||||||
|
Promise.resolve({ data: {} as any });
|
||||||
|
|
||||||
|
const DEFAULT_NOT_FOUND = (): Promise<Response> => {
|
||||||
throw new HttpError(404);
|
throw new HttpError(404);
|
||||||
};
|
};
|
||||||
const DEFAULT_NOT_ALLOWED_METHOD = () => {
|
const DEFAULT_NOT_ALLOWED_METHOD = (): Promise<Response> => {
|
||||||
throw new HttpError(405);
|
throw new HttpError(405);
|
||||||
};
|
};
|
||||||
|
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 =
|
export type ListenOptions =
|
||||||
& Partial<
|
& Partial<
|
||||||
@@ -117,7 +163,6 @@ async function listenOnFreePort(
|
|||||||
throw firstError;
|
throw firstError;
|
||||||
}
|
}
|
||||||
|
|
||||||
export let getRouter: <State>(app: App<State>) => Router<MiddlewareFn<State>>;
|
|
||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
export let getIslandRegistry: (app: App<any>) => ServerIslandRegistry;
|
export let getIslandRegistry: (app: App<any>) => ServerIslandRegistry;
|
||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
@@ -132,9 +177,15 @@ export class App<State> {
|
|||||||
#islandRegistry: ServerIslandRegistry = new Map();
|
#islandRegistry: ServerIslandRegistry = new Map();
|
||||||
#buildCache: BuildCache | null = null;
|
#buildCache: BuildCache | null = null;
|
||||||
#islandNames = new Set<string>();
|
#islandNames = new Set<string>();
|
||||||
|
#root = newSegment<State>("", null);
|
||||||
|
#routeDefs: {
|
||||||
|
method: Method | "ALL";
|
||||||
|
pattern: string;
|
||||||
|
fns: MiddlewareFn<State>[];
|
||||||
|
unshift: boolean;
|
||||||
|
}[] = [];
|
||||||
|
|
||||||
static {
|
static {
|
||||||
getRouter = (app) => app.#router;
|
|
||||||
getIslandRegistry = (app) => app.#islandRegistry;
|
getIslandRegistry = (app) => app.#islandRegistry;
|
||||||
getBuildCache = (app) => app.#buildCache;
|
getBuildCache = (app) => app.#buildCache;
|
||||||
setBuildCache = (app, cache) => app.#buildCache = cache;
|
setBuildCache = (app, cache) => app.#buildCache = cache;
|
||||||
@@ -175,76 +226,170 @@ export class App<State> {
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
use(middleware: MiddlewareFn<State>): this {
|
use(...middleware: MiddlewareFn<State>[]): this;
|
||||||
this.#router.addMiddleware(middleware);
|
use(path: string, ...middleware: MiddlewareFn<State>[]): this;
|
||||||
|
use(
|
||||||
|
pathOrMiddleware: string | MiddlewareFn<State>,
|
||||||
|
...middlewares: MiddlewareFn<State>[]
|
||||||
|
): this {
|
||||||
|
let path: string;
|
||||||
|
let fns: MiddlewareFn<State>[];
|
||||||
|
if (typeof pathOrMiddleware === "string") {
|
||||||
|
path = pathOrMiddleware;
|
||||||
|
fns = middlewares!;
|
||||||
|
} else {
|
||||||
|
path = "*";
|
||||||
|
middlewares.unshift(pathOrMiddleware);
|
||||||
|
fns = middlewares;
|
||||||
|
}
|
||||||
|
|
||||||
|
const segment = getOrCreateSegment(this.#root, path, false);
|
||||||
|
segment.middlewares.push(...fns);
|
||||||
|
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
notFound(routeOrMiddleware: Route<State> | MiddlewareFn<State>): this {
|
||||||
|
const route = typeof routeOrMiddleware === "function"
|
||||||
|
? { handler: routeOrMiddleware }
|
||||||
|
: routeOrMiddleware;
|
||||||
|
ensureHandler(route);
|
||||||
|
this.#root.notFound = (ctx) => renderRoute(ctx, route);
|
||||||
|
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
onError(
|
||||||
|
path: string,
|
||||||
|
routeOrMiddleware: Route<State> | MiddlewareFn<State>,
|
||||||
|
): this {
|
||||||
|
const segment = getOrCreateSegment(this.#root, path, true);
|
||||||
|
segment.errorRoute = typeof routeOrMiddleware === "function"
|
||||||
|
? { handler: routeOrMiddleware }
|
||||||
|
: routeOrMiddleware;
|
||||||
|
|
||||||
|
ensureHandler(segment.errorRoute);
|
||||||
|
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
appWrapper(component: RouteComponent<State>) {
|
||||||
|
const segment = getOrCreateSegment<State>(this.#root, "", false);
|
||||||
|
segment.app = component;
|
||||||
|
}
|
||||||
|
|
||||||
|
layout(
|
||||||
|
path: string,
|
||||||
|
component: RouteComponent<State>,
|
||||||
|
config?: LayoutConfig,
|
||||||
|
): this {
|
||||||
|
const segment = getOrCreateSegment<State>(this.#root, path, true);
|
||||||
|
segment.layout = { component, config: config ?? null };
|
||||||
|
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
route(path: string, route: Route<State>): this {
|
||||||
|
const segment = getOrCreateSegment<State>(this.#root, path, false);
|
||||||
|
const middlewares = segmentToMiddlewares(segment);
|
||||||
|
|
||||||
|
ensureHandler(route);
|
||||||
|
middlewares.push((ctx) => renderRoute(ctx, route));
|
||||||
|
|
||||||
|
const routePath = route.config?.routeOverride ?? path;
|
||||||
|
|
||||||
|
if (typeof route.handler === "function") {
|
||||||
|
this.#addRoute("ALL", routePath, middlewares);
|
||||||
|
} else if (isHandlerByMethod(route.handler!)) {
|
||||||
|
for (const method of Object.keys(route.handler)) {
|
||||||
|
this.#addRoute(method as Method, routePath, middlewares);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
get(path: string, ...middlewares: MiddlewareFn<State>[]): this {
|
get(path: string, ...middlewares: MiddlewareFn<State>[]): this {
|
||||||
return this.#addRoutes("GET", path, middlewares);
|
this.#addMiddleware("GET", path, middlewares);
|
||||||
|
return this;
|
||||||
}
|
}
|
||||||
post(path: string, ...middlewares: MiddlewareFn<State>[]): this {
|
post(path: string, ...middlewares: MiddlewareFn<State>[]): this {
|
||||||
return this.#addRoutes("POST", path, middlewares);
|
this.#addMiddleware("POST", path, middlewares);
|
||||||
|
return this;
|
||||||
}
|
}
|
||||||
patch(path: string, ...middlewares: MiddlewareFn<State>[]): this {
|
patch(path: string, ...middlewares: MiddlewareFn<State>[]): this {
|
||||||
return this.#addRoutes("PATCH", path, middlewares);
|
this.#addMiddleware("PATCH", path, middlewares);
|
||||||
|
return this;
|
||||||
}
|
}
|
||||||
put(path: string, ...middlewares: MiddlewareFn<State>[]): this {
|
put(path: string, ...middlewares: MiddlewareFn<State>[]): this {
|
||||||
return this.#addRoutes("PUT", path, middlewares);
|
this.#addMiddleware("PUT", path, middlewares);
|
||||||
|
return this;
|
||||||
}
|
}
|
||||||
delete(path: string, ...middlewares: MiddlewareFn<State>[]): this {
|
delete(path: string, ...middlewares: MiddlewareFn<State>[]): this {
|
||||||
return this.#addRoutes("DELETE", path, middlewares);
|
this.#addMiddleware("DELETE", path, middlewares);
|
||||||
|
return this;
|
||||||
}
|
}
|
||||||
head(path: string, ...middlewares: MiddlewareFn<State>[]): this {
|
head(path: string, ...middlewares: MiddlewareFn<State>[]): this {
|
||||||
return this.#addRoutes("HEAD", path, middlewares);
|
this.#addMiddleware("HEAD", path, middlewares);
|
||||||
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
all(path: string, ...middlewares: MiddlewareFn<State>[]): this {
|
all(path: string, ...middlewares: MiddlewareFn<State>[]): this {
|
||||||
return this.#addRoutes("ALL", path, middlewares);
|
this.#addMiddleware("ALL", path, middlewares);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
#addMiddleware(
|
||||||
|
method: Method | "ALL",
|
||||||
|
path: string,
|
||||||
|
fns: MiddlewareFn<State>[],
|
||||||
|
unshift = false,
|
||||||
|
) {
|
||||||
|
const segment = getOrCreateSegment<State>(this.#root, path, false);
|
||||||
|
const result = segmentToMiddlewares(segment);
|
||||||
|
|
||||||
|
result.push(...fns);
|
||||||
|
|
||||||
|
const resPath = mergePath(this.config.basePath, path);
|
||||||
|
this.#addRoute(method, resPath, result, unshift);
|
||||||
|
}
|
||||||
|
|
||||||
|
#addRoute(
|
||||||
|
method: Method | "ALL",
|
||||||
|
path: string,
|
||||||
|
fns: MiddlewareFn<State>[],
|
||||||
|
unshift = false,
|
||||||
|
) {
|
||||||
|
this.#routeDefs.push({ method, pattern: path, fns, unshift });
|
||||||
}
|
}
|
||||||
|
|
||||||
mountApp(path: string, app: App<State>): this {
|
mountApp(path: string, app: App<State>): this {
|
||||||
const routes = app.#router._routes;
|
const segmentPath = mergePath(path, `/__${INTERNAL_ID++}/`);
|
||||||
|
const segment = getOrCreateSegment(this.#root, segmentPath, true);
|
||||||
|
const fns = segmentToMiddlewares(segment);
|
||||||
|
|
||||||
|
const routes = app.#routeDefs;
|
||||||
|
for (let i = 0; i < routes.length; i++) {
|
||||||
|
const route = routes[i];
|
||||||
|
|
||||||
|
const merged = mergePath(path, route.pattern);
|
||||||
|
const mergedFns = [...fns, ...route.fns];
|
||||||
|
this.#addRoute(route.method, merged, mergedFns, route.unshift);
|
||||||
|
}
|
||||||
|
|
||||||
app.#islandRegistry.forEach((value, key) => {
|
app.#islandRegistry.forEach((value, key) => {
|
||||||
this.#islandRegistry.set(key, value);
|
this.#islandRegistry.set(key, value);
|
||||||
});
|
});
|
||||||
|
|
||||||
const middlewares = app.#router._middlewares;
|
app.#root.notFound = this.#root.notFound;
|
||||||
|
|
||||||
// Special case when user calls one of these:
|
|
||||||
// - `app.mountApp("/", otherApp)`
|
|
||||||
// - `app.mountApp("/*", otherApp)`
|
|
||||||
const isSelf = path === "/*" || path === "/";
|
|
||||||
if (isSelf && middlewares.length > 0) {
|
|
||||||
this.#router._middlewares.push(...middlewares);
|
|
||||||
}
|
|
||||||
|
|
||||||
for (let i = 0; i < routes.length; i++) {
|
|
||||||
const route = routes[i];
|
|
||||||
|
|
||||||
const merged = typeof route.path === "string"
|
|
||||||
? mergePaths(path, route.path)
|
|
||||||
: route.path;
|
|
||||||
const combined = isSelf
|
|
||||||
? route.handlers
|
|
||||||
: middlewares.concat(route.handlers);
|
|
||||||
this.#router.add(route.method, merged, combined);
|
|
||||||
}
|
|
||||||
|
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
#addRoutes(
|
/**
|
||||||
method: Method | "ALL",
|
* Create handler function for `Deno.serve` or to be used in
|
||||||
pathname: string | URLPattern,
|
* testing.
|
||||||
middlewares: MiddlewareFn<State>[],
|
*/
|
||||||
): this {
|
|
||||||
const merged = typeof pathname === "string"
|
|
||||||
? mergePaths(this.config.basePath, pathname)
|
|
||||||
: pathname;
|
|
||||||
this.#router.add(method, merged, middlewares);
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
handler(): (
|
handler(): (
|
||||||
request: Request,
|
request: Request,
|
||||||
info?: Deno.ServeHandlerInfo,
|
info?: Deno.ServeHandlerInfo,
|
||||||
@@ -263,6 +408,27 @@ export class App<State> {
|
|||||||
return missingBuildHandler;
|
return missingBuildHandler;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const staticMids: MiddlewareFn<State>[] = [];
|
||||||
|
if (this.#root.middlewares.length > 0) {
|
||||||
|
staticMids.push(...this.#root.middlewares);
|
||||||
|
}
|
||||||
|
|
||||||
|
staticMids.push(serveInternalStaticFiles());
|
||||||
|
|
||||||
|
this.#addMiddleware(
|
||||||
|
"ALL",
|
||||||
|
"*",
|
||||||
|
staticMids,
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
|
||||||
|
for (let i = 0; i < this.#routeDefs.length; i++) {
|
||||||
|
const route = this.#routeDefs[i];
|
||||||
|
this.#router.add(route.method, route.pattern, route.fns, route.unshift);
|
||||||
|
}
|
||||||
|
|
||||||
|
const rootMiddlewares = this.#root.middlewares;
|
||||||
|
|
||||||
return async (
|
return async (
|
||||||
req: Request,
|
req: Request,
|
||||||
conn: Deno.ServeHandlerInfo = DEFAULT_CONN_INFO,
|
conn: Deno.ServeHandlerInfo = DEFAULT_CONN_INFO,
|
||||||
@@ -273,13 +439,32 @@ export class App<State> {
|
|||||||
|
|
||||||
const method = req.method.toUpperCase() as Method;
|
const method = req.method.toUpperCase() as Method;
|
||||||
const matched = this.#router.match(method, url);
|
const matched = this.#router.match(method, url);
|
||||||
|
let { params, pattern, handlers, methodMatch } = matched;
|
||||||
|
|
||||||
const next = matched.patternMatch && !matched.methodMatch
|
const span = trace.getActiveSpan();
|
||||||
? DEFAULT_NOT_ALLOWED_METHOD
|
if (span && pattern) {
|
||||||
: DEFAULT_NOT_FOUND;
|
span.updateName(`${method} ${pattern}`);
|
||||||
|
span.setAttribute("http.route", pattern);
|
||||||
|
}
|
||||||
|
|
||||||
const { params, handlers, pattern } = matched;
|
let next: () => Promise<Response>;
|
||||||
const ctx = new FreshReqContext<State>(
|
|
||||||
|
if (pattern === null || !methodMatch) {
|
||||||
|
handlers = rootMiddlewares;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (matched.pattern !== null && !methodMatch) {
|
||||||
|
if (method === "OPTIONS") {
|
||||||
|
const allowed = this.#router.getAllowedMethods(matched.pattern);
|
||||||
|
next = defaultOptionsHandler(allowed);
|
||||||
|
} else {
|
||||||
|
next = DEFAULT_NOT_ALLOWED_METHOD;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
next = DEFAULT_NOT_FOUND;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ctx = new Context<State>(
|
||||||
req,
|
req,
|
||||||
url,
|
url,
|
||||||
conn,
|
conn,
|
||||||
@@ -290,19 +475,10 @@ export class App<State> {
|
|||||||
this.#buildCache!,
|
this.#buildCache!,
|
||||||
);
|
);
|
||||||
|
|
||||||
const span = trace.getActiveSpan();
|
|
||||||
if (span && pattern) {
|
|
||||||
span.updateName(`${method} ${pattern}`);
|
|
||||||
span.setAttribute("http.route", pattern);
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
let result: unknown;
|
if (handlers.length === 0) return await next();
|
||||||
if (handlers.length === 1 && handlers[0].length === 1) {
|
|
||||||
result = await handlers[0][0](ctx);
|
const result = await runMiddlewares(handlers, ctx);
|
||||||
} else {
|
|
||||||
result = await runMiddlewares(handlers, ctx);
|
|
||||||
}
|
|
||||||
if (!(result instanceof Response)) {
|
if (!(result instanceof Response)) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`Expected a "Response" instance to be returned, but got: ${result}`,
|
`Expected a "Response" instance to be returned, but got: ${result}`,
|
||||||
@@ -311,17 +487,8 @@ export class App<State> {
|
|||||||
|
|
||||||
return result;
|
return result;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err instanceof HttpError) {
|
ctx.error = err;
|
||||||
if (err.status >= 500) {
|
return await DEFAULT_ERROR_HANDLER(ctx);
|
||||||
// deno-lint-ignore no-console
|
|
||||||
console.error(err);
|
|
||||||
}
|
|
||||||
return new Response(err.message, { status: err.status });
|
|
||||||
}
|
|
||||||
|
|
||||||
// deno-lint-ignore no-console
|
|
||||||
console.error(err);
|
|
||||||
return new Response("Internal server error", { status: 500 });
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -331,7 +498,7 @@ export class App<State> {
|
|||||||
options.onListen = createOnListen(this.config.basePath, options);
|
options.onListen = createOnListen(this.config.basePath, options);
|
||||||
}
|
}
|
||||||
|
|
||||||
const handler = await this.handler();
|
const handler = this.handler();
|
||||||
if (options.port) {
|
if (options.port) {
|
||||||
await Deno.serve(options, handler);
|
await Deno.serve(options, handler);
|
||||||
return;
|
return;
|
||||||
@@ -351,3 +518,15 @@ const missingBuildHandler = async (): Promise<Response> => {
|
|||||||
: renderToString(h(ForgotBuild, null));
|
: renderToString(h(ForgotBuild, null));
|
||||||
return new Response(html, { headers, status: 500 });
|
return new Response(html, { headers, status: 500 });
|
||||||
};
|
};
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+79
-3
@@ -2,6 +2,7 @@ import { expect } from "@std/expect";
|
|||||||
import { App, getIslandRegistry, setBuildCache } from "./app.ts";
|
import { App, getIslandRegistry, setBuildCache } from "./app.ts";
|
||||||
import { FakeServer } from "./test_utils.ts";
|
import { FakeServer } from "./test_utils.ts";
|
||||||
import { ProdBuildCache } from "./build_cache.ts";
|
import { ProdBuildCache } from "./build_cache.ts";
|
||||||
|
import { HttpError } from "./error.ts";
|
||||||
|
|
||||||
Deno.test("App - .use()", async () => {
|
Deno.test("App - .use()", async () => {
|
||||||
const app = new App<{ text: string }>()
|
const app = new App<{ text: string }>()
|
||||||
@@ -35,8 +36,6 @@ Deno.test("App - .use() #2", async () => {
|
|||||||
|
|
||||||
Deno.test("App - .get()", async () => {
|
Deno.test("App - .get()", async () => {
|
||||||
const app = new App()
|
const app = new App()
|
||||||
.post("/", () => new Response("ok"))
|
|
||||||
.post("/foo", () => new Response("ok"))
|
|
||||||
.get("/", () => new Response("ok"))
|
.get("/", () => new Response("ok"))
|
||||||
.get("/foo", () => new Response("ok"));
|
.get("/foo", () => new Response("ok"));
|
||||||
|
|
||||||
@@ -323,11 +322,11 @@ Deno.test(
|
|||||||
"App - .mountApp() self mount, different order",
|
"App - .mountApp() self mount, different order",
|
||||||
async () => {
|
async () => {
|
||||||
const innerApp = new App<{ text: string }>()
|
const innerApp = new App<{ text: string }>()
|
||||||
.get("/foo", (ctx) => new Response(ctx.state.text))
|
|
||||||
.use(function B(ctx) {
|
.use(function B(ctx) {
|
||||||
ctx.state.text += "B";
|
ctx.state.text += "B";
|
||||||
return ctx.next();
|
return ctx.next();
|
||||||
})
|
})
|
||||||
|
.get("/foo", (ctx) => new Response(ctx.state.text))
|
||||||
.post("/foo", (ctx) => new Response(ctx.state.text));
|
.post("/foo", (ctx) => new Response(ctx.state.text));
|
||||||
|
|
||||||
const app = new App<{ text: string }>()
|
const app = new App<{ text: string }>()
|
||||||
@@ -392,6 +391,27 @@ Deno.test(
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// 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 - catches errors", async () => {
|
Deno.test("App - catches errors", async () => {
|
||||||
let thrownErr: unknown | null = null;
|
let thrownErr: unknown | null = null;
|
||||||
const app = new App<{ text: string }>()
|
const app = new App<{ text: string }>()
|
||||||
@@ -532,3 +552,59 @@ Deno.test("App - adding Island should convert to valid export names", () => {
|
|||||||
fn: component3,
|
fn: component3,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
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");
|
||||||
|
});
|
||||||
|
|||||||
+2
-1
@@ -1,5 +1,6 @@
|
|||||||
import type { ComponentChildren } from "preact";
|
import type { ComponentChildren } from "preact";
|
||||||
import type { FreshContext, PageProps } from "./context.ts";
|
import type { FreshContext } from "./context.ts";
|
||||||
|
import type { PageProps } from "./render.ts";
|
||||||
import type { HandlerFn, RouteHandler } from "./handlers.ts";
|
import type { HandlerFn, RouteHandler } from "./handlers.ts";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
import type { PageProps } from "./context.ts";
|
import type { PageProps } from "./render.ts";
|
||||||
import { assertType, type IsExact } from "@std/testing/types";
|
import { assertType, type IsExact } from "@std/testing/types";
|
||||||
import { expect } from "@std/expect";
|
import { expect } from "@std/expect";
|
||||||
import { type defineApp, type defineLayout, defineRoute } from "./compat.ts";
|
import { type defineApp, type defineLayout, defineRoute } from "./compat.ts";
|
||||||
|
|||||||
+119
-112
@@ -1,22 +1,26 @@
|
|||||||
import {
|
import {
|
||||||
|
type AnyComponent,
|
||||||
type ComponentType,
|
type ComponentType,
|
||||||
|
Fragment,
|
||||||
type FunctionComponent,
|
type FunctionComponent,
|
||||||
h,
|
h,
|
||||||
isValidElement,
|
isValidElement,
|
||||||
type VNode,
|
type VNode,
|
||||||
} from "preact";
|
} from "preact";
|
||||||
import { renderToString } from "preact-render-to-string";
|
|
||||||
import { SpanStatusCode } from "@opentelemetry/api";
|
import { SpanStatusCode } from "@opentelemetry/api";
|
||||||
import type { ResolvedFreshConfig } from "./config.ts";
|
import type { ResolvedFreshConfig } from "./config.ts";
|
||||||
import type { BuildCache } from "./build_cache.ts";
|
import type { BuildCache } from "./build_cache.ts";
|
||||||
import {
|
import { RenderState, setRenderState } from "./runtime/server/preact_hooks.tsx";
|
||||||
FreshScripts,
|
import { PARTIAL_SEARCH_PARAM } from "./constants.ts";
|
||||||
RenderState,
|
|
||||||
setRenderState,
|
|
||||||
} from "./runtime/server/preact_hooks.tsx";
|
|
||||||
import { DEV_ERROR_OVERLAY_URL, PARTIAL_SEARCH_PARAM } from "./constants.ts";
|
|
||||||
import { BUILD_ID } from "./runtime/build_id.ts";
|
|
||||||
import { tracer } from "./otel.ts";
|
import { tracer } from "./otel.ts";
|
||||||
|
import {
|
||||||
|
type ComponentDef,
|
||||||
|
isAsyncAnyComponent,
|
||||||
|
type PageProps,
|
||||||
|
preactRender,
|
||||||
|
renderAsyncAnyComponent,
|
||||||
|
renderRouteComponent,
|
||||||
|
} from "./render.ts";
|
||||||
|
|
||||||
export interface Island {
|
export interface Island {
|
||||||
file: string | URL;
|
file: string | URL;
|
||||||
@@ -27,24 +31,44 @@ export interface Island {
|
|||||||
|
|
||||||
export type ServerIslandRegistry = Map<ComponentType, Island>;
|
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;
|
||||||
|
export let getInternals: <T>(ctx: Context<T>) => UiTree<unknown, T>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The context passed to every middleware. It is unique for every request.
|
* The context passed to every middleware. It is unique for every request.
|
||||||
*/
|
*/
|
||||||
export interface FreshContext<State = unknown> {
|
export class Context<State> {
|
||||||
|
#internal: UiTree<unknown, State> = {
|
||||||
|
app: null,
|
||||||
|
layouts: [],
|
||||||
|
};
|
||||||
/** Reference to the resolved Fresh configuration */
|
/** Reference to the resolved Fresh configuration */
|
||||||
readonly config: ResolvedFreshConfig;
|
readonly config: ResolvedFreshConfig;
|
||||||
readonly state: State;
|
|
||||||
/** The original incoming `Request` object` */
|
|
||||||
readonly req: Request;
|
|
||||||
/**
|
/**
|
||||||
* The request url parsed into an `URL` instance. This is typically used
|
* 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
|
* to apply logic based on the pathname of the incoming url or when
|
||||||
* certain search parameters are set.
|
* certain search parameters are set.
|
||||||
*/
|
*/
|
||||||
readonly url: URL;
|
readonly url: URL;
|
||||||
|
/** The original incoming `Request` object` */
|
||||||
|
readonly req: Request;
|
||||||
readonly params: Record<string, string>;
|
readonly params: Record<string, string>;
|
||||||
readonly error: unknown;
|
readonly state: State = {} as State;
|
||||||
readonly info: Deno.ServeHandlerInfo;
|
data: unknown = undefined;
|
||||||
|
error: unknown | null = null;
|
||||||
|
readonly info: Deno.ServeHandlerInfo | Deno.ServeHandlerInfo;
|
||||||
/**
|
/**
|
||||||
* Whether the current Request is a partial request.
|
* Whether the current Request is a partial request.
|
||||||
*
|
*
|
||||||
@@ -53,20 +77,7 @@ export interface FreshContext<State = unknown> {
|
|||||||
* be used to determine if only `<Partial>`'s need to be rendered.
|
* be used to determine if only `<Partial>`'s need to be rendered.
|
||||||
*/
|
*/
|
||||||
readonly isPartial: boolean;
|
readonly isPartial: boolean;
|
||||||
/**
|
|
||||||
* 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(path: string, status?: number): Response;
|
|
||||||
/**
|
/**
|
||||||
* Call the next middleware.
|
* Call the next middleware.
|
||||||
* ```ts
|
* ```ts
|
||||||
@@ -90,25 +101,7 @@ export interface FreshContext<State = unknown> {
|
|||||||
* return res
|
* return res
|
||||||
* }
|
* }
|
||||||
*/
|
*/
|
||||||
next(): Promise<Response>;
|
next: () => Promise<Response>;
|
||||||
render(vnode: VNode, init?: ResponseInit): Response | Promise<Response>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export let getBuildCache: (ctx: FreshContext<unknown>) => BuildCache;
|
|
||||||
|
|
||||||
export class FreshReqContext<State>
|
|
||||||
implements FreshContext<State>, PageProps<unknown, State> {
|
|
||||||
readonly config: ResolvedFreshConfig;
|
|
||||||
readonly url: URL;
|
|
||||||
readonly req: Request;
|
|
||||||
readonly params: Record<string, string>;
|
|
||||||
readonly state: State = {} as State;
|
|
||||||
data: unknown = undefined;
|
|
||||||
error: unknown | null = null;
|
|
||||||
readonly info: Deno.ServeHandlerInfo | Deno.ServeHandlerInfo;
|
|
||||||
readonly isPartial: boolean;
|
|
||||||
|
|
||||||
next: FreshContext<State>["next"];
|
|
||||||
|
|
||||||
#islandRegistry: ServerIslandRegistry;
|
#islandRegistry: ServerIslandRegistry;
|
||||||
#buildCache: BuildCache;
|
#buildCache: BuildCache;
|
||||||
@@ -117,7 +110,9 @@ export class FreshReqContext<State>
|
|||||||
Component!: FunctionComponent;
|
Component!: FunctionComponent;
|
||||||
|
|
||||||
static {
|
static {
|
||||||
getBuildCache = (ctx) => (ctx as FreshReqContext<unknown>).#buildCache;
|
// deno-lint-ignore no-explicit-any
|
||||||
|
getInternals = (ctx) => (ctx as Context<unknown>).#internal as any;
|
||||||
|
getBuildCache = (ctx) => (ctx as Context<unknown>).#buildCache;
|
||||||
}
|
}
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
@@ -126,7 +121,7 @@ export class FreshReqContext<State>
|
|||||||
info: Deno.ServeHandlerInfo,
|
info: Deno.ServeHandlerInfo,
|
||||||
params: Record<string, string>,
|
params: Record<string, string>,
|
||||||
config: ResolvedFreshConfig,
|
config: ResolvedFreshConfig,
|
||||||
next: FreshContext<State>["next"],
|
next: () => Promise<Response>,
|
||||||
islandRegistry: ServerIslandRegistry,
|
islandRegistry: ServerIslandRegistry,
|
||||||
buildCache: BuildCache,
|
buildCache: BuildCache,
|
||||||
) {
|
) {
|
||||||
@@ -141,6 +136,19 @@ export class FreshReqContext<State>
|
|||||||
this.#buildCache = buildCache;
|
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 {
|
redirect(pathOrUrl: string, status = 302): Response {
|
||||||
let location = pathOrUrl;
|
let location = pathOrUrl;
|
||||||
|
|
||||||
@@ -166,17 +174,61 @@ export class FreshReqContext<State>
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
render(
|
async render(
|
||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
vnode: VNode<any>,
|
vnode: VNode<any> | null,
|
||||||
init: ResponseInit | undefined = {},
|
init: ResponseInit | undefined = {},
|
||||||
): Response | Promise<Response> {
|
): Promise<Response> {
|
||||||
if (arguments.length === 0) {
|
if (arguments.length === 0) {
|
||||||
throw new Error(`No arguments passed to: ctx.render()`);
|
throw new Error(`No arguments passed to: ctx.render()`);
|
||||||
} else if (vnode !== null && !isValidElement(vnode)) {
|
} else if (vnode !== null && !isValidElement(vnode)) {
|
||||||
throw new Error(`Non-JSX element passed to: ctx.render()`);
|
throw new Error(`Non-JSX element passed to: ctx.render()`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const defs = this.#internal.layouts;
|
||||||
|
const appDef = 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
|
const headers = init.headers !== undefined
|
||||||
? init.headers instanceof Headers
|
? init.headers instanceof Headers
|
||||||
? init.headers
|
? init.headers
|
||||||
@@ -198,13 +250,21 @@ export class FreshReqContext<State>
|
|||||||
|
|
||||||
const html = tracer.startActiveSpan("render", (span) => {
|
const html = tracer.startActiveSpan("render", (span) => {
|
||||||
span.setAttribute("fresh.span_type", "render");
|
span.setAttribute("fresh.span_type", "render");
|
||||||
|
const state = new RenderState(
|
||||||
|
this,
|
||||||
|
this.#islandRegistry,
|
||||||
|
this.#buildCache,
|
||||||
|
partialId,
|
||||||
|
);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
setRenderState(state);
|
||||||
|
|
||||||
return preactRender(
|
return preactRender(
|
||||||
vnode,
|
vnode ?? h(Fragment, null),
|
||||||
this,
|
this,
|
||||||
this.#islandRegistry,
|
state,
|
||||||
this.#buildCache,
|
this.#buildCache,
|
||||||
partialId,
|
|
||||||
headers,
|
headers,
|
||||||
);
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -218,6 +278,9 @@ export class FreshReqContext<State>
|
|||||||
}
|
}
|
||||||
throw err;
|
throw err;
|
||||||
} finally {
|
} finally {
|
||||||
|
state.clear();
|
||||||
|
setRenderState(null);
|
||||||
|
|
||||||
span.end();
|
span.end();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -225,7 +288,7 @@ export class FreshReqContext<State>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Object.defineProperties(FreshReqContext.prototype, {
|
Object.defineProperties(Context.prototype, {
|
||||||
config: { enumerable: true },
|
config: { enumerable: true },
|
||||||
url: { enumerable: true },
|
url: { enumerable: true },
|
||||||
req: { enumerable: true },
|
req: { enumerable: true },
|
||||||
@@ -236,59 +299,3 @@ Object.defineProperties(FreshReqContext.prototype, {
|
|||||||
next: { enumerable: true },
|
next: { enumerable: true },
|
||||||
info: { enumerable: true },
|
info: { enumerable: true },
|
||||||
});
|
});
|
||||||
|
|
||||||
function preactRender<State, Data>(
|
|
||||||
vnode: VNode,
|
|
||||||
ctx: PageProps<Data, State>,
|
|
||||||
islandRegistry: ServerIslandRegistry,
|
|
||||||
buildCache: BuildCache,
|
|
||||||
partialId: string,
|
|
||||||
headers: Headers,
|
|
||||||
) {
|
|
||||||
const state = new RenderState(ctx, islandRegistry, buildCache, partialId);
|
|
||||||
setRenderState(state);
|
|
||||||
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 = `${basePath}/_fresh/js/${BUILD_ID}/fresh-runtime.js`;
|
|
||||||
let link = `<${encodeURI(runtimeUrl)}>; rel="modulepreload"; as="script"`;
|
|
||||||
state.islands.forEach((island) => {
|
|
||||||
const chunk = buildCache.getIslandChunkName(island.name);
|
|
||||||
if (chunk !== null) {
|
|
||||||
link += `, <${
|
|
||||||
encodeURI(`${basePath}${chunk}`)
|
|
||||||
}>; rel="modulepreload"; as="script"`;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
if (link !== "") {
|
|
||||||
headers.append("Link", link);
|
|
||||||
}
|
|
||||||
|
|
||||||
state.clear();
|
|
||||||
setRenderState(null);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export type PageProps<Data = unknown, T = unknown> =
|
|
||||||
& Omit<FreshContext<T>, "next" | "render" | "redirect">
|
|
||||||
& { data: Data; Component: FunctionComponent };
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { expect } from "@std/expect";
|
import { expect } from "@std/expect";
|
||||||
import { FreshReqContext } from "./context.ts";
|
import { Context } from "./context.ts";
|
||||||
import { App } from "fresh";
|
import { App } from "fresh";
|
||||||
import { asset } from "fresh/runtime";
|
import { asset } from "fresh/runtime";
|
||||||
import { FakeServer } from "./test_utils.ts";
|
import { FakeServer } from "./test_utils.ts";
|
||||||
@@ -7,23 +7,23 @@ import { BUILD_ID } from "./runtime/build_id.ts";
|
|||||||
import { parseHtml } from "../tests/test_utils.tsx";
|
import { parseHtml } from "../tests/test_utils.tsx";
|
||||||
|
|
||||||
Deno.test("FreshReqContext.prototype.redirect", () => {
|
Deno.test("FreshReqContext.prototype.redirect", () => {
|
||||||
let res = FreshReqContext.prototype.redirect("/");
|
let res = Context.prototype.redirect("/");
|
||||||
expect(res.status).toEqual(302);
|
expect(res.status).toEqual(302);
|
||||||
expect(res.headers.get("Location")).toEqual("/");
|
expect(res.headers.get("Location")).toEqual("/");
|
||||||
|
|
||||||
res = FreshReqContext.prototype.redirect("//evil.com");
|
res = Context.prototype.redirect("//evil.com");
|
||||||
expect(res.status).toEqual(302);
|
expect(res.status).toEqual(302);
|
||||||
expect(res.headers.get("Location")).toEqual("/evil.com");
|
expect(res.headers.get("Location")).toEqual("/evil.com");
|
||||||
|
|
||||||
res = FreshReqContext.prototype.redirect("//evil.com/foo//bar");
|
res = Context.prototype.redirect("//evil.com/foo//bar");
|
||||||
expect(res.status).toEqual(302);
|
expect(res.status).toEqual(302);
|
||||||
expect(res.headers.get("Location")).toEqual("/evil.com/foo/bar");
|
expect(res.headers.get("Location")).toEqual("/evil.com/foo/bar");
|
||||||
|
|
||||||
res = FreshReqContext.prototype.redirect("https://deno.com");
|
res = Context.prototype.redirect("https://deno.com");
|
||||||
expect(res.status).toEqual(302);
|
expect(res.status).toEqual(302);
|
||||||
expect(res.headers.get("Location")).toEqual("https://deno.com");
|
expect(res.headers.get("Location")).toEqual("https://deno.com");
|
||||||
|
|
||||||
res = FreshReqContext.prototype.redirect("/", 307);
|
res = Context.prototype.redirect("/", 307);
|
||||||
expect(res.status).toEqual(307);
|
expect(res.status).toEqual(307);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
import type { AnyComponent } from "preact";
|
import type { AnyComponent } from "preact";
|
||||||
import type { HandlerByMethod, HandlerFn, RouteHandler } from "./handlers.ts";
|
import type { HandlerByMethod, HandlerFn, RouteHandler } from "./handlers.ts";
|
||||||
import type { Middleware } from "./middlewares/mod.ts";
|
import type { Middleware } from "./middlewares/mod.ts";
|
||||||
import type { PageProps } from "./context.ts";
|
import type { PageProps } from "./render.ts";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A set of define functions that enable better type inference and code
|
* A set of define functions that enable better type inference and code
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ export class Builder implements FreshBuilder {
|
|||||||
#transformer = new FreshFileTransformer(fsAdapter);
|
#transformer = new FreshFileTransformer(fsAdapter);
|
||||||
#addedInternalTransforms = false;
|
#addedInternalTransforms = false;
|
||||||
#options: { target: string | string[] };
|
#options: { target: string | string[] };
|
||||||
|
#chunksReady = Promise.withResolvers<void>();
|
||||||
|
|
||||||
constructor(options: BuildOptions = {}) {
|
constructor(options: BuildOptions = {}) {
|
||||||
this.#options = {
|
this.#options = {
|
||||||
@@ -70,6 +71,11 @@ export class Builder implements FreshBuilder {
|
|||||||
.use(liveReload())
|
.use(liveReload())
|
||||||
.use(devErrorOverlay())
|
.use(devErrorOverlay())
|
||||||
.use(automaticWorkspaceFolders(app.config.root))
|
.use(automaticWorkspaceFolders(app.config.root))
|
||||||
|
// Wait for island chunks to be ready before attempting to serve them
|
||||||
|
.use(async (ctx) => {
|
||||||
|
await this.#chunksReady.promise;
|
||||||
|
return await ctx.next();
|
||||||
|
})
|
||||||
.mountApp("/*", app);
|
.mountApp("/*", app);
|
||||||
|
|
||||||
devApp.config.mode = "development";
|
devApp.config.mode = "development";
|
||||||
@@ -205,6 +211,8 @@ export class Builder implements FreshBuilder {
|
|||||||
|
|
||||||
await buildCache.flush();
|
await buildCache.flush();
|
||||||
|
|
||||||
|
this.#chunksReady.resolve();
|
||||||
|
|
||||||
if (!dev) {
|
if (!dev) {
|
||||||
// deno-lint-ignore no-console
|
// deno-lint-ignore no-console
|
||||||
console.log(
|
console.log(
|
||||||
|
|||||||
@@ -30,16 +30,10 @@ Deno.test("CORS - Preflight default", async () => {
|
|||||||
const res = await handler(req);
|
const res = await handler(req);
|
||||||
|
|
||||||
expect(res.status).toBe(204);
|
expect(res.status).toBe(204);
|
||||||
expect(res.statusText).toBe("No Content");
|
expect(res.headers.get("Access-Control-Allow-Methods")?.split(",")[0])
|
||||||
expect(res.headers.get("Access-Control-Allow-Methods")?.split(",")[0]).toBe(
|
.toBe("GET");
|
||||||
"GET",
|
expect(res.headers.get("Access-Control-Allow-Headers")?.split(","))
|
||||||
);
|
.toEqual(["X-PINGOTHER", "Content-Type"]);
|
||||||
expect(res.headers.get("Access-Control-Allow-Headers")?.split(",")).toEqual(
|
|
||||||
[
|
|
||||||
"X-PINGOTHER",
|
|
||||||
"Content-Type",
|
|
||||||
],
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
Deno.test("CORS - Preflight with options", async () => {
|
Deno.test("CORS - Preflight with options", async () => {
|
||||||
|
|||||||
+23
-21
@@ -1,4 +1,4 @@
|
|||||||
import type { FreshContext, FreshReqContext } from "../context.ts";
|
import { type Context, getInternals } from "../context.ts";
|
||||||
import type { App as _App } from "../app.ts";
|
import type { App as _App } from "../app.ts";
|
||||||
import type { Define as _Define } from "../define.ts";
|
import type { Define as _Define } from "../define.ts";
|
||||||
|
|
||||||
@@ -6,14 +6,14 @@ import type { Define as _Define } from "../define.ts";
|
|||||||
* A middleware function is the basic building block of Fresh. It allows you
|
* 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
|
* 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
|
* routes, serve files, create APIs and much more. Middlewares can be chained by
|
||||||
* calling {@linkcode FreshContext.next|ctx.next()} inside of the function.
|
* calling {@linkcode Context.next|ctx.next()} inside of the function.
|
||||||
*
|
*
|
||||||
* Middlewares can be synchronous or asynchronous. If a middleware returns a
|
* Middlewares can be synchronous or asynchronous. If a middleware returns a
|
||||||
* {@linkcode Response} object, the response will be sent back to the client. If
|
* {@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
|
* a middleware returns a `Promise<Response>`, Fresh will wait for the promise
|
||||||
* to resolve before sending the response.
|
* to resolve before sending the response.
|
||||||
*
|
*
|
||||||
* A {@linkcode FreshContext} object is passed to the middleware function. This
|
* A {@linkcode Context} object is passed to the middleware function. This
|
||||||
* object contains the original request object, as well as any state related to
|
* 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 current request. The context object also contains methods to redirect
|
||||||
* the client to another URL, or to call the next middleware in the chain.
|
* the client to another URL, or to call the next middleware in the chain.
|
||||||
@@ -72,7 +72,7 @@ import type { Define as _Define } from "../define.ts";
|
|||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
export type MiddlewareFn<State> = (
|
export type MiddlewareFn<State> = (
|
||||||
ctx: FreshContext<State>,
|
ctx: Context<State>,
|
||||||
) => Response | Promise<Response>;
|
) => Response | Promise<Response>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -82,27 +82,29 @@ export type MiddlewareFn<State> = (
|
|||||||
export type Middleware<State> = MiddlewareFn<State> | MiddlewareFn<State>[];
|
export type Middleware<State> = MiddlewareFn<State> | MiddlewareFn<State>[];
|
||||||
|
|
||||||
export function runMiddlewares<State>(
|
export function runMiddlewares<State>(
|
||||||
middlewares: MiddlewareFn<State>[][],
|
middlewares: MiddlewareFn<State>[],
|
||||||
ctx: FreshReqContext<State>,
|
ctx: Context<State>,
|
||||||
): Promise<Response> {
|
): Promise<Response> {
|
||||||
let fn = ctx.next;
|
let fn = ctx.next;
|
||||||
let i = middlewares.length;
|
let i = middlewares.length;
|
||||||
while (i--) {
|
while (i--) {
|
||||||
const stack = middlewares[i];
|
const local = fn;
|
||||||
let j = stack.length;
|
const next = middlewares[i];
|
||||||
while (j--) {
|
fn = async () => {
|
||||||
const local = fn;
|
const internals = getInternals(ctx);
|
||||||
const next = stack[j];
|
const { app: prevApp, layouts: prevLayouts } = internals;
|
||||||
fn = async () => {
|
|
||||||
ctx.next = local;
|
ctx.next = local;
|
||||||
try {
|
try {
|
||||||
return await next(ctx);
|
return await next(ctx);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
ctx.error = err;
|
ctx.error = err;
|
||||||
throw err;
|
throw err;
|
||||||
}
|
} finally {
|
||||||
};
|
internals.app = prevApp;
|
||||||
}
|
internals.layouts = prevLayouts;
|
||||||
|
}
|
||||||
|
};
|
||||||
}
|
}
|
||||||
return fn();
|
return fn();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ Deno.test("runMiddleware", async () => {
|
|||||||
];
|
];
|
||||||
|
|
||||||
const server = serveMiddleware<{ text: string }>((ctx) =>
|
const server = serveMiddleware<{ text: string }>((ctx) =>
|
||||||
runMiddlewares([middlewares], ctx)
|
runMiddlewares(middlewares, ctx)
|
||||||
);
|
);
|
||||||
|
|
||||||
const res = await server.get("/");
|
const res = await server.get("/");
|
||||||
@@ -43,7 +43,7 @@ Deno.test("runMiddleware - middlewares should only be called once", async () =>
|
|||||||
|
|
||||||
const server = serveMiddleware<{ count: number }>((ctx) =>
|
const server = serveMiddleware<{ count: number }>((ctx) =>
|
||||||
runMiddlewares(
|
runMiddlewares(
|
||||||
[[A, (ctx) => new Response(String(ctx.state.count))]],
|
[A, (ctx) => new Response(String(ctx.state.count))],
|
||||||
ctx,
|
ctx,
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
@@ -75,8 +75,11 @@ Deno.test("runMiddleware - runs multiple stacks", async () => {
|
|||||||
ctx.state.text = "";
|
ctx.state.text = "";
|
||||||
return runMiddlewares(
|
return runMiddlewares(
|
||||||
[
|
[
|
||||||
[A, B],
|
A,
|
||||||
[C, D, (ctx) => new Response(String(ctx.state.text))],
|
B,
|
||||||
|
C,
|
||||||
|
D,
|
||||||
|
(ctx) => new Response(String(ctx.state.text)),
|
||||||
],
|
],
|
||||||
ctx,
|
ctx,
|
||||||
);
|
);
|
||||||
@@ -122,7 +125,7 @@ Deno.test("runMiddleware - throws errors", async () => {
|
|||||||
];
|
];
|
||||||
|
|
||||||
const server = serveMiddleware<{ text: string }>((ctx) =>
|
const server = serveMiddleware<{ text: string }>((ctx) =>
|
||||||
runMiddlewares([middlewares], ctx)
|
runMiddlewares(middlewares, ctx)
|
||||||
);
|
);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -3,8 +3,8 @@ import { contentType as getContentType } from "@std/media-types/content-type";
|
|||||||
import type { MiddlewareFn } from "./mod.ts";
|
import type { MiddlewareFn } from "./mod.ts";
|
||||||
import { ASSET_CACHE_BUST_KEY } from "../runtime/shared_internal.tsx";
|
import { ASSET_CACHE_BUST_KEY } from "../runtime/shared_internal.tsx";
|
||||||
import { BUILD_ID } from "../runtime/build_id.ts";
|
import { BUILD_ID } from "../runtime/build_id.ts";
|
||||||
|
import { tracer } from "../otel.ts";
|
||||||
import { getBuildCache } from "../context.ts";
|
import { getBuildCache } from "../context.ts";
|
||||||
import { trace, tracer } from "../otel.ts";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fresh middleware to enable file-system based routing.
|
* Fresh middleware to enable file-system based routing.
|
||||||
@@ -12,11 +12,20 @@ import { trace, tracer } from "../otel.ts";
|
|||||||
* // Enable Fresh static file serving
|
* // Enable Fresh static file serving
|
||||||
* app.use(staticFiles());
|
* app.use(staticFiles());
|
||||||
* ```
|
* ```
|
||||||
|
* @deprecated This is not needed anymore. Remove this middleware.
|
||||||
*/
|
*/
|
||||||
export function staticFiles<T>(): MiddlewareFn<T> {
|
export function staticFiles<T>(): MiddlewareFn<T> {
|
||||||
return async function freshStaticFiles(ctx) {
|
return async function freshStaticFiles(ctx) {
|
||||||
|
return await ctx.next();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function serveInternalStaticFiles<T>(): MiddlewareFn<T> {
|
||||||
|
return async function freshServeStaticFiles(ctx) {
|
||||||
const { req, url, config } = ctx;
|
const { req, url, config } = ctx;
|
||||||
|
|
||||||
const buildCache = getBuildCache(ctx);
|
const buildCache = getBuildCache(ctx);
|
||||||
|
if (buildCache === null) return await ctx.next();
|
||||||
|
|
||||||
let pathname = decodeURIComponent(url.pathname);
|
let pathname = decodeURIComponent(url.pathname);
|
||||||
if (config.basePath) {
|
if (config.basePath) {
|
||||||
@@ -33,7 +42,7 @@ export function staticFiles<T>(): MiddlewareFn<T> {
|
|||||||
if (pathname === "/favicon.ico") {
|
if (pathname === "/favicon.ico") {
|
||||||
return new Response(null, { status: 404 });
|
return new Response(null, { status: 404 });
|
||||||
}
|
}
|
||||||
return ctx.next();
|
return await ctx.next();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (req.method !== "GET" && req.method !== "HEAD") {
|
if (req.method !== "GET" && req.method !== "HEAD") {
|
||||||
@@ -41,12 +50,6 @@ export function staticFiles<T>(): MiddlewareFn<T> {
|
|||||||
return new Response("Method Not Allowed", { status: 405 });
|
return new Response("Method Not Allowed", { status: 405 });
|
||||||
}
|
}
|
||||||
|
|
||||||
const parentSpan = trace.getActiveSpan();
|
|
||||||
if (parentSpan) {
|
|
||||||
parentSpan.updateName(`${req.method} /*`);
|
|
||||||
parentSpan.setAttribute("http.route", "/*");
|
|
||||||
}
|
|
||||||
|
|
||||||
const span = tracer.startSpan("static file", {
|
const span = tracer.startSpan("static file", {
|
||||||
attributes: { "fresh.span_type": "static_file" },
|
attributes: { "fresh.span_type": "static_file" },
|
||||||
startTime,
|
startTime,
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { staticFiles } from "./static_files.ts";
|
import { serveInternalStaticFiles } from "./static_files.ts";
|
||||||
import { serveMiddleware } from "../test_utils.ts";
|
import { serveMiddleware } from "../test_utils.ts";
|
||||||
import type { BuildCache, StaticFile } from "../build_cache.ts";
|
import type { BuildCache, StaticFile } from "../build_cache.ts";
|
||||||
import { expect } from "@std/expect";
|
import { expect } from "@std/expect";
|
||||||
@@ -39,7 +39,7 @@ Deno.test("static files - 200", async () => {
|
|||||||
"foo.css": { content: "body {}", hash: null },
|
"foo.css": { content: "body {}", hash: null },
|
||||||
});
|
});
|
||||||
const server = serveMiddleware(
|
const server = serveMiddleware(
|
||||||
staticFiles(),
|
serveInternalStaticFiles(),
|
||||||
{ buildCache },
|
{ buildCache },
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -59,7 +59,7 @@ Deno.test("static files - HEAD 200", async () => {
|
|||||||
"foo.css": { content: "body {}", hash: null },
|
"foo.css": { content: "body {}", hash: null },
|
||||||
});
|
});
|
||||||
const server = serveMiddleware(
|
const server = serveMiddleware(
|
||||||
staticFiles(),
|
serveInternalStaticFiles(),
|
||||||
{ buildCache },
|
{ buildCache },
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -76,7 +76,7 @@ Deno.test("static files - etag", async () => {
|
|||||||
"foo.css": { content: "body {}", hash: "123" },
|
"foo.css": { content: "body {}", hash: "123" },
|
||||||
});
|
});
|
||||||
const server = serveMiddleware(
|
const server = serveMiddleware(
|
||||||
staticFiles(),
|
serveInternalStaticFiles(),
|
||||||
{ buildCache },
|
{ buildCache },
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -101,7 +101,7 @@ Deno.test("static files - etag", async () => {
|
|||||||
Deno.test("static files - 404 on missing favicon.ico", async () => {
|
Deno.test("static files - 404 on missing favicon.ico", async () => {
|
||||||
const buildCache = new MockBuildCache({});
|
const buildCache = new MockBuildCache({});
|
||||||
const server = serveMiddleware(
|
const server = serveMiddleware(
|
||||||
staticFiles(),
|
serveInternalStaticFiles(),
|
||||||
{ buildCache },
|
{ buildCache },
|
||||||
);
|
);
|
||||||
const res = await server.get("favicon.ico");
|
const res = await server.get("favicon.ico");
|
||||||
@@ -114,7 +114,7 @@ Deno.test("static files - 405 on wrong HTTP method", async () => {
|
|||||||
"foo.css": { content: "body {}", hash: null },
|
"foo.css": { content: "body {}", hash: null },
|
||||||
});
|
});
|
||||||
const server = serveMiddleware(
|
const server = serveMiddleware(
|
||||||
staticFiles(),
|
serveInternalStaticFiles(),
|
||||||
{ buildCache },
|
{ buildCache },
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -131,7 +131,7 @@ Deno.test("static files - disables caching in development", async () => {
|
|||||||
"foo.css": { content: "body {}", hash: null },
|
"foo.css": { content: "body {}", hash: null },
|
||||||
});
|
});
|
||||||
const server = serveMiddleware(
|
const server = serveMiddleware(
|
||||||
staticFiles(),
|
serveInternalStaticFiles(),
|
||||||
{
|
{
|
||||||
buildCache,
|
buildCache,
|
||||||
config: {
|
config: {
|
||||||
@@ -159,7 +159,7 @@ Deno.test("static files - enables caching in production", async () => {
|
|||||||
"foo.css": { content: "body {}", hash: null },
|
"foo.css": { content: "body {}", hash: null },
|
||||||
});
|
});
|
||||||
const server = serveMiddleware(
|
const server = serveMiddleware(
|
||||||
staticFiles(),
|
serveInternalStaticFiles(),
|
||||||
{
|
{
|
||||||
buildCache,
|
buildCache,
|
||||||
config: {
|
config: {
|
||||||
@@ -189,7 +189,7 @@ Deno.test("static files - decoded pathname", async () => {
|
|||||||
"인천.avif": { content: "body {}", hash: null },
|
"인천.avif": { content: "body {}", hash: null },
|
||||||
});
|
});
|
||||||
const server = serveMiddleware(
|
const server = serveMiddleware(
|
||||||
staticFiles(),
|
serveInternalStaticFiles(),
|
||||||
{ buildCache },
|
{ buildCache },
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
+2
-1
@@ -14,7 +14,8 @@ export type { Middleware, MiddlewareFn } from "./middlewares/mod.ts";
|
|||||||
export { staticFiles } from "./middlewares/static_files.ts";
|
export { staticFiles } from "./middlewares/static_files.ts";
|
||||||
export { cors, type CORSOptions } from "./middlewares/cors.ts";
|
export { cors, type CORSOptions } from "./middlewares/cors.ts";
|
||||||
export type { FreshConfig, ResolvedFreshConfig } from "./config.ts";
|
export type { FreshConfig, ResolvedFreshConfig } from "./config.ts";
|
||||||
export type { FreshContext, Island, PageProps } from "./context.ts";
|
export type { Context, FreshContext, Island } from "./context.ts";
|
||||||
export { createDefine, type Define } from "./define.ts";
|
export { createDefine, type Define } from "./define.ts";
|
||||||
export type { Method } from "./router.ts";
|
export type { Method } from "./router.ts";
|
||||||
export { HttpError } from "./error.ts";
|
export { HttpError } from "./error.ts";
|
||||||
|
export type { PageProps } from "./render.ts";
|
||||||
|
|||||||
+12
-1
@@ -1,7 +1,18 @@
|
|||||||
import { trace } from "@opentelemetry/api";
|
import { type Span, SpanStatusCode, trace } from "@opentelemetry/api";
|
||||||
import denoJson from "../deno.json" with { type: "json" };
|
import denoJson from "../deno.json" with { type: "json" };
|
||||||
|
|
||||||
export const CURRENT_FRESH_VERSION = denoJson.version;
|
export const CURRENT_FRESH_VERSION = denoJson.version;
|
||||||
|
|
||||||
export const tracer = trace.getTracer("fresh", CURRENT_FRESH_VERSION);
|
export const tracer = trace.getTracer("fresh", CURRENT_FRESH_VERSION);
|
||||||
export { trace };
|
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),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+80
-209
@@ -5,16 +5,12 @@ import * as path from "@std/path";
|
|||||||
import type { RouteConfig } from "../../types.ts";
|
import type { RouteConfig } from "../../types.ts";
|
||||||
import type { RouteHandler } from "../../handlers.ts";
|
import type { RouteHandler } from "../../handlers.ts";
|
||||||
import type { MiddlewareFn } from "../../middlewares/mod.ts";
|
import type { MiddlewareFn } from "../../middlewares/mod.ts";
|
||||||
import {
|
import type { AsyncAnyComponent } from "../../render.ts";
|
||||||
type AsyncAnyComponent,
|
import { pathToPattern } from "../../router.ts";
|
||||||
renderMiddleware,
|
|
||||||
} from "./render_middleware.ts";
|
|
||||||
import { type Method, pathToPattern } from "../../router.ts";
|
|
||||||
import { type HandlerFn, isHandlerByMethod } from "../../handlers.ts";
|
import { type HandlerFn, isHandlerByMethod } from "../../handlers.ts";
|
||||||
import { type FsAdapter, fsAdapter } from "../../fs.ts";
|
import { type FsAdapter, fsAdapter } from "../../fs.ts";
|
||||||
import { HttpError } from "../../error.ts";
|
|
||||||
import { parseRootPath } from "../../config.ts";
|
import { parseRootPath } from "../../config.ts";
|
||||||
import type { FreshReqContext, PageProps } from "../../context.ts";
|
import type { PageProps } from "../../render.ts";
|
||||||
|
|
||||||
const TEST_FILE_PATTERN = /[._]test\.(?:[tj]sx?|[mc][tj]s)$/;
|
const TEST_FILE_PATTERN = /[._]test\.(?:[tj]sx?|[mc][tj]s)$/;
|
||||||
const GROUP_REG = /(^|[/\\\\])\((_[^/\\\\]+)\)[/\\\\]/;
|
const GROUP_REG = /(^|[/\\\\])\((_[^/\\\\]+)\)[/\\\\]/;
|
||||||
@@ -25,7 +21,7 @@ interface InternalRoute<State> {
|
|||||||
filePath: string;
|
filePath: string;
|
||||||
config: RouteConfig | null;
|
config: RouteConfig | null;
|
||||||
handlers:
|
handlers:
|
||||||
| RouteHandler<unknown, State>[]
|
| MiddlewareFn<State>[]
|
||||||
| RouteHandler<unknown, State>
|
| RouteHandler<unknown, State>
|
||||||
| null;
|
| null;
|
||||||
component: AnyComponent<PageProps<unknown, State>> | null;
|
component: AnyComponent<PageProps<unknown, State>> | null;
|
||||||
@@ -165,233 +161,108 @@ export async function fsRoutes<State>(
|
|||||||
);
|
);
|
||||||
|
|
||||||
routeModules.sort((a, b) => sortRoutePaths(a.path, b.path));
|
routeModules.sort((a, b) => sortRoutePaths(a.path, b.path));
|
||||||
|
const errorPaths = new Set<string>();
|
||||||
const stack: InternalRoute<State>[] = [];
|
|
||||||
let hasApp = false;
|
|
||||||
|
|
||||||
const specialPaths = new Set<string>();
|
|
||||||
|
|
||||||
for (let i = 0; i < routeModules.length; i++) {
|
for (let i = 0; i < routeModules.length; i++) {
|
||||||
const routeMod = routeModules[i];
|
const routeMod = routeModules[i];
|
||||||
const normalized = routeMod.path;
|
const normalized = routeMod.path;
|
||||||
|
|
||||||
let j = stack.length - 1;
|
|
||||||
while (
|
|
||||||
j >= 0 && stack[j].base !== "" &&
|
|
||||||
!routeMod.path.startsWith(stack[j].base + "/")
|
|
||||||
) {
|
|
||||||
j--;
|
|
||||||
stack.pop();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (normalized.endsWith("/_app")) {
|
if (normalized.endsWith("/_app")) {
|
||||||
hasApp = true;
|
const component = routeMod.component;
|
||||||
stack.push(routeMod);
|
if (component !== null) {
|
||||||
|
app.appWrapper(component);
|
||||||
|
}
|
||||||
continue;
|
continue;
|
||||||
} else if (normalized.endsWith("/_middleware")) {
|
} else if (normalized.endsWith("/_middleware")) {
|
||||||
stack.push(routeMod);
|
if (routeMod.handlers === null) continue;
|
||||||
|
|
||||||
|
if (isHandlerByMethod(routeMod.handlers)) {
|
||||||
|
warnInvalidRoute(
|
||||||
|
"Middleware does not support object handlers with GET, POST, etc.",
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const pattern = pathToPattern(
|
||||||
|
normalized.slice(1, -"/_middleware".length),
|
||||||
|
{ keepGroups: true },
|
||||||
|
);
|
||||||
|
|
||||||
|
const handlers = (Array.isArray(routeMod.handlers)
|
||||||
|
? routeMod.handlers
|
||||||
|
: [routeMod.handlers]) as MiddlewareFn<State>[];
|
||||||
|
|
||||||
|
app.use(pattern, ...handlers);
|
||||||
|
|
||||||
continue;
|
continue;
|
||||||
} else if (normalized.endsWith("/_layout")) {
|
} else if (normalized.endsWith("/_layout")) {
|
||||||
stack.push(routeMod);
|
if (routeMod.handlers !== null) {
|
||||||
|
warnInvalidRoute("Layout does not support handlers");
|
||||||
|
}
|
||||||
|
|
||||||
|
const pattern = pathToPattern(normalized.slice(1, -"/_layout".length), {
|
||||||
|
keepGroups: true,
|
||||||
|
});
|
||||||
|
const { component, config } = routeMod;
|
||||||
|
if (component !== null) {
|
||||||
|
app.layout(pattern, component, config ?? undefined);
|
||||||
|
}
|
||||||
continue;
|
continue;
|
||||||
} else if (normalized.endsWith("/_error")) {
|
} else if (normalized.endsWith("/_error")) {
|
||||||
stack.push(routeMod);
|
const pattern = pathToPattern(normalized.slice(1, -"/_error".length), {
|
||||||
|
keepGroups: true,
|
||||||
|
});
|
||||||
|
errorPaths.add(pattern);
|
||||||
|
app.onError(pattern, {
|
||||||
|
config: routeMod.config ?? undefined,
|
||||||
|
component: routeMod.component ?? undefined,
|
||||||
|
// deno-lint-ignore no-explicit-any
|
||||||
|
handler: routeMod.handlers as any ?? undefined,
|
||||||
|
});
|
||||||
continue;
|
continue;
|
||||||
} else if (normalized.endsWith("/_404")) {
|
} else if (normalized.endsWith("/_404")) {
|
||||||
stack.push(routeMod);
|
app.notFound({
|
||||||
|
config: routeMod.config ?? undefined,
|
||||||
|
component: routeMod.component ?? undefined,
|
||||||
|
// deno-lint-ignore no-explicit-any
|
||||||
|
handler: routeMod.handlers as any ?? undefined,
|
||||||
|
});
|
||||||
continue;
|
continue;
|
||||||
} else if (normalized.endsWith("/_500")) {
|
} else if (normalized.endsWith("/_500")) {
|
||||||
stack.push(routeMod);
|
const pattern = pathToPattern(normalized.slice(1, -"/_500".length), {
|
||||||
|
keepGroups: true,
|
||||||
|
});
|
||||||
|
if (errorPaths.has(pattern)) continue;
|
||||||
|
|
||||||
|
app.onError(pattern, {
|
||||||
|
config: routeMod.config ?? undefined,
|
||||||
|
component: routeMod.component ?? undefined,
|
||||||
|
// deno-lint-ignore no-explicit-any
|
||||||
|
handler: routeMod.handlers as any ?? undefined,
|
||||||
|
});
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Remove any elements not matching our parent path anymore
|
let pattern = pathToPattern(normalized.slice(1), { keepGroups: true });
|
||||||
const middlewares: MiddlewareFn<State>[] = [];
|
if (normalized.endsWith("/index")) {
|
||||||
let components: AnyComponent<PageProps<unknown, State>>[] = [];
|
if (!pattern.endsWith("/")) {
|
||||||
|
pattern += "/";
|
||||||
let skipApp = !!routeMod.config?.skipAppWrapper;
|
|
||||||
const skipLayouts = !!routeMod.config?.skipInheritedLayouts;
|
|
||||||
|
|
||||||
for (let k = 0; k < stack.length; k++) {
|
|
||||||
const mod = stack[k];
|
|
||||||
if (mod.path.endsWith("/_middleware")) {
|
|
||||||
if (Array.isArray(mod.handlers)) {
|
|
||||||
middlewares.push(...(mod.handlers as MiddlewareFn<State>[]));
|
|
||||||
} else if (typeof mod.handlers === "function") {
|
|
||||||
middlewares.push(mod.handlers as MiddlewareFn<State>);
|
|
||||||
} else if (isHandlerByMethod(mod.handlers)) {
|
|
||||||
warnInvalidRoute(
|
|
||||||
"Middleware does not support object handlers with GET, POST, etc.",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// _app template
|
|
||||||
if (skipApp && mod.path === "/_app") {
|
|
||||||
continue;
|
|
||||||
} else if (!skipApp && mod.config?.skipAppWrapper) {
|
|
||||||
skipApp = true;
|
|
||||||
if (hasApp) {
|
|
||||||
// _app component is always first
|
|
||||||
components.shift();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// _layouts
|
|
||||||
if (skipLayouts && mod.path.endsWith("/_layout")) {
|
|
||||||
continue;
|
|
||||||
} else if (mod.handlers !== null && mod.path.endsWith("/_layout")) {
|
|
||||||
warnInvalidRoute("Layout does not support handlers");
|
|
||||||
} else if (!skipLayouts && mod.config?.skipInheritedLayouts) {
|
|
||||||
const first = components.length > 0 ? components[0] : null;
|
|
||||||
components = [];
|
|
||||||
|
|
||||||
if (!skipApp && hasApp && first !== null) {
|
|
||||||
components.push(first);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mod.path.endsWith("/_error") || mod.path.endsWith("/_500")) {
|
|
||||||
const handlers = mod.handlers;
|
|
||||||
const handler = handlers === null ||
|
|
||||||
(isHandlerByMethod(handlers) && Object.keys(handlers).length === 0)
|
|
||||||
? undefined
|
|
||||||
: typeof handlers === "function"
|
|
||||||
? handlers
|
|
||||||
: ((ctx) => {
|
|
||||||
const { method } = ctx.req;
|
|
||||||
if (!Array.isArray(handlers)) {
|
|
||||||
const maybeFn = handlers[method as Method];
|
|
||||||
if (maybeFn !== undefined) {
|
|
||||||
return maybeFn(ctx);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return ctx.next();
|
|
||||||
}) as HandlerFn<unknown, State>;
|
|
||||||
const errorComponents = components.slice();
|
|
||||||
if (mod.component !== null) {
|
|
||||||
errorComponents.push(mod.component);
|
|
||||||
}
|
|
||||||
let parent = mod.path.slice(0, -"_error".length);
|
|
||||||
parent = parent + "*";
|
|
||||||
|
|
||||||
// Add error route as its own route
|
|
||||||
if (!specialPaths.has(mod.path)) {
|
|
||||||
specialPaths.add(mod.path);
|
|
||||||
app.all(
|
|
||||||
parent,
|
|
||||||
errorMiddleware(errorComponents, handler),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
middlewares.push(errorMiddleware(errorComponents, handler));
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mod.path.endsWith("/_404")) {
|
|
||||||
const handlers = mod.handlers;
|
|
||||||
const handler = handlers === null ||
|
|
||||||
(isHandlerByMethod(handlers) && Object.keys(handlers).length === 0)
|
|
||||||
? undefined
|
|
||||||
: typeof handlers === "function"
|
|
||||||
? handlers
|
|
||||||
: ((ctx) => {
|
|
||||||
const { method } = ctx.req;
|
|
||||||
if (!Array.isArray(handlers)) {
|
|
||||||
const maybeFn = handlers[method as Method];
|
|
||||||
if (maybeFn !== undefined) {
|
|
||||||
return maybeFn(ctx);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return ctx.next();
|
|
||||||
}) as HandlerFn<unknown, State>;
|
|
||||||
const notFoundComponents = components.slice();
|
|
||||||
if (mod.component !== null) {
|
|
||||||
notFoundComponents.push(mod.component);
|
|
||||||
}
|
|
||||||
app.use(notFoundMiddleware(notFoundComponents, handler));
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mod.component !== null) {
|
|
||||||
components.push(mod.component);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const handlers = routeMod.handlers;
|
const routePattern = pathToPattern(normalized.slice(1));
|
||||||
const routePath = routeMod.config?.routeOverride ??
|
|
||||||
pathToPattern(normalized.slice(1));
|
|
||||||
|
|
||||||
if (routeMod.component !== null) {
|
app.route(pattern, {
|
||||||
components.push(routeMod.component);
|
config: {
|
||||||
const missingGetHandler = isHandlerByMethod(handlers) &&
|
...routeMod.config ?? undefined,
|
||||||
!Object.keys(handlers).includes("GET");
|
routeOverride: routeMod.config?.routeOverride ?? routePattern,
|
||||||
if (missingGetHandler) {
|
},
|
||||||
const combined = middlewares.concat(
|
component: routeMod.component ?? undefined,
|
||||||
renderMiddleware(components, undefined),
|
// deno-lint-ignore no-explicit-any
|
||||||
);
|
handler: routeMod.handlers as any ?? undefined,
|
||||||
app.get(routePath, ...combined);
|
});
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
|
||||||
handlers === null ||
|
|
||||||
(isHandlerByMethod(handlers) && Object.keys(handlers).length === 0)
|
|
||||||
) {
|
|
||||||
const combined = middlewares.concat(
|
|
||||||
renderMiddleware(components, undefined),
|
|
||||||
);
|
|
||||||
app.get(routePath, ...combined);
|
|
||||||
} else if (isHandlerByMethod(handlers)) {
|
|
||||||
for (const method of Object.keys(handlers) as Method[]) {
|
|
||||||
const fn = handlers[method];
|
|
||||||
|
|
||||||
if (fn !== undefined) {
|
|
||||||
const combined = middlewares.concat(renderMiddleware(components, fn));
|
|
||||||
const lower = method.toLowerCase() as Lowercase<Method>;
|
|
||||||
app[lower](routePath, ...combined);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else if (typeof handlers === "function") {
|
|
||||||
const combined = middlewares.concat(
|
|
||||||
renderMiddleware(components, handlers),
|
|
||||||
);
|
|
||||||
app.all(routePath, ...combined);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function errorMiddleware<State>(
|
|
||||||
components: AnyComponent<PageProps<unknown, State>>[],
|
|
||||||
handler: HandlerFn<unknown, State> | undefined,
|
|
||||||
): MiddlewareFn<State> {
|
|
||||||
const mid = renderMiddleware<State>(components, handler);
|
|
||||||
return async function errorMiddleware(ctx) {
|
|
||||||
try {
|
|
||||||
return await ctx.next();
|
|
||||||
} catch (err) {
|
|
||||||
(ctx as FreshReqContext<State>).error = err;
|
|
||||||
return mid(ctx);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function notFoundMiddleware<State>(
|
|
||||||
components: AnyComponent<PageProps<unknown, State>>[],
|
|
||||||
handler: HandlerFn<unknown, State> | undefined,
|
|
||||||
): MiddlewareFn<State> {
|
|
||||||
const mid = renderMiddleware<State>(components, handler);
|
|
||||||
return async function notFoundMiddleware(ctx) {
|
|
||||||
try {
|
|
||||||
return await ctx.next();
|
|
||||||
} catch (err) {
|
|
||||||
if (err instanceof HttpError && err.status === 404) {
|
|
||||||
return mid(ctx);
|
|
||||||
}
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function warnInvalidRoute(message: string) {
|
function warnInvalidRoute(message: string) {
|
||||||
// deno-lint-ignore no-console
|
// deno-lint-ignore no-console
|
||||||
console.warn(
|
console.warn(
|
||||||
|
|||||||
@@ -13,7 +13,8 @@ import { stub } from "@std/testing/mock";
|
|||||||
import { type HandlerByMethod, type HandlerFn, page } from "../../handlers.ts";
|
import { type HandlerByMethod, type HandlerFn, page } from "../../handlers.ts";
|
||||||
import type { Method } from "../../router.ts";
|
import type { Method } from "../../router.ts";
|
||||||
import { parseHtml } from "../../../tests/test_utils.tsx";
|
import { parseHtml } from "../../../tests/test_utils.tsx";
|
||||||
import type { FreshContext } from "fresh";
|
import type { FreshContext } from "../../context.ts";
|
||||||
|
import { HttpError } from "../../error.ts";
|
||||||
|
|
||||||
async function createServer<T>(
|
async function createServer<T>(
|
||||||
files: Record<string, string | Uint8Array | FreshFsItem<T>>,
|
files: Record<string, string | Uint8Array | FreshFsItem<T>>,
|
||||||
@@ -193,13 +194,13 @@ Deno.test("fsRoutes - middleware", async () => {
|
|||||||
Deno.test("fsRoutes - nested middlewares", async () => {
|
Deno.test("fsRoutes - nested middlewares", async () => {
|
||||||
const server = await createServer<{ text: string }>({
|
const server = await createServer<{ text: string }>({
|
||||||
"routes/_middleware.ts": {
|
"routes/_middleware.ts": {
|
||||||
handler: (ctx) => {
|
handler: function A(ctx) {
|
||||||
ctx.state.text = "A";
|
ctx.state.text = "A";
|
||||||
return ctx.next();
|
return ctx.next();
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"routes/foo/_middleware.ts": {
|
"routes/foo/_middleware.ts": {
|
||||||
handler: (ctx) => {
|
handler: function B(ctx) {
|
||||||
ctx.state.text += "B";
|
ctx.state.text += "B";
|
||||||
return ctx.next();
|
return ctx.next();
|
||||||
},
|
},
|
||||||
@@ -332,18 +333,22 @@ Deno.test("fsRoutes - nested _layout", async () => {
|
|||||||
default: () => <>foo</>,
|
default: () => <>foo</>,
|
||||||
},
|
},
|
||||||
"routes/foo/_layout.tsx": {
|
"routes/foo/_layout.tsx": {
|
||||||
default: (ctx) => (
|
default: function fooBar(ctx) {
|
||||||
<>
|
return (
|
||||||
layout_foo_bar/<ctx.Component />
|
<>
|
||||||
</>
|
layout_foo_bar/<ctx.Component />
|
||||||
),
|
</>
|
||||||
|
);
|
||||||
|
},
|
||||||
},
|
},
|
||||||
"routes/_layout.tsx": {
|
"routes/_layout.tsx": {
|
||||||
default: (ctx) => (
|
default: function rootLayout(ctx) {
|
||||||
<>
|
return (
|
||||||
layout/<ctx.Component />
|
<>
|
||||||
</>
|
layout/<ctx.Component />
|
||||||
),
|
</>
|
||||||
|
);
|
||||||
|
},
|
||||||
},
|
},
|
||||||
"routes/_app.tsx": {
|
"routes/_app.tsx": {
|
||||||
default: (ctx) => (
|
default: (ctx) => (
|
||||||
@@ -806,7 +811,7 @@ Deno.test("fsRoutes - _error render component", async () => {
|
|||||||
},
|
},
|
||||||
"routes/foo/index.tsx": {
|
"routes/foo/index.tsx": {
|
||||||
handlers: () => {
|
handlers: () => {
|
||||||
throw new Error("ok");
|
throw new Error("failing");
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -816,7 +821,8 @@ Deno.test("fsRoutes - _error render component", async () => {
|
|||||||
expect(doc.body.firstChild?.textContent).toEqual("ok");
|
expect(doc.body.firstChild?.textContent).toEqual("ok");
|
||||||
});
|
});
|
||||||
|
|
||||||
Deno.test("fsRoutes - _error render on 404", async () => {
|
// 404 pages go to the root error page if available
|
||||||
|
Deno.test.ignore("fsRoutes - _error render on 404", async () => {
|
||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
let error: any = null;
|
let error: any = null;
|
||||||
const server = await createServer({
|
const server = await createServer({
|
||||||
@@ -828,7 +834,7 @@ Deno.test("fsRoutes - _error render on 404", async () => {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
"routes/foo/_error.tsx": {
|
"routes/foo/_error.tsx": {
|
||||||
default: (ctx) => {
|
default: function foo2(ctx) {
|
||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
error = ctx.error as any;
|
error = ctx.error as any;
|
||||||
return <p>ok foo</p>;
|
return <p>ok foo</p>;
|
||||||
@@ -1110,34 +1116,23 @@ Deno.test(
|
|||||||
"fsRoutes - returns response code from error route",
|
"fsRoutes - returns response code from error route",
|
||||||
async () => {
|
async () => {
|
||||||
const server = await createServer<{ text: string }>({
|
const server = await createServer<{ text: string }>({
|
||||||
"routes/_app.tsx": {
|
|
||||||
default: (ctx) => {
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
_app/<ctx.Component />
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
},
|
|
||||||
},
|
|
||||||
"routes/_error.tsx": {
|
"routes/_error.tsx": {
|
||||||
default: () => <div>fail</div>,
|
default: () => <div>fail</div>,
|
||||||
},
|
},
|
||||||
"routes/index.tsx": {
|
"routes/fail.tsx": {
|
||||||
default: () => <div>index</div>,
|
|
||||||
},
|
|
||||||
"routes/bar.tsx": {
|
|
||||||
default: () => <div>index</div>,
|
|
||||||
},
|
|
||||||
"routes/foo/index.tsx": {
|
|
||||||
default: () => <div>foo/index</div>,
|
|
||||||
},
|
|
||||||
"routes/foo/_error.tsx": {
|
|
||||||
default: () => {
|
default: () => {
|
||||||
throw new Error("fail");
|
throw new Error("fail");
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"routes/foo/bar.tsx": {
|
"routes/foo/_error.tsx": {
|
||||||
default: () => <div>foo/index</div>,
|
default: () => {
|
||||||
|
throw new HttpError(501);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"routes/foo/fail.tsx": {
|
||||||
|
default: () => {
|
||||||
|
throw new Error("fail");
|
||||||
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -1145,9 +1140,13 @@ Deno.test(
|
|||||||
await res.body?.cancel();
|
await res.body?.cancel();
|
||||||
expect(res.status).toEqual(404);
|
expect(res.status).toEqual(404);
|
||||||
|
|
||||||
res = await server.get("/foo/asdf");
|
res = await server.get("/fail");
|
||||||
await res.body?.cancel();
|
await res.body?.cancel();
|
||||||
expect(res.status).toEqual(500);
|
expect(res.status).toEqual(500);
|
||||||
|
|
||||||
|
res = await server.get("/foo/fail");
|
||||||
|
await res.body?.cancel();
|
||||||
|
expect(res.status).toEqual(501);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -1,139 +0,0 @@
|
|||||||
import { type AnyComponent, h, type RenderableProps, type VNode } from "preact";
|
|
||||||
import type { MiddlewareFn } from "../../middlewares/mod.ts";
|
|
||||||
import type { HandlerFn, PageResponse } from "../../handlers.ts";
|
|
||||||
import type { FreshReqContext, PageProps } from "../../context.ts";
|
|
||||||
import { HttpError } from "../../error.ts";
|
|
||||||
import { tracer } from "../../otel.ts";
|
|
||||||
import { SpanStatusCode } from "@opentelemetry/api";
|
|
||||||
|
|
||||||
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 function renderMiddleware<State>(
|
|
||||||
components: Array<
|
|
||||||
| AnyComponent<PageProps<unknown, State>>
|
|
||||||
| AsyncAnyComponent<PageProps<unknown, State>>
|
|
||||||
>,
|
|
||||||
handler: HandlerFn<unknown, State> | undefined,
|
|
||||||
init?: ResponseInit | undefined,
|
|
||||||
): MiddlewareFn<State> {
|
|
||||||
return async (ctx) => {
|
|
||||||
let result: PageResponse<unknown> | undefined;
|
|
||||||
if (handler !== undefined) {
|
|
||||||
const res = await tracer.startActiveSpan("handler", {
|
|
||||||
attributes: { "fresh.span_type": "fs_routes/handler" },
|
|
||||||
}, async (span) => {
|
|
||||||
try {
|
|
||||||
const res = await handler(ctx);
|
|
||||||
span.setAttribute(
|
|
||||||
"fresh.handler_response",
|
|
||||||
res instanceof Response ? "http" : "data",
|
|
||||||
);
|
|
||||||
return res;
|
|
||||||
} catch (err) {
|
|
||||||
if (err instanceof Error) {
|
|
||||||
span.recordException(err);
|
|
||||||
} else {
|
|
||||||
span.setStatus({
|
|
||||||
code: SpanStatusCode.ERROR,
|
|
||||||
message: String(err),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
throw err;
|
|
||||||
} finally {
|
|
||||||
span.end();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
if (res instanceof Response) {
|
|
||||||
return res;
|
|
||||||
}
|
|
||||||
|
|
||||||
result = res;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (components.length === 0) {
|
|
||||||
throw new Error(`Did not receive any components to render.`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const props = ctx as FreshReqContext<State>;
|
|
||||||
props.data = result?.data;
|
|
||||||
|
|
||||||
let vnode: VNode | null = null;
|
|
||||||
for (let i = components.length - 1; i >= 0; i--) {
|
|
||||||
const child = vnode;
|
|
||||||
// FIXME: remove when we're using `<Slot />`
|
|
||||||
props.Component = () => child;
|
|
||||||
|
|
||||||
const fn = components[i];
|
|
||||||
|
|
||||||
if (isAsyncAnyComponent(fn)) {
|
|
||||||
const result = 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) {
|
|
||||||
if (err instanceof Error) {
|
|
||||||
span.recordException(err);
|
|
||||||
} else {
|
|
||||||
span.setStatus({
|
|
||||||
code: SpanStatusCode.ERROR,
|
|
||||||
message: String(err),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
throw err;
|
|
||||||
} finally {
|
|
||||||
span.end();
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
if (result instanceof Response) {
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
vnode = result;
|
|
||||||
} else {
|
|
||||||
// deno-lint-ignore no-explicit-any
|
|
||||||
vnode = h(components[i] as any, props) as VNode;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let status: number | undefined = init?.status ?? result?.status;
|
|
||||||
if (
|
|
||||||
ctx.error !== null && ctx.error !== undefined
|
|
||||||
) {
|
|
||||||
if (
|
|
||||||
ctx.error instanceof HttpError
|
|
||||||
) {
|
|
||||||
status = ctx.error.status;
|
|
||||||
} else {
|
|
||||||
status = 500;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return ctx.render(vnode!, {
|
|
||||||
status,
|
|
||||||
statusText: init?.statusText,
|
|
||||||
headers: init?.headers ?? result?.headers,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,125 +0,0 @@
|
|||||||
import { expect } from "@std/expect";
|
|
||||||
import { delay, serveMiddleware } from "../../test_utils.ts";
|
|
||||||
import { renderMiddleware } from "./render_middleware.ts";
|
|
||||||
import { parseHtml } from "../../../tests/test_utils.tsx";
|
|
||||||
|
|
||||||
Deno.test("renderMiddleware - responds with HTML", async () => {
|
|
||||||
const server = await serveMiddleware(
|
|
||||||
renderMiddleware([() => <p>ok</p>], undefined),
|
|
||||||
);
|
|
||||||
|
|
||||||
const res = await server.get("/");
|
|
||||||
expect(res.headers.get("Content-Type")).toEqual("text/html; charset=utf-8");
|
|
||||||
|
|
||||||
const doc = parseHtml(await res.text());
|
|
||||||
// deno-lint-ignore no-explicit-any
|
|
||||||
expect((doc.body.firstChild as any).outerHTML).toEqual("<p>ok</p>");
|
|
||||||
});
|
|
||||||
|
|
||||||
Deno.test("renderMiddleware - bypass rendering when handler returns Response", async () => {
|
|
||||||
const server = await serveMiddleware(
|
|
||||||
renderMiddleware(
|
|
||||||
[() => <p>fail</p>],
|
|
||||||
() => new Response(null, { status: 204 }),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const res = await server.get("/");
|
|
||||||
expect(res.status).toEqual(204);
|
|
||||||
expect(res.body).toEqual(null);
|
|
||||||
});
|
|
||||||
|
|
||||||
Deno.test("renderMiddleware - chain components", async () => {
|
|
||||||
const server = await serveMiddleware(
|
|
||||||
renderMiddleware(
|
|
||||||
[
|
|
||||||
(ctx) => (
|
|
||||||
<div>
|
|
||||||
c1<ctx.Component />
|
|
||||||
</div>
|
|
||||||
),
|
|
||||||
(ctx) => (
|
|
||||||
<>
|
|
||||||
c2<ctx.Component />
|
|
||||||
</>
|
|
||||||
),
|
|
||||||
() => <>c3</>,
|
|
||||||
],
|
|
||||||
undefined,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const res = await server.get("/");
|
|
||||||
expect(res.status).toEqual(200);
|
|
||||||
|
|
||||||
const doc = parseHtml(await res.text());
|
|
||||||
expect(doc.body.firstChild?.textContent).toEqual("c1c2c3");
|
|
||||||
});
|
|
||||||
|
|
||||||
Deno.test("renderMiddleware - chain async components", async () => {
|
|
||||||
const server = await serveMiddleware(
|
|
||||||
renderMiddleware(
|
|
||||||
[
|
|
||||||
async (ctx) => {
|
|
||||||
await delay(1);
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
c1<ctx.Component />
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
},
|
|
||||||
async (ctx) => {
|
|
||||||
await delay(1);
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
c2<ctx.Component />
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
},
|
|
||||||
async () => {
|
|
||||||
await delay(1);
|
|
||||||
return <>c3</>;
|
|
||||||
},
|
|
||||||
],
|
|
||||||
undefined,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const res = await server.get("/");
|
|
||||||
expect(res.status).toEqual(200);
|
|
||||||
|
|
||||||
const doc = parseHtml(await res.text());
|
|
||||||
expect(doc.body.firstChild!.textContent).toEqual("c1c2c3");
|
|
||||||
});
|
|
||||||
|
|
||||||
Deno.test("renderMiddleware - async components Response bail out", async () => {
|
|
||||||
const server = await serveMiddleware(
|
|
||||||
renderMiddleware(
|
|
||||||
[
|
|
||||||
async (ctx) => {
|
|
||||||
await delay(1);
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
c1<ctx.Component />
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
},
|
|
||||||
async () => {
|
|
||||||
await delay(1);
|
|
||||||
|
|
||||||
return new Response("foo");
|
|
||||||
},
|
|
||||||
async () => {
|
|
||||||
await delay(1);
|
|
||||||
return <>c3</>;
|
|
||||||
},
|
|
||||||
],
|
|
||||||
undefined,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const res = await server.get("/");
|
|
||||||
expect(res.status).toEqual(200);
|
|
||||||
|
|
||||||
expect(await res.text()).toEqual("foo");
|
|
||||||
});
|
|
||||||
+158
@@ -0,0 +1,158 @@
|
|||||||
|
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 type { BuildCache } from "./build_cache.ts";
|
||||||
|
import { DEV_ERROR_OVERLAY_URL } from "./constants.ts";
|
||||||
|
import { renderToString } from "preact-render-to-string";
|
||||||
|
import { BUILD_ID } from "./runtime/build_id.ts";
|
||||||
|
|
||||||
|
export type AsyncAnyComponent<P> = {
|
||||||
|
(
|
||||||
|
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,
|
||||||
|
buildCache: BuildCache,
|
||||||
|
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 = `${basePath}/_fresh/js/${BUILD_ID}/fresh-runtime.js`;
|
||||||
|
let link = `<${encodeURI(runtimeUrl)}>; rel="modulepreload"; as="script"`;
|
||||||
|
state.islands.forEach((island) => {
|
||||||
|
const chunk = buildCache.getIslandChunkName(island.name);
|
||||||
|
if (chunk !== null) {
|
||||||
|
link += `, <${
|
||||||
|
encodeURI(`${basePath}${chunk}`)
|
||||||
|
}>; 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;
|
||||||
|
}
|
||||||
+184
-81
@@ -1,119 +1,180 @@
|
|||||||
export type Method = "HEAD" | "GET" | "POST" | "PATCH" | "PUT" | "DELETE";
|
export type Method =
|
||||||
|
| "HEAD"
|
||||||
|
| "GET"
|
||||||
|
| "POST"
|
||||||
|
| "PATCH"
|
||||||
|
| "PUT"
|
||||||
|
| "DELETE"
|
||||||
|
| "OPTIONS";
|
||||||
|
|
||||||
export interface Route<T> {
|
export type RouteByMethod<T> = {
|
||||||
path: string | URLPattern;
|
[m in Method]: T[];
|
||||||
method: Method | "ALL";
|
};
|
||||||
handlers: T[];
|
|
||||||
|
export interface StaticRouteDef<T> {
|
||||||
|
pattern: string | URLPattern;
|
||||||
|
byMethod: RouteByMethod<T>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DynamicRouteDef<T> {
|
||||||
|
pattern: URLPattern;
|
||||||
|
byMethod: RouteByMethod<T>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface RouteResult<T> {
|
export interface RouteResult<T> {
|
||||||
params: Record<string, string>;
|
params: Record<string, string>;
|
||||||
handlers: T[][];
|
handlers: T[];
|
||||||
methodMatch: boolean;
|
methodMatch: boolean;
|
||||||
patternMatch: boolean;
|
|
||||||
pattern: string | null;
|
pattern: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Router<T> {
|
export interface Router<T> {
|
||||||
_routes: Route<T>[];
|
|
||||||
_middlewares: T[];
|
|
||||||
addMiddleware(fn: T): void;
|
|
||||||
add(
|
add(
|
||||||
method: Method | "ALL",
|
method: Method | "OPTIONS" | "ALL",
|
||||||
pathname: string | URLPattern,
|
pathname: string,
|
||||||
handlers: T[],
|
handlers: T[],
|
||||||
|
unshift?: boolean,
|
||||||
): void;
|
): void;
|
||||||
match(method: Method, url: URL): RouteResult<T>;
|
match(method: Method, url: URL, init?: T[]): RouteResult<T>;
|
||||||
|
getAllowedMethods(pattern: string): string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export const IS_PATTERN = /[*:{}+?()]/;
|
export const IS_PATTERN = /[*:{}+?()]/;
|
||||||
|
|
||||||
export class UrlPatternRouter<T> implements Router<T> {
|
const EMPTY: string[] = [];
|
||||||
readonly _routes: Route<T>[] = [];
|
|
||||||
readonly _middlewares: T[] = [];
|
|
||||||
|
|
||||||
addMiddleware(fn: T): void {
|
export class UrlPatternRouter<T> implements Router<T> {
|
||||||
this._middlewares.push(fn);
|
#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 | "ALL", pathname: string | URLPattern, handlers: T[]) {
|
add(
|
||||||
if (
|
method: Method | "ALL",
|
||||||
typeof pathname === "string" && pathname !== "/*" &&
|
pathname: string,
|
||||||
IS_PATTERN.test(pathname)
|
handlers: T[],
|
||||||
) {
|
unshift = false,
|
||||||
this._routes.push({
|
) {
|
||||||
path: new URLPattern({ pathname }),
|
let allowed = this.#allowed.get(pathname);
|
||||||
handlers,
|
if (allowed === undefined) {
|
||||||
method,
|
allowed = new Set();
|
||||||
});
|
this.#allowed.set(pathname, allowed);
|
||||||
|
}
|
||||||
|
if (method === "ALL") {
|
||||||
|
allowed.add("GET");
|
||||||
|
allowed.add("POST");
|
||||||
|
allowed.add("PATCH");
|
||||||
|
allowed.add("PUT");
|
||||||
|
allowed.add("DELETE");
|
||||||
|
allowed.add("HEAD");
|
||||||
|
allowed.add("OPTIONS");
|
||||||
} else {
|
} else {
|
||||||
this._routes.push({
|
allowed.add(method);
|
||||||
path: pathname,
|
}
|
||||||
handlers,
|
|
||||||
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: {
|
||||||
|
DELETE: [],
|
||||||
|
GET: [],
|
||||||
|
HEAD: [],
|
||||||
|
OPTIONS: [],
|
||||||
|
PATCH: [],
|
||||||
|
POST: [],
|
||||||
|
PUT: [],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
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: {
|
||||||
|
DELETE: [],
|
||||||
|
GET: [],
|
||||||
|
HEAD: [],
|
||||||
|
OPTIONS: [],
|
||||||
|
PATCH: [],
|
||||||
|
POST: [],
|
||||||
|
PUT: [],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
this.#statics.set(pathname, def);
|
||||||
|
}
|
||||||
|
|
||||||
|
byMethod = def.byMethod;
|
||||||
|
}
|
||||||
|
|
||||||
|
const fn = unshift ? "unshift" : "push";
|
||||||
|
if (method === "ALL") {
|
||||||
|
byMethod.DELETE[fn](...handlers);
|
||||||
|
byMethod.GET[fn](...handlers);
|
||||||
|
byMethod.HEAD[fn](...handlers);
|
||||||
|
byMethod.OPTIONS[fn](...handlers);
|
||||||
|
byMethod.PATCH[fn](...handlers);
|
||||||
|
byMethod.POST[fn](...handlers);
|
||||||
|
byMethod.PUT[fn](...handlers);
|
||||||
|
} else {
|
||||||
|
byMethod[method][fn](...handlers);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
match(method: Method, url: URL): RouteResult<T> {
|
match(method: Method, url: URL, init: T[] = []): RouteResult<T> {
|
||||||
const result: RouteResult<T> = {
|
const result: RouteResult<T> = {
|
||||||
params: {},
|
params: Object.create(null),
|
||||||
handlers: [],
|
handlers: init,
|
||||||
methodMatch: false,
|
methodMatch: false,
|
||||||
patternMatch: false,
|
|
||||||
pattern: null,
|
pattern: null,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (this._middlewares.length > 0) {
|
const staticMatch = this.#statics.get(url.pathname);
|
||||||
result.handlers.push(this._middlewares);
|
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._routes.length; i++) {
|
for (let i = 0; i < this.#dynamicArr.length; i++) {
|
||||||
const route = this._routes[i];
|
const route = this.#dynamicArr[i];
|
||||||
|
|
||||||
// Fast path for string based routes which are expected
|
const match = route.pattern.exec(url);
|
||||||
// to be either wildcard `*` match or an exact pathname match.
|
if (match === null) continue;
|
||||||
if (
|
|
||||||
typeof route.path === "string" &&
|
|
||||||
(route.path === "/*" || route.path === url.pathname)
|
|
||||||
) {
|
|
||||||
if (route.method !== "ALL") result.patternMatch = true;
|
|
||||||
result.pattern = route.path;
|
|
||||||
|
|
||||||
if (route.method === "ALL" || route.method === method) {
|
result.pattern = route.pattern.pathname;
|
||||||
result.handlers.push(route.handlers);
|
|
||||||
|
|
||||||
if (route.path === "/*" && route.method === "ALL") {
|
const handlers = route.byMethod[method];
|
||||||
continue;
|
if (handlers.length > 0) {
|
||||||
}
|
result.methodMatch = true;
|
||||||
|
result.handlers.push(...handlers);
|
||||||
|
|
||||||
result.methodMatch = true;
|
// Decode matched params
|
||||||
|
for (const [key, value] of Object.entries(match.pathname.groups)) {
|
||||||
return result;
|
result.params[key] = value === undefined ? "" : decodeURI(value);
|
||||||
}
|
|
||||||
} else if (route.path instanceof URLPattern) {
|
|
||||||
const match = route.path.exec(url);
|
|
||||||
if (match !== null) {
|
|
||||||
if (route.method !== "ALL") result.patternMatch = true;
|
|
||||||
result.pattern = route.path.pathname;
|
|
||||||
|
|
||||||
if (route.method === "ALL" || route.method === method) {
|
|
||||||
result.handlers.push(route.handlers);
|
|
||||||
|
|
||||||
// Decode matched params
|
|
||||||
for (const [key, value] of Object.entries(match.pathname.groups)) {
|
|
||||||
result.params[key] = value === undefined ? "" : decodeURI(value);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (route.method === "ALL") {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
result.methodMatch = true;
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
@@ -123,7 +184,10 @@ export class UrlPatternRouter<T> implements Router<T> {
|
|||||||
/**
|
/**
|
||||||
* Transform a filesystem URL path to a `path-to-regex` style matcher.
|
* Transform a filesystem URL path to a `path-to-regex` style matcher.
|
||||||
*/
|
*/
|
||||||
export function pathToPattern(path: string): string {
|
export function pathToPattern(
|
||||||
|
path: string,
|
||||||
|
options?: { keepGroups: boolean },
|
||||||
|
): string {
|
||||||
const parts = path.split("/");
|
const parts = path.split("/");
|
||||||
if (parts[parts.length - 1] === "index") {
|
if (parts[parts.length - 1] === "index") {
|
||||||
if (parts.length === 1) {
|
if (parts.length === 1) {
|
||||||
@@ -148,7 +212,7 @@ export function pathToPattern(path: string): string {
|
|||||||
// Case: /foo/(bar) -> /foo
|
// Case: /foo/(bar) -> /foo
|
||||||
// Case: /foo/(bar)/bob -> /foo/bob
|
// Case: /foo/(bar)/bob -> /foo/bob
|
||||||
// Case: /(foo)/bar -> /bar
|
// Case: /(foo)/bar -> /bar
|
||||||
if (part.startsWith("(") && part.endsWith(")")) {
|
if (!options?.keepGroups && part.startsWith("(") && part.endsWith(")")) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -216,3 +280,42 @@ export function pathToPattern(path: string): string {
|
|||||||
|
|
||||||
return 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 === "/*") path = "/*";
|
||||||
|
|
||||||
|
const s = (basePath !== "" && path === "/") ? "" : path;
|
||||||
|
return basePath + s;
|
||||||
|
}
|
||||||
|
|||||||
+44
-51
@@ -1,5 +1,11 @@
|
|||||||
import { expect } from "@std/expect";
|
import { expect } from "@std/expect";
|
||||||
import { IS_PATTERN, pathToPattern, UrlPatternRouter } from "./router.ts";
|
import {
|
||||||
|
IS_PATTERN,
|
||||||
|
mergePath,
|
||||||
|
pathToPattern,
|
||||||
|
patternToSegments,
|
||||||
|
UrlPatternRouter,
|
||||||
|
} from "./router.ts";
|
||||||
|
|
||||||
Deno.test("IS_PATTERN", () => {
|
Deno.test("IS_PATTERN", () => {
|
||||||
expect(IS_PATTERN.test("/foo")).toEqual(false);
|
expect(IS_PATTERN.test("/foo")).toEqual(false);
|
||||||
@@ -11,66 +17,26 @@ Deno.test("IS_PATTERN", () => {
|
|||||||
expect(IS_PATTERN.test("/foo/(a)")).toEqual(true);
|
expect(IS_PATTERN.test("/foo/(a)")).toEqual(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
Deno.test("UrlPatternRouter - GET get first match", () => {
|
|
||||||
const router = new UrlPatternRouter();
|
|
||||||
const A = () => {};
|
|
||||||
const B = () => {};
|
|
||||||
const C = () => {};
|
|
||||||
router.add("GET", "/", [A]);
|
|
||||||
router.add("GET", "/", [B]);
|
|
||||||
router.add("GET", "/", [C]);
|
|
||||||
|
|
||||||
const res = router.match("GET", new URL("/", "http://localhost"));
|
|
||||||
expect(res).toEqual({
|
|
||||||
params: {},
|
|
||||||
handlers: [[A]],
|
|
||||||
methodMatch: true,
|
|
||||||
pattern: "/",
|
|
||||||
patternMatch: true,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
Deno.test("UrlPatternRouter - GET get matches with middlewares", () => {
|
|
||||||
const router = new UrlPatternRouter();
|
|
||||||
const A = () => {};
|
|
||||||
const B = () => {};
|
|
||||||
const C = () => {};
|
|
||||||
router.add("ALL", "/*", [A]);
|
|
||||||
router.add("ALL", "/*", [B]);
|
|
||||||
router.add("GET", "/", [C]);
|
|
||||||
|
|
||||||
const res = router.match("GET", new URL("/", "http://localhost"));
|
|
||||||
expect(res).toEqual({
|
|
||||||
params: {},
|
|
||||||
handlers: [[A], [B], [C]],
|
|
||||||
methodMatch: true,
|
|
||||||
pattern: "/",
|
|
||||||
patternMatch: true,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
Deno.test("UrlPatternRouter - GET extract params", () => {
|
Deno.test("UrlPatternRouter - GET extract params", () => {
|
||||||
const router = new UrlPatternRouter();
|
const router = new UrlPatternRouter();
|
||||||
const A = () => {};
|
const A = () => {};
|
||||||
router.add("GET", new URLPattern({ pathname: "/:foo/:bar/c" }), [A]);
|
router.add("GET", "/:foo/:bar/c", [A]);
|
||||||
|
|
||||||
let res = router.match("GET", new URL("/a/b/c", "http://localhost"));
|
let res = router.match("GET", new URL("/a/b/c", "http://localhost"));
|
||||||
expect(res).toEqual({
|
expect(res).toEqual({
|
||||||
params: { foo: "a", bar: "b" },
|
params: { foo: "a", bar: "b" },
|
||||||
handlers: [[A]],
|
handlers: [A],
|
||||||
methodMatch: true,
|
methodMatch: true,
|
||||||
pattern: "/:foo/:bar/c",
|
pattern: "/:foo/:bar/c",
|
||||||
patternMatch: true,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Decode params
|
// Decode params
|
||||||
res = router.match("GET", new URL("/a%20a/b/c", "http://localhost"));
|
res = router.match("GET", new URL("/a%20a/b/c", "http://localhost"));
|
||||||
expect(res).toEqual({
|
expect(res).toEqual({
|
||||||
params: { foo: "a a", bar: "b" },
|
params: { foo: "a a", bar: "b" },
|
||||||
handlers: [[A]],
|
handlers: [A],
|
||||||
methodMatch: true,
|
methodMatch: true,
|
||||||
pattern: "/:foo/:bar/c",
|
pattern: "/:foo/:bar/c",
|
||||||
patternMatch: true,
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -81,11 +47,10 @@ Deno.test("UrlPatternRouter - Wrong method match", () => {
|
|||||||
|
|
||||||
const res = router.match("POST", new URL("/foo", "http://localhost"));
|
const res = router.match("POST", new URL("/foo", "http://localhost"));
|
||||||
expect(res).toEqual({
|
expect(res).toEqual({
|
||||||
params: {},
|
params: Object.create(null),
|
||||||
handlers: [],
|
handlers: [],
|
||||||
methodMatch: false,
|
methodMatch: false,
|
||||||
pattern: "/foo",
|
pattern: "/foo",
|
||||||
patternMatch: true,
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -98,11 +63,10 @@ Deno.test("UrlPatternRouter - wrong + correct method", () => {
|
|||||||
|
|
||||||
const res = router.match("POST", new URL("/foo", "http://localhost"));
|
const res = router.match("POST", new URL("/foo", "http://localhost"));
|
||||||
expect(res).toEqual({
|
expect(res).toEqual({
|
||||||
params: {},
|
params: Object.create(null),
|
||||||
handlers: [[B]],
|
handlers: [B],
|
||||||
methodMatch: true,
|
methodMatch: true,
|
||||||
pattern: "/foo",
|
pattern: "/foo",
|
||||||
patternMatch: true,
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -116,10 +80,9 @@ Deno.test("UrlPatternRouter - convert patterns automatically", () => {
|
|||||||
params: {
|
params: {
|
||||||
id: "foo",
|
id: "foo",
|
||||||
},
|
},
|
||||||
handlers: [[A]],
|
handlers: [A],
|
||||||
methodMatch: true,
|
methodMatch: true,
|
||||||
pattern: "/books/:id",
|
pattern: "/books/:id",
|
||||||
patternMatch: true,
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -170,4 +133,34 @@ Deno.test("pathToPattern", async (t) => {
|
|||||||
expect(() => pathToPattern("foo/foo-[[name]]")).toThrow();
|
expect(() => pathToPattern("foo/foo-[[name]]")).toThrow();
|
||||||
expect(() => pathToPattern("foo/[[name]]-bar")).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/*");
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import {
|
|||||||
} from "preact";
|
} from "preact";
|
||||||
import type { Signal } from "@preact/signals";
|
import type { Signal } from "@preact/signals";
|
||||||
import type { Stringifiers } from "../../jsonify/stringify.ts";
|
import type { Stringifiers } from "../../jsonify/stringify.ts";
|
||||||
import type { PageProps } from "../../context.ts";
|
import type { PageProps } from "../../render.ts";
|
||||||
import { Partial, type PartialProps } from "../shared.ts";
|
import { Partial, type PartialProps } from "../shared.ts";
|
||||||
import { stringify } from "../../jsonify/stringify.ts";
|
import { stringify } from "../../jsonify/stringify.ts";
|
||||||
import type { ServerIslandRegistry } from "../../context.ts";
|
import type { ServerIslandRegistry } from "../../context.ts";
|
||||||
@@ -88,7 +88,8 @@ export class RenderState {
|
|||||||
hasRuntimeScript = false;
|
hasRuntimeScript = false;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
public ctx: PageProps<unknown, unknown>,
|
// deno-lint-ignore no-explicit-any
|
||||||
|
public ctx: PageProps<any, any>,
|
||||||
public islandRegistry: ServerIslandRegistry,
|
public islandRegistry: ServerIslandRegistry,
|
||||||
public buildCache: BuildCache,
|
public buildCache: BuildCache,
|
||||||
public partialId: string,
|
public partialId: string,
|
||||||
|
|||||||
+214
@@ -0,0 +1,214 @@
|
|||||||
|
import type { AnyComponent } from "preact";
|
||||||
|
import type { MiddlewareFn } 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: MiddlewareFn<State>[];
|
||||||
|
layout: {
|
||||||
|
component: RouteComponent<State>;
|
||||||
|
config: LayoutConfig | null;
|
||||||
|
} | null;
|
||||||
|
errorRoute: Route<State> | null;
|
||||||
|
notFound: MiddlewareFn<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>,
|
||||||
|
): MiddlewareFn<State>[] {
|
||||||
|
const result: MiddlewareFn<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"));
|
||||||
|
});
|
||||||
+12
-3
@@ -1,4 +1,4 @@
|
|||||||
import { FreshReqContext } from "./context.ts";
|
import { Context } from "./context.ts";
|
||||||
import type { FsAdapter } from "./fs.ts";
|
import type { FsAdapter } from "./fs.ts";
|
||||||
import { type BuildCache, ProdBuildCache } from "./build_cache.ts";
|
import { type BuildCache, ProdBuildCache } from "./build_cache.ts";
|
||||||
import type { ResolvedFreshConfig } from "./config.ts";
|
import type { ResolvedFreshConfig } from "./config.ts";
|
||||||
@@ -45,6 +45,15 @@ export class FakeServer {
|
|||||||
const req = new Request(url, { method: "head" });
|
const req = new Request(url, { method: "head" });
|
||||||
return await this.handler(req, STUB);
|
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) {
|
private toUrl(path: string) {
|
||||||
return new URL(path, "http://localhost/");
|
return new URL(path, "http://localhost/");
|
||||||
@@ -62,7 +71,7 @@ const DEFAULT_CONFIG: ResolvedFreshConfig = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export function serveMiddleware<T>(
|
export function serveMiddleware<T>(
|
||||||
middleware: (ctx: FreshReqContext<T>) => Response | Promise<Response>,
|
middleware: (ctx: Context<T>) => Response | Promise<Response>,
|
||||||
options: {
|
options: {
|
||||||
config?: ResolvedFreshConfig;
|
config?: ResolvedFreshConfig;
|
||||||
buildCache?: BuildCache;
|
buildCache?: BuildCache;
|
||||||
@@ -76,7 +85,7 @@ export function serveMiddleware<T>(
|
|||||||
const buildCache = options.buildCache ??
|
const buildCache = options.buildCache ??
|
||||||
new ProdBuildCache(config, new Map(), new Map(), true);
|
new ProdBuildCache(config, new Map(), new Map(), true);
|
||||||
|
|
||||||
const ctx = new FreshReqContext<T>(
|
const ctx = new Context<T>(
|
||||||
req,
|
req,
|
||||||
new URL(req.url),
|
new URL(req.url),
|
||||||
DEFAULT_CONN_INFO,
|
DEFAULT_CONN_INFO,
|
||||||
|
|||||||
@@ -1,3 +1,6 @@
|
|||||||
|
import type { RouteHandler } from "./handlers.ts";
|
||||||
|
import type { RouteComponent } from "./segments.ts";
|
||||||
|
|
||||||
export interface RouteConfig {
|
export interface RouteConfig {
|
||||||
/**
|
/**
|
||||||
* A route override for the page. This is useful for pages where the route
|
* A route override for the page. This is useful for pages where the route
|
||||||
@@ -42,6 +45,12 @@ export interface LayoutConfig {
|
|||||||
skipAppWrapper?: boolean;
|
skipAppWrapper?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface Route<State> {
|
||||||
|
component?: RouteComponent<State>;
|
||||||
|
config?: RouteConfig;
|
||||||
|
handler?: RouteHandler<unknown, State>;
|
||||||
|
}
|
||||||
|
|
||||||
// TODO: Uncomment once JSR supports global types
|
// TODO: Uncomment once JSR supports global types
|
||||||
// declare global {
|
// declare global {
|
||||||
// namespace preact.createElement.JSX {
|
// namespace preact.createElement.JSX {
|
||||||
|
|||||||
@@ -14,25 +14,6 @@ export function assertInDir(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Joins two path segments into a single normalized path.
|
|
||||||
* @example
|
|
||||||
* ```ts
|
|
||||||
* mergePaths("/api", "users"); // "/api/users"
|
|
||||||
* mergePaths("/api/", "/users"); // "/api/users"
|
|
||||||
* mergePaths("/", "/users"); // "/users"
|
|
||||||
* mergePaths("", "/users"); // "/users"
|
|
||||||
* mergePaths("/api", "/users"); // "/api/users"
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function mergePaths(a: string, b: string) {
|
|
||||||
if (a === "" || a === "/" || a === "/*") return b;
|
|
||||||
if (b === "/") return a;
|
|
||||||
if (a.endsWith("/")) return a.slice(0, -1) + b;
|
|
||||||
if (!b.startsWith("/")) return a + "/" + b;
|
|
||||||
return a + b;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Converts a file path to a valid JS export name.
|
* Converts a file path to a valid JS export name.
|
||||||
*
|
*
|
||||||
|
|||||||
+1
-10
@@ -1,14 +1,5 @@
|
|||||||
import { expect } from "@std/expect";
|
import { expect } from "@std/expect";
|
||||||
import { escapeScript, mergePaths, pathToExportName } from "./utils.ts";
|
import { escapeScript, pathToExportName } from "./utils.ts";
|
||||||
|
|
||||||
Deno.test("mergePaths", () => {
|
|
||||||
expect(mergePaths("", "")).toEqual("");
|
|
||||||
expect(mergePaths("/", "/foo")).toEqual("/foo");
|
|
||||||
expect(mergePaths("/*", "/foo")).toEqual("/foo");
|
|
||||||
expect(mergePaths("/foo/bar", "/baz")).toEqual("/foo/bar/baz");
|
|
||||||
expect(mergePaths("/foo/bar/", "/baz")).toEqual("/foo/bar/baz");
|
|
||||||
expect(mergePaths("/foo/bar", "baz")).toEqual("/foo/bar/baz");
|
|
||||||
});
|
|
||||||
|
|
||||||
Deno.test("filenameToExportName", () => {
|
Deno.test("filenameToExportName", () => {
|
||||||
expect(pathToExportName("/islands/foo.tsx")).toBe("foo");
|
expect(pathToExportName("/islands/foo.tsx")).toBe("foo");
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { App, staticFiles } from "fresh";
|
import { App } from "fresh";
|
||||||
import {
|
import {
|
||||||
allIslandApp,
|
allIslandApp,
|
||||||
assertNotSelector,
|
assertNotSelector,
|
||||||
@@ -27,8 +27,7 @@ function testApp<T>(): App<T> {
|
|||||||
const app = new App<T>()
|
const app = new App<T>()
|
||||||
.island(selfCounter, "SelfCounter", SelfCounter)
|
.island(selfCounter, "SelfCounter", SelfCounter)
|
||||||
.island(partialInIsland, "PartialInIsland", PartialInIsland)
|
.island(partialInIsland, "PartialInIsland", PartialInIsland)
|
||||||
.island(jsonIsland, "JsonIsland", JsonIsland)
|
.island(jsonIsland, "JsonIsland", JsonIsland);
|
||||||
.use(staticFiles());
|
|
||||||
setBuildCache(app, getBuildCache(allIslandApp));
|
setBuildCache(app, getBuildCache(allIslandApp));
|
||||||
return app;
|
return app;
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-23
@@ -19,7 +19,6 @@ import {
|
|||||||
withBrowserApp,
|
withBrowserApp,
|
||||||
} from "./test_utils.tsx";
|
} from "./test_utils.tsx";
|
||||||
import { parseHtml, waitForText } from "./test_utils.tsx";
|
import { parseHtml, waitForText } from "./test_utils.tsx";
|
||||||
import { staticFiles } from "../src/middlewares/static_files.ts";
|
|
||||||
import { expect } from "@std/expect";
|
import { expect } from "@std/expect";
|
||||||
import { JsxConditional } from "./fixtures_islands/JsxConditional.tsx";
|
import { JsxConditional } from "./fixtures_islands/JsxConditional.tsx";
|
||||||
import { FnIsland } from "./fixtures_islands/FnIsland.tsx";
|
import { FnIsland } from "./fixtures_islands/FnIsland.tsx";
|
||||||
@@ -47,7 +46,6 @@ Deno.test({
|
|||||||
const counterIsland = getIsland("Counter.tsx");
|
const counterIsland = getIsland("Counter.tsx");
|
||||||
|
|
||||||
const app = testApp()
|
const app = testApp()
|
||||||
.use(staticFiles())
|
|
||||||
.island(counterIsland, "Counter", Counter)
|
.island(counterIsland, "Counter", Counter)
|
||||||
.get("/", (ctx) => {
|
.get("/", (ctx) => {
|
||||||
const sig = signal(3);
|
const sig = signal(3);
|
||||||
@@ -73,7 +71,6 @@ Deno.test({
|
|||||||
const multipleIslands = getIsland("Multiple.tsx");
|
const multipleIslands = getIsland("Multiple.tsx");
|
||||||
|
|
||||||
const app = testApp()
|
const app = testApp()
|
||||||
.use(staticFiles())
|
|
||||||
.island(multipleIslands, "Multiple1", Multiple1)
|
.island(multipleIslands, "Multiple1", Multiple1)
|
||||||
.island(multipleIslands, "Multiple2", Multiple2)
|
.island(multipleIslands, "Multiple2", Multiple2)
|
||||||
.get("/", (ctx) => {
|
.get("/", (ctx) => {
|
||||||
@@ -103,7 +100,6 @@ Deno.test({
|
|||||||
const counterIsland = getIsland("Counter.tsx");
|
const counterIsland = getIsland("Counter.tsx");
|
||||||
|
|
||||||
const app = testApp()
|
const app = testApp()
|
||||||
.use(staticFiles())
|
|
||||||
.island(counterIsland, "Counter", Counter)
|
.island(counterIsland, "Counter", Counter)
|
||||||
.get("/", (ctx) => {
|
.get("/", (ctx) => {
|
||||||
const sig = signal(0);
|
const sig = signal(0);
|
||||||
@@ -132,7 +128,6 @@ Deno.test({
|
|||||||
const jsonIsland = getIsland("JsonIsland.tsx");
|
const jsonIsland = getIsland("JsonIsland.tsx");
|
||||||
|
|
||||||
const app = testApp()
|
const app = testApp()
|
||||||
.use(staticFiles())
|
|
||||||
.island(jsonIsland, "JsonIsland", Counter)
|
.island(jsonIsland, "JsonIsland", Counter)
|
||||||
.get("/", (ctx) => {
|
.get("/", (ctx) => {
|
||||||
return ctx.render(
|
return ctx.render(
|
||||||
@@ -160,7 +155,6 @@ Deno.test({
|
|||||||
const nullIsland = getIsland("NullIsland.tsx");
|
const nullIsland = getIsland("NullIsland.tsx");
|
||||||
|
|
||||||
const app = testApp()
|
const app = testApp()
|
||||||
.use(staticFiles())
|
|
||||||
.island(nullIsland, "NullIsland", NullIsland)
|
.island(nullIsland, "NullIsland", NullIsland)
|
||||||
.get("/", (ctx) => {
|
.get("/", (ctx) => {
|
||||||
return ctx.render(
|
return ctx.render(
|
||||||
@@ -184,7 +178,6 @@ Deno.test({
|
|||||||
const islandInIsland = getIsland("IslandInIsland.tsx");
|
const islandInIsland = getIsland("IslandInIsland.tsx");
|
||||||
|
|
||||||
const app = testApp()
|
const app = testApp()
|
||||||
.use(staticFiles())
|
|
||||||
.island(counter, "Counter", Counter)
|
.island(counter, "Counter", Counter)
|
||||||
.island(islandInIsland, "IslandInIsland", IslandInIsland)
|
.island(islandInIsland, "IslandInIsland", IslandInIsland)
|
||||||
.get("/", (ctx) => {
|
.get("/", (ctx) => {
|
||||||
@@ -213,7 +206,6 @@ Deno.test({
|
|||||||
const jsxIsland = getIsland("JsxIsland.tsx");
|
const jsxIsland = getIsland("JsxIsland.tsx");
|
||||||
|
|
||||||
const app = testApp()
|
const app = testApp()
|
||||||
.use(staticFiles())
|
|
||||||
.island(jsxIsland, "JsxIsland", JsxIsland)
|
.island(jsxIsland, "JsxIsland", JsxIsland)
|
||||||
.get("/", (ctx) => {
|
.get("/", (ctx) => {
|
||||||
return ctx.render(
|
return ctx.render(
|
||||||
@@ -241,7 +233,6 @@ Deno.test({
|
|||||||
const jsxIsland = getIsland("JsxIsland.tsx");
|
const jsxIsland = getIsland("JsxIsland.tsx");
|
||||||
|
|
||||||
const app = testApp()
|
const app = testApp()
|
||||||
.use(staticFiles())
|
|
||||||
.island(jsxIsland, "JsxIsland", JsxIsland)
|
.island(jsxIsland, "JsxIsland", JsxIsland)
|
||||||
.get("/", (ctx) => {
|
.get("/", (ctx) => {
|
||||||
return ctx.render(
|
return ctx.render(
|
||||||
@@ -271,7 +262,6 @@ Deno.test({
|
|||||||
const jsxChildrenIsland = getIsland("JsxChildrenIsland.tsx");
|
const jsxChildrenIsland = getIsland("JsxChildrenIsland.tsx");
|
||||||
|
|
||||||
const app = testApp()
|
const app = testApp()
|
||||||
.use(staticFiles())
|
|
||||||
.island(jsxChildrenIsland, "JsxChildrenIsland", JsxChildrenIsland)
|
.island(jsxChildrenIsland, "JsxChildrenIsland", JsxChildrenIsland)
|
||||||
.get("/", (ctx) => {
|
.get("/", (ctx) => {
|
||||||
return ctx.render(
|
return ctx.render(
|
||||||
@@ -307,7 +297,6 @@ Deno.test({
|
|||||||
const selfCounter = getIsland("SelfCounter.tsx");
|
const selfCounter = getIsland("SelfCounter.tsx");
|
||||||
|
|
||||||
const app = testApp()
|
const app = testApp()
|
||||||
.use(staticFiles())
|
|
||||||
.island(passThrough, "PassThrough", PassThrough)
|
.island(passThrough, "PassThrough", PassThrough)
|
||||||
.island(selfCounter, "SelfCounter", SelfCounter)
|
.island(selfCounter, "SelfCounter", SelfCounter)
|
||||||
.get("/", (ctx) => {
|
.get("/", (ctx) => {
|
||||||
@@ -339,7 +328,6 @@ Deno.test({
|
|||||||
const selfCounter = getIsland("SelfCounter.tsx");
|
const selfCounter = getIsland("SelfCounter.tsx");
|
||||||
|
|
||||||
const app = testApp()
|
const app = testApp()
|
||||||
.use(staticFiles())
|
|
||||||
.island(counterWithSlots, "CounterWithSlots", CounterWithSlots)
|
.island(counterWithSlots, "CounterWithSlots", CounterWithSlots)
|
||||||
.island(selfCounter, "SelfCounter", SelfCounter)
|
.island(selfCounter, "SelfCounter", SelfCounter)
|
||||||
.get("/", (ctx) => {
|
.get("/", (ctx) => {
|
||||||
@@ -382,7 +370,6 @@ Deno.test({
|
|||||||
const selfCounter = getIsland("SelfCounter.tsx");
|
const selfCounter = getIsland("SelfCounter.tsx");
|
||||||
|
|
||||||
const app = testApp()
|
const app = testApp()
|
||||||
.use(staticFiles())
|
|
||||||
.island(passThrough, "PassThrough", PassThrough)
|
.island(passThrough, "PassThrough", PassThrough)
|
||||||
.island(selfCounter, "SelfCounter", SelfCounter)
|
.island(selfCounter, "SelfCounter", SelfCounter)
|
||||||
.get("/", (ctx) => {
|
.get("/", (ctx) => {
|
||||||
@@ -424,7 +411,6 @@ Deno.test({
|
|||||||
const selfCounter = getIsland("SelfCounter.tsx");
|
const selfCounter = getIsland("SelfCounter.tsx");
|
||||||
|
|
||||||
const app = testApp()
|
const app = testApp()
|
||||||
.use(staticFiles())
|
|
||||||
.island(jsxConditional, "JsxConditional", JsxConditional)
|
.island(jsxConditional, "JsxConditional", JsxConditional)
|
||||||
.island(selfCounter, "SelfCounter", SelfCounter)
|
.island(selfCounter, "SelfCounter", SelfCounter)
|
||||||
.get("/", (ctx) => {
|
.get("/", (ctx) => {
|
||||||
@@ -466,7 +452,6 @@ Deno.test({
|
|||||||
const jsxConditional = getIsland("JsxConditional.tsx");
|
const jsxConditional = getIsland("JsxConditional.tsx");
|
||||||
|
|
||||||
const app = testApp()
|
const app = testApp()
|
||||||
.use(staticFiles())
|
|
||||||
.island(jsxConditional, "JsxConditional", JsxConditional)
|
.island(jsxConditional, "JsxConditional", JsxConditional)
|
||||||
.get("/", (ctx) => {
|
.get("/", (ctx) => {
|
||||||
return ctx.render(
|
return ctx.render(
|
||||||
@@ -541,7 +526,6 @@ Deno.test({
|
|||||||
const fnIsland = getIsland("FnIsland.tsx");
|
const fnIsland = getIsland("FnIsland.tsx");
|
||||||
|
|
||||||
const app = testApp()
|
const app = testApp()
|
||||||
.use(staticFiles())
|
|
||||||
.island(fragmentIsland, "FragmentIsland", FragmentIsland)
|
.island(fragmentIsland, "FragmentIsland", FragmentIsland)
|
||||||
.island(fnIsland, "FnIsland", FnIsland)
|
.island(fnIsland, "FnIsland", FnIsland)
|
||||||
.get("/", (ctx) => {
|
.get("/", (ctx) => {
|
||||||
@@ -570,7 +554,6 @@ Deno.test({
|
|||||||
const escapeIsland = getIsland("EscapeIsland.tsx");
|
const escapeIsland = getIsland("EscapeIsland.tsx");
|
||||||
|
|
||||||
const app = testApp()
|
const app = testApp()
|
||||||
.use(staticFiles())
|
|
||||||
.island(escapeIsland, "EscapeIsland", EscapeIsland)
|
.island(escapeIsland, "EscapeIsland", EscapeIsland)
|
||||||
.get("/", (ctx) => {
|
.get("/", (ctx) => {
|
||||||
return ctx.render(
|
return ctx.render(
|
||||||
@@ -667,7 +650,6 @@ Deno.test({
|
|||||||
const nodeProcess = getIsland("NodeProcess.tsx");
|
const nodeProcess = getIsland("NodeProcess.tsx");
|
||||||
|
|
||||||
const app = testApp()
|
const app = testApp()
|
||||||
.use(staticFiles())
|
|
||||||
.island(nodeProcess, "NodeProcess", NodeProcess)
|
.island(nodeProcess, "NodeProcess", NodeProcess)
|
||||||
.get("/", (ctx) =>
|
.get("/", (ctx) =>
|
||||||
ctx.render(
|
ctx.render(
|
||||||
@@ -695,7 +677,6 @@ Deno.test({
|
|||||||
const selfCounter = getIsland("SelfCounter.tsx");
|
const selfCounter = getIsland("SelfCounter.tsx");
|
||||||
|
|
||||||
const app = testApp({ basePath: "/foo" })
|
const app = testApp({ basePath: "/foo" })
|
||||||
.use(staticFiles())
|
|
||||||
.island(selfCounter, "SelfCounter", SelfCounter)
|
.island(selfCounter, "SelfCounter", SelfCounter)
|
||||||
.get("/", (ctx) =>
|
.get("/", (ctx) =>
|
||||||
ctx.render(
|
ctx.render(
|
||||||
@@ -720,7 +701,6 @@ Deno.test({
|
|||||||
const freshAttrs = getIsland("FreshAttrs.tsx");
|
const freshAttrs = getIsland("FreshAttrs.tsx");
|
||||||
|
|
||||||
const app = testApp()
|
const app = testApp()
|
||||||
.use(staticFiles())
|
|
||||||
.island(freshAttrs, "FreshAttrs", FreshAttrs)
|
.island(freshAttrs, "FreshAttrs", FreshAttrs)
|
||||||
.get("/", (ctx) =>
|
.get("/", (ctx) =>
|
||||||
ctx.render(
|
ctx.render(
|
||||||
@@ -747,8 +727,7 @@ Deno.test({
|
|||||||
Deno.test({
|
Deno.test({
|
||||||
name: "fsRoutes - load islands from group folder",
|
name: "fsRoutes - load islands from group folder",
|
||||||
fn: async () => {
|
fn: async () => {
|
||||||
const app = testApp()
|
const app = testApp();
|
||||||
.use(staticFiles());
|
|
||||||
|
|
||||||
await fsRoutes(app, {
|
await fsRoutes(app, {
|
||||||
dir: path.join(
|
dir: path.join(
|
||||||
@@ -778,7 +757,6 @@ Deno.test({
|
|||||||
const selfCounter = getIsland("SelfCounter.tsx");
|
const selfCounter = getIsland("SelfCounter.tsx");
|
||||||
|
|
||||||
const app = testApp()
|
const app = testApp()
|
||||||
.use(staticFiles())
|
|
||||||
.island(selfCounter, "SelfCounter", SelfCounter)
|
.island(selfCounter, "SelfCounter", SelfCounter)
|
||||||
.get("/", (ctx) =>
|
.get("/", (ctx) =>
|
||||||
ctx.render(
|
ctx.render(
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { App, staticFiles } from "fresh";
|
import { App } from "fresh";
|
||||||
import { Partial } from "fresh/runtime";
|
import { Partial } from "fresh/runtime";
|
||||||
import {
|
import {
|
||||||
allIslandApp,
|
allIslandApp,
|
||||||
@@ -40,8 +40,7 @@ function testApp<T>(): App<T> {
|
|||||||
.island(selfCounter, "SelfCounter", SelfCounter)
|
.island(selfCounter, "SelfCounter", SelfCounter)
|
||||||
.island(partialInIsland, "PartialInIsland", PartialInIsland)
|
.island(partialInIsland, "PartialInIsland", PartialInIsland)
|
||||||
.island(jsonIsland, "JsonIsland", JsonIsland)
|
.island(jsonIsland, "JsonIsland", JsonIsland)
|
||||||
.island(optOutPartialLink, "OptOutPartialLink", OptOutPartialLink)
|
.island(optOutPartialLink, "OptOutPartialLink", OptOutPartialLink);
|
||||||
.use(staticFiles());
|
|
||||||
|
|
||||||
setBuildCache(app, getBuildCache(allIslandApp));
|
setBuildCache(app, getBuildCache(allIslandApp));
|
||||||
return app;
|
return app;
|
||||||
|
|||||||
+1
-2
@@ -1,7 +1,6 @@
|
|||||||
import { App, fsRoutes, staticFiles, trailingSlashes } from "fresh";
|
import { App, fsRoutes, trailingSlashes } from "fresh";
|
||||||
|
|
||||||
export const app = new App({ root: import.meta.url })
|
export const app = new App({ root: import.meta.url })
|
||||||
.use(staticFiles())
|
|
||||||
.use(trailingSlashes("never"));
|
.use(trailingSlashes("never"));
|
||||||
|
|
||||||
await fsRoutes(app, {
|
await fsRoutes(app, {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { PageProps } from "../../../src/context.ts";
|
import type { PageProps } from "@fresh/core";
|
||||||
|
|
||||||
export default function Layout({ Component }: PageProps) {
|
export default function Layout({ Component }: PageProps) {
|
||||||
return (
|
return (
|
||||||
|
|||||||
Reference in New Issue
Block a user