Reorganize and rename various interfaces to improve consistency and make dependencies clearer; introduce a separate server-side context for handling Conduit requests
diff --git a/demo/src/DemoAPI.ts b/demo/src/DemoAPI.ts
index 3c7c567..9ba1d70 100644
--- a/demo/src/DemoAPI.ts
+++ b/demo/src/DemoAPI.ts
@@ -1,20 +1,25 @@
// Yggdrasil
// Copyright (c) jottocraft 2024
-import { YggdrasilConduitAPI } from "@jottocraft/yggdrasil";
-
// This file contains the Typescript definition for the Demo
-// Conduit API. This file could be shared to allow other projects
-// to call this API with type safety.
+// Conduit API.
-export type DemoAPI = {
+type DemoApiCtx = {
+ /** The second argument defines common context parameters passed to all Conduit API calls. */
+ name: string;
+};
+
+/** Defines the API used between the conduit client and server. Export this object from a package for cross-project type safety! */
+export type DemoApi = {
client: {
/** The first argument to YggdrasilConduitAPI defines your API functions available to the client. */
hello: (time: "morning" | "evening" | "afternoon" | "night") => Promise<string>;
goodbye: () => Promise<string>;
};
- context: {
- /** The second argument defines common context parameters passed to all Conduit API calls. */
- name: string;
- };
+ apiCtx: DemoApiCtx;
+};
+
+/** Extends DemoApi with a server-side context. Useful for including extra common processing, or non-serializable utilities that depend on apiCtx. */
+export type DemoApiServerTypes = DemoApi & {
+ conduitCtx: DemoApiCtx;
};
\ No newline at end of file
diff --git a/demo/src/api/goodbye.ts b/demo/src/api/goodbye.ts
index 3b3cb6f..fc19d92 100644
--- a/demo/src/api/goodbye.ts
+++ b/demo/src/api/goodbye.ts
@@ -1,10 +1,10 @@
// Yggdrasil
// Copyright (c) jottocraft 2024. All rights reserved.
-import { DemoServer } from "../server";
+import { defineDemoApi } from "../server";
-export const goodbye = DemoServer.defineAPI().goodbye(async (ygg) => {
+export const goodbye = defineDemoApi().goodbye(async (ygg) => {
ygg.upstreamHeaders.set["X-Test-Header"] = "X-Test-Value";
- if (!ygg.apiCtx.name) throw ygg.status(400, "BAD_REQUEST", "Missing required name parameter!");
- return "Goodbye " + ygg.apiCtx.name + "!";
+ if (!ygg.conduitCtx.name) throw ygg.status(400, "BAD_REQUEST", "Missing required name parameter!");
+ return "Goodbye " + ygg.conduitCtx.name + "!";
});
\ No newline at end of file
diff --git a/demo/src/api/hello.ts b/demo/src/api/hello.ts
index 1969727..34f0a7a 100644
--- a/demo/src/api/hello.ts
+++ b/demo/src/api/hello.ts
@@ -1,8 +1,8 @@
// Yggdrasil
// Copyright (c) jottocraft 2024. All rights reserved.
-import { DemoServer } from "../server";
+import { defineDemoApi } from "../server";
-export const hello = DemoServer.defineAPI().hello(async (ygg, time) => {
- return "Good " + time + " " + ygg.apiCtx.name + "!";
+export const hello = defineDemoApi().hello(async (ygg, time) => {
+ return "Good " + time + " " + ygg.conduitCtx.name + "!";
});
\ No newline at end of file
diff --git a/demo/src/index.ts b/demo/src/index.ts
index 0d3935b..dca92fc 100644
--- a/demo/src/index.ts
+++ b/demo/src/index.ts
@@ -3,13 +3,16 @@
import { YggdrasilConduitServer, YggdrasilServerContext, YggdrasilRouter, YggdrasilStatus, createConduitServerSideClient } from "@jottocraft/yggdrasil";
-import { DemoServer } from "./server";
+import { DemoAppTypes, DemoServer } from "./server";
import * as routes from "./routes";
import * as api from "./api";
-import { DemoAPI } from "./DemoAPI";
+import { DemoApi, DemoApiServerTypes } from "./DemoApi";
-const DemoRouter = new YggdrasilRouter(DemoServer, routes);
-const DemoConduitServer = new YggdrasilConduitServer(DemoServer, api);
+const DemoRouter = new YggdrasilRouter<DemoAppTypes>(DemoServer, routes);
+const DemoConduitServer = new YggdrasilConduitServer<DemoAppTypes, DemoApiServerTypes>(DemoServer, api, {
+ conduitBasePath: "/demo/conduit/",
+ prepareConduitCtx: async (ygg, apiCtx) => apiCtx
+});
export default {
async fetch(request: Request, env: DemoEnv, ctx: ExecutionContext): Promise<Response> {
@@ -33,12 +36,11 @@
ctx: {
env,
ctx,
- conduit: createConduitServerSideClient<DemoAPI>({ name: "jottocraft" }, { baseURL: "https://yggdrasil.ns.jottocraft.com/demo/conduit/", fetcher: (input: RequestInfo | URL, init?: RequestInit) => this.fetch(new Request(input, init), env, ctx), allowHeaderManipulation: true })
+ conduit: createConduitServerSideClient<DemoApi>({ name: "jottocraft" }, { baseURL: "https://yggdrasil.ns.jottocraft.com/demo/conduit/", fetcher: (input: RequestInfo | URL, init?: RequestInit) => this.fetch(new Request(input, init), env, ctx), allowHeaderManipulation: true })
}
}, {
debug: true,
baseURL: "https://yggdrasil.ns.jottocraft.com/demo",
- conduitBasePath: "/demo/conduit/",
normalization: {
trailingSlash: false,
lowercase: true,
diff --git a/demo/src/routes/abc.ts b/demo/src/routes/abc.ts
index a7e9bd1..4bd8eb8 100644
--- a/demo/src/routes/abc.ts
+++ b/demo/src/routes/abc.ts
@@ -1,8 +1,8 @@
// Yggdrasil
// Copyright (c) jottocraft 2024
-import { DemoServer } from "../server";
+import { defineDemoRoute } from "../server";
-export const abc = DemoServer.defineRoute("GET", "/abc", async (ygg) => {
+export const abc = defineDemoRoute("GET", "/abc", async (ygg) => {
return new Response("aardvark", { status: 200 });
});
\ No newline at end of file
diff --git a/demo/src/routes/def.ts b/demo/src/routes/def.ts
index c8417cc..a93655c 100644
--- a/demo/src/routes/def.ts
+++ b/demo/src/routes/def.ts
@@ -1,10 +1,8 @@
// Yggdrasil
// Copyright (c) jottocraft 2024
-import { YggdrasilStatus } from "@jottocraft/yggdrasil";
+import { defineDemoRoute } from "../server";
-import { DemoServer } from "../server";
-
-export const def = DemoServer.defineRoute("GET", "/def", async (ygg) => {
+export const def = defineDemoRoute("GET", "/def", async (ygg) => {
throw ygg.status(400, "INVALID_REQUEST", "Invalid request.");
});
\ No newline at end of file
diff --git a/demo/src/routes/goodbye.ts b/demo/src/routes/goodbye.ts
index 1faa1e9..99a9c25 100644
--- a/demo/src/routes/goodbye.ts
+++ b/demo/src/routes/goodbye.ts
@@ -1,9 +1,9 @@
// Yggdrasil
// Copyright (c) jottocraft 2024
-import { DemoServer } from "../server";
+import { defineDemoRoute } from "../server";
-export const goodbye = DemoServer.defineRoute("GET", "/goodbye", async (ygg) => {
+export const goodbye = defineDemoRoute("GET", "/goodbye", async (ygg) => {
const goodbyeMessage = await ygg.ctx.conduit().goodbye();
return new Response(goodbyeMessage, { status: 200 });
});
\ No newline at end of file
diff --git a/demo/src/routes/hij.ts b/demo/src/routes/hij.ts
index 900cdb6..0498150 100644
--- a/demo/src/routes/hij.ts
+++ b/demo/src/routes/hij.ts
@@ -1,8 +1,8 @@
// Yggdrasil
// Copyright (c) jottocraft 2024
-import { DemoServer } from "../server";
+import { defineDemoRoute } from "../server";
-export const hij = DemoServer.defineRoute("GET", "/hij/$message", async (ygg) => {
+export const hij = defineDemoRoute("GET", "/hij/$message", async (ygg) => {
return new Response("Message: " + ygg.params.message, { status: 200 });
});
\ No newline at end of file
diff --git a/demo/src/routes/memo.ts b/demo/src/routes/memo.ts
index d15dbce..ee9e7c5 100644
--- a/demo/src/routes/memo.ts
+++ b/demo/src/routes/memo.ts
@@ -1,14 +1,14 @@
// Yggdrasil
// Copyright (c) jottocraft 2024
-import { DemoServer } from "../server";
+import { defineDemoRoute } from "../server";
async function multiplyNumbers() {
console.log("Multiplying numbers...");
return 34 * 45;
}
-export const memo = DemoServer.defineRoute("GET", "/memo", async (ygg) => {
+export const memo = defineDemoRoute("GET", "/memo", async (ygg) => {
// Do the same thing a bunch of times to test memoization.
const data = await Promise.all([
ygg.memoize("multiplyNumbers", multiplyNumbers),
diff --git a/demo/src/routes/spacer.ts b/demo/src/routes/spacer.ts
index b6aab06..a750240 100644
--- a/demo/src/routes/spacer.ts
+++ b/demo/src/routes/spacer.ts
@@ -2,9 +2,9 @@
// Copyright (c) jottocraft 2024
import { YggdrasilSpacer } from "@jottocraft/yggdrasil";
-import { DemoServer } from "../server";
+import { defineDemoRoute } from "../server";
-export const spacer = DemoServer.defineRoute("GET", "/spacer", async (ygg) => {
+export const spacer = defineDemoRoute("GET", "/spacer", async (ygg) => {
const spacer = new YggdrasilSpacer(1000);
const tasks = [];
diff --git a/demo/src/server.ts b/demo/src/server.ts
index 4d174f9..88cf937 100644
--- a/demo/src/server.ts
+++ b/demo/src/server.ts
@@ -4,14 +4,26 @@
// This file contains the key Server and Blueprint objects
// that other files use to configure and run Yggdrasil Server.
-import { YggdrasilConduitAPIClient, YggdrasilServer } from "@jottocraft/yggdrasil";
+// IMPORTANT: To properly setup consistent type safety in your project, you should
+// define your YggdrasilAppTypes, YggdrasilConduitApi, and YggdrasilConduitServerApiTypes
+// type definitions somewhere they can be shared between files, and explicitly include them when using
+// defineApi(), defineRoute(), new YggdrasilServer(), new YggdrasilConduitServer(), and new YggdrasilRouter().
+// TypeScript can infer some of these relationships, but not all, and the errors you'll see will be extremely
+// confusing if you don't do this.
-import { DemoAPI } from "./DemoAPI";
+import { defineApi, defineRoute, YggdrasilConduitApiClient, YggdrasilServer } from "@jottocraft/yggdrasil";
-export const DemoServer = new YggdrasilServer<{
+import { DemoApi, DemoApiServerTypes } from "./DemoApi";
+
+export type DemoAppTypes = {
ctx: {
env: DemoEnv;
ctx: ExecutionContext;
- conduit: YggdrasilConduitAPIClient<DemoAPI>;
+ conduit: YggdrasilConduitApiClient<DemoApi>;
}
-}, DemoAPI>();
\ No newline at end of file
+};
+
+export const DemoServer = new YggdrasilServer<DemoAppTypes>();
+
+export const defineDemoApi = defineApi<DemoAppTypes, DemoApiServerTypes>;
+export const defineDemoRoute = defineRoute<DemoAppTypes>;
\ No newline at end of file
diff --git a/yggdrasil/package.json b/yggdrasil/package.json
index d1b8165..2d0e701 100644
--- a/yggdrasil/package.json
+++ b/yggdrasil/package.json
@@ -1,7 +1,7 @@
{
"name": "@jottocraft/yggdrasil",
"description": "A simple and flexible TypeScript library for streamlining web request handling.",
- "version": "0.0.1-alpha.12",
+ "version": "0.0.1-alpha.13",
"license": "LGPL-2.1-only",
"author": "jottocraft <[email protected]>",
"main": "lib/index.js",
diff --git a/yggdrasil/src/YggdrasilConduitServer.ts b/yggdrasil/src/YggdrasilConduitServer.ts
index 5855744..e5f189a 100644
--- a/yggdrasil/src/YggdrasilConduitServer.ts
+++ b/yggdrasil/src/YggdrasilConduitServer.ts
@@ -1,55 +1,104 @@
// Yggdrasil
// Copyright (c) jottocraft 2024
-import { YggdrasilConduitAPI, YggdrasilConduitRequest, YggdrasilConduitResponse } from "~/conduitClient";
-import { YggdrasilConduitContext, YggdrasilServerContext } from "~/context";
-import { YggdrasilAppTypes, YggdrasilServer } from "~/YggdrasilServer";
+import type { YggdrasilConduitApi, YggdrasilConduitRequest, YggdrasilConduitResponse } from "~/conduit";
+import type { YggdrasilAdditionalHeaders, YggdrasilAppTypes, YggdrasilServer, YggdrasilServerContext } from "~/YggdrasilServer";
+
+/**
+ * Types defining your Conduit API, extended with an additional server-side attributes.
+ */
+export type YggdrasilConduitServerApiTypes = YggdrasilConduitApi & {
+ /** A custom application-defined context object used to add custom attributes to YggdrasilConduitContext objects processed through your server. */
+ conduitCtx?: any;
+};
+
+/**
+ * Options to configure YggdrasilConduitServer.
+ */
+export type YggdrasilConduitServerOptions<AppTypes extends YggdrasilAppTypes, ApiTypes extends YggdrasilConduitServerApiTypes> = {
+ /**
+ * The base path used for Conduit API requests.
+ * This path IS case sensitive and will not be normalized.
+ * It must start and end with a slash.
+ * e.g. /, /conduit/, etc.
+ */
+ conduitBasePath: string;
+ /**
+ * Receives the apiCtx context passed by the Conduit client and applies any custom pre-processing you want to do
+ * before your Conduit API handlers are called. Takes a client-side apiCtx context and returns a server-side conduitCtx context.
+ */
+ prepareConduitCtx: (ygg: YggdrasilServerContext<AppTypes>, apiCtx: ApiTypes["apiCtx"]) => Promise<ApiTypes["conduitCtx"]>;
+};
+
+/**
+ * Context associated with the current Conduit API request being processed.
+ */
+export type YggdrasilConduitContext<AppTypes extends YggdrasilAppTypes, ApiTypes extends YggdrasilConduitServerApiTypes> = YggdrasilServerContext<AppTypes> & {
+ /** Headers that will be set/appended to the highest-level upstream request. */
+ upstreamHeaders: YggdrasilAdditionalHeaders;
+ /** Context from the Conduit request. */
+ conduitCtx: ApiTypes["conduitCtx"];
+};
type AnyFn = (...args: any[]) => any;
/**
* A function that executes the server's implementation of its Conduit function.
*/
-export type YggdrasilConduitAPIHandler<AppTypes extends YggdrasilAppTypes, ApiSpec extends YggdrasilConduitAPI, API extends AnyFn> = (ygg: YggdrasilConduitContext<AppTypes, ApiSpec>, ...parameters: Parameters<API>) => ReturnType<API>;
+export type YggdrasilConduitApiHandler<AppTypes extends YggdrasilAppTypes, ApiTypes extends YggdrasilConduitServerApiTypes, Api extends AnyFn> = (ygg: YggdrasilConduitContext<AppTypes, ApiTypes>, ...parameters: Parameters<Api>) => ReturnType<Api>;
/**
* An object that stores the server's Conduit function implementations.
*/
-export type YggdrasilConduitApiClientImpl<AppTypes extends YggdrasilAppTypes, ApiSpec extends YggdrasilConduitAPI> = {
- [Property in keyof ApiSpec["client"]]: ApiSpec["client"][Property] extends AnyFn ? YggdrasilConduitAPIHandler<AppTypes, ApiSpec, ApiSpec["client"][Property]> : YggdrasilConduitApiClientImpl<AppTypes, Omit<ApiSpec, "client"> & { client: ApiSpec["client"][Property] }>;
+export type YggdrasilConduitApiClientImpl<AppTypes extends YggdrasilAppTypes, ApiTypes extends YggdrasilConduitServerApiTypes> = {
+ [Property in keyof ApiTypes["client"]]: ApiTypes["client"][Property] extends AnyFn ? YggdrasilConduitApiHandler<AppTypes, ApiTypes, ApiTypes["client"][Property]> : YggdrasilConduitApiClientImpl<AppTypes, Omit<ApiTypes, "client"> & { client: ApiTypes["client"][Property] }>;
};
/**
* A helper object for defining Conduit function implementations with automatic type safety.
*/
-export type YggdrasilConduitApiClientBlueprint<AppTypes extends YggdrasilAppTypes, ApiSpec extends YggdrasilConduitAPI> = {
- [Property in keyof ApiSpec["client"]]: ApiSpec["client"][Property] extends AnyFn ? (impl: YggdrasilConduitAPIHandler<AppTypes, ApiSpec, ApiSpec["client"][Property]>) => YggdrasilConduitAPIHandler<AppTypes, ApiSpec, ApiSpec["client"][Property]> : YggdrasilConduitApiClientBlueprint<AppTypes, Omit<ApiSpec, "client"> & { client: ApiSpec["client"][Property] }>;
+export type YggdrasilConduitApiClientBlueprint<AppTypes extends YggdrasilAppTypes, ApiTypes extends YggdrasilConduitServerApiTypes> = {
+ [Property in keyof ApiTypes["client"]]: ApiTypes["client"][Property] extends AnyFn ? (impl: YggdrasilConduitApiHandler<AppTypes, ApiTypes, ApiTypes["client"][Property]>) => YggdrasilConduitApiHandler<AppTypes, ApiTypes, ApiTypes["client"][Property]> : YggdrasilConduitApiClientBlueprint<AppTypes, Omit<ApiTypes, "client"> & { client: ApiTypes["client"][Property] }>;
};
/**
* Internal type for recursing through arbitrary segments in the API object.
*/
-type APISegment<AppTypes extends YggdrasilAppTypes, ApiSpec extends YggdrasilConduitAPI> = {
- [segment: string]: APISegment<AppTypes, ApiSpec> | YggdrasilConduitAPIHandler<AppTypes, ApiSpec, AnyFn>;
+type ApiSegment<AppTypes extends YggdrasilAppTypes, ApiTypes extends YggdrasilConduitServerApiTypes> = {
+ [segment: string]: ApiSegment<AppTypes, ApiTypes> | YggdrasilConduitApiHandler<AppTypes, ApiTypes, AnyFn>;
};
/**
+ * A helper for defining API routes with type safety.
+ */
+export function defineApi<AppTypes extends YggdrasilAppTypes, ApiTypes extends YggdrasilConduitServerApiTypes = { client: unknown; }>(): YggdrasilConduitApiClientBlueprint<AppTypes, ApiTypes> {
+ const implProxy = new Proxy((impl: unknown) => impl, {
+ get: (target, name) => {
+ return implProxy;
+ }
+ }) as any;
+
+ return implProxy;
+}
+
+/**
* A server for handling Conduit requests made to Yggdrasil Server.
*/
-export class YggdrasilConduitServer<AppTypes extends YggdrasilAppTypes, ApiSpec extends YggdrasilConduitAPI> {
- constructor(server: YggdrasilServer<AppTypes, ApiSpec>, api: YggdrasilConduitApiClientImpl<AppTypes, ApiSpec>) {
+export class YggdrasilConduitServer<AppTypes extends YggdrasilAppTypes, ApiTypes extends YggdrasilConduitServerApiTypes> {
+ constructor(server: YggdrasilServer<AppTypes>, api: YggdrasilConduitApiClientImpl<AppTypes, ApiTypes>, options: YggdrasilConduitServerOptions<AppTypes, ApiTypes>) {
this.#server = server;
this.#api = api;
+ this.#options = options;
}
async handleRequest(ygg: YggdrasilServerContext<AppTypes>): Promise<Response> {
- if (!ygg.options.conduitBasePath) throw ygg.status(500, "YGG_BADLY_CONFIGURED", "conduitBasePath must be configured to use Yggdrasil Server Conduit.");
+ if (!this.#options.conduitBasePath) throw ygg.status(500, "YGG_BADLY_CONFIGURED", "conduitBasePath must be configured to use Yggdrasil Server Conduit.");
- let requestedPath = ygg.pathname.requested.replace(ygg.options.conduitBasePath, "");
- if (!ygg.pathname.requested.startsWith(ygg.options.conduitBasePath) || (requestedPath === "/") || requestedPath.endsWith("/")) throw ygg.status(404, "YGG_API_NOT_FOUND", "The requested API can't be located.");
+ let requestedPath = ygg.pathname.requested.replace(this.#options.conduitBasePath, "");
+ if (!ygg.pathname.requested.startsWith(this.#options.conduitBasePath) || (requestedPath === "/") || requestedPath.endsWith("/")) throw ygg.status(404, "YGG_API_NOT_FOUND", "The requested API can't be located.");
- let requestedApiSegment = this.#api as APISegment<AppTypes, ApiSpec>;
- let requestedApi: YggdrasilConduitAPIHandler<AppTypes, ApiSpec, AnyFn> | undefined;
+ let requestedApiSegment = this.#api as ApiSegment<AppTypes, ApiTypes>;
+ let requestedApi: YggdrasilConduitApiHandler<AppTypes, ApiTypes, AnyFn> | undefined;
const segments = requestedPath.split("/");
for (const segment of segments) {
@@ -65,7 +114,7 @@
if (requestedApi) {
if (ygg.request.headers.get("Content-Type") !== "application/json+jottocraft-ygg-req") throw ygg.status(400, "YGG_BAD_API_REQUEST", "Badly formatted Conduit request.");
- let request: YggdrasilConduitRequest<ApiSpec["context"], unknown[]>;
+ let request: YggdrasilConduitRequest<ApiTypes["apiCtx"], unknown[]>;
try {
request = await ygg.request.json();
} catch (e) {
@@ -74,13 +123,15 @@
if (!request.parameters || !(request.parameters instanceof Array)) throw ygg.status(400, "YGG_BAD_API_REQUEST", "Badly formatted Conduit request.");
+ const conduitCtx = await this.#options.prepareConduitCtx(ygg, request.context);
+
const yggConduitCtx = {
upstreamHeaders: {
set: {},
append: []
},
- apiCtx: request.context
- } satisfies Omit<YggdrasilConduitContext<AppTypes, ApiSpec>, keyof YggdrasilServerContext<AppTypes>> as unknown as YggdrasilConduitContext<AppTypes, ApiSpec>;
+ conduitCtx
+ } satisfies Omit<YggdrasilConduitContext<AppTypes, ApiTypes>, keyof YggdrasilServerContext<AppTypes>> as unknown as YggdrasilConduitContext<AppTypes, ApiTypes>;
Object.setPrototypeOf(yggConduitCtx, ygg);
const data = await requestedApi(yggConduitCtx, ...request.parameters);
@@ -103,5 +154,6 @@
}
#server: YggdrasilServer<AppTypes>;
- #api: YggdrasilConduitApiClientImpl<AppTypes, ApiSpec>;
+ #api: YggdrasilConduitApiClientImpl<AppTypes, ApiTypes>;
+ #options: YggdrasilConduitServerOptions<AppTypes, ApiTypes>;
};
\ No newline at end of file
diff --git a/yggdrasil/src/YggdrasilRouter.ts b/yggdrasil/src/YggdrasilRouter.ts
index 2a77ef0..316d2be 100644
--- a/yggdrasil/src/YggdrasilRouter.ts
+++ b/yggdrasil/src/YggdrasilRouter.ts
@@ -1,8 +1,15 @@
// Yggdrasil
// Copyright (c) jottocraft 2024
-import { YggdrasilRouterContext, YggdrasilServerContext } from "~/context";
-import { YggdrasilAppTypes, YggdrasilServer } from "~/YggdrasilServer";
+import type { YggdrasilAppTypes, YggdrasilServer, YggdrasilServerContext } from "~/YggdrasilServer";
+
+/**
+ * Context associated with the current route being processed.
+ */
+export type YggdrasilRouterContext<AppTypes extends YggdrasilAppTypes> = YggdrasilServerContext<AppTypes> & {
+ /** The parameters set by variable segments in the router's path. */
+ params: YggdrasilRouterRequestParams;
+};
/**
* An object that represents the route configuration made by YggdrasilServer.defineRoute().
@@ -37,6 +44,13 @@
export type YggdrasilRouterHandler<AppTypes extends YggdrasilAppTypes> = (ygg: YggdrasilRouterContext<AppTypes>) => Promise<Response>;
/**
+ * Defines a route to use with YggdrasilRouter.
+ */
+export function defineRoute<AppTypes extends YggdrasilAppTypes>(method: string, route: string, handler: YggdrasilRouterHandler<AppTypes>): YggdrasilRouteConfig<AppTypes> {
+ return { method, route, handler };
+}
+
+/**
* A server for routing requests made to YggdrasilServer.
*/
export class YggdrasilRouter<AppTypes extends YggdrasilAppTypes> {
@@ -56,9 +70,9 @@
registeredPath = registeredPath.children[segment];
}
}
-
+
registeredPath.handlers ??= {};
- registeredPath.handlers[route.method] = route.handler;
+ registeredPath.handlers[route.method] = route.handler;
}
}
@@ -81,14 +95,14 @@
if (requestedPath.handlers) {
const yggRouterCtx = { params } as YggdrasilRouterContext<AppTypes>;
Object.setPrototypeOf(yggRouterCtx, ygg);
-
+
if (requestedPath.handlers[ygg.request.method]) {
return requestedPath.handlers[ygg.request.method](yggRouterCtx);
} else if (requestedPath.handlers["*"]) {
return requestedPath.handlers["*"](yggRouterCtx);
} else {
throw ygg.status(405, "YGG_ROUTE_METHOD_MISMATCH", "The requested page can't be loaded with the requested method.");
- }
+ }
} else {
throw ygg.status(404, "YGG_ROUTE_NOT_FOUND", "The requested page can't be located.");
}
diff --git a/yggdrasil/src/YggdrasilServer.ts b/yggdrasil/src/YggdrasilServer.ts
index 52a2d66..8566358 100644
--- a/yggdrasil/src/YggdrasilServer.ts
+++ b/yggdrasil/src/YggdrasilServer.ts
@@ -1,24 +1,88 @@
// Yggdrasil
// Copyright (c) jottocraft 2024
-import { applyHeaders } from "~/util/applyHeaders";
import { generateStatusPage } from "~/util/generateStatusPage";
-
-import { YggdrasilServerContext, YggdrasilServerContextOptions } from "~/context";
-import { YggdrasilRouteConfig, YggdrasilRouterHandler } from "~/YggdrasilRouter";
-import { YggdrasilStatus } from "~/YggdrasilStatus";
-import { YggdrasilConduitApiClientBlueprint } from "~/YggdrasilConduitServer";
-import { YggdrasilConduitAPI } from "~/conduitClient";
+import { YggdrasilStatus, type YggdrasilStatusOptions } from "~/YggdrasilStatus";
/**
* Defines the app's types.
*/
export type YggdrasilAppTypes = {
+ /** A custom application-defined context object used to add custom attributes to YggdrasilContext objects processed through your server. */
ctx?: any;
+ /** A custom application-defined context object used to add custom attributes to YggdrasilStatus objects thrown in your server. */
statusCtx?: any;
};
/**
+ * Options to configure YggdrasilServer.
+ */
+export type YggdrasilServerOptions<AppTypes extends YggdrasilAppTypes> = {
+ /** True if debug information should be returned on the status pages. */
+ debug?: boolean;
+ /**
+ * The base external URL handled by this server, without a trailing slash, e.g. https://jottocraft.com, https://jottocraft.com/app.
+ * All requests must have a pathname that's prefixed with the pathname of this base URL, or an error will be thrown.
+ * The host and scheme do not have to match, however, e.g. if using a reverse proxy.
+ * The case should match your normalization.lowercase setting.
+ */
+ baseURL?: string;
+ /** Configures URL path normalization. */
+ normalization?: {
+ /** True if paths should have trailing slashes, e.g. /page/ instead of /page. False if they should not. Undefined if normalization should not be performed. */
+ trailingSlash?: boolean;
+ /** True if paths should be all lowercase, e.g. /page instead of /Page or /PaGe. */
+ lowercase?: boolean;
+ /** True if a redirect should be performed if the normalized path does not match the actual requested path. */
+ redirect?: boolean;
+ };
+ /** A function you can implement to generate HTML status pages for a given YggdrasilStatus object. By default, a plaintext status page will be shown. */
+ generateHtmlStatusPage?: (e: YggdrasilStatus<AppTypes>) => Promise<Response>;
+};
+
+/**
+ * Context associated with the current request being processed.
+ */
+export type YggdrasilServerContext<AppTypes extends YggdrasilAppTypes> = {
+ /** Constructs a YggdrasilStatus object based on the current context. */
+ status: (status: number, statusCode: string, messageOrOptions?: string | YggdrasilStatusOptions<AppTypes["statusCtx"]>) => YggdrasilStatus<AppTypes>;
+ /** Throws a YggdrasilStatus if the condition isn't met. */
+ assert: (condition: any, status: number, statusCode: string, messageOrOptions?: string | YggdrasilStatusOptions<AppTypes["statusCtx"]>) => asserts condition;
+ /** The Yggdrasil Server instance associated with this request. */
+ server: YggdrasilServer<AppTypes>;
+ /** The original request. */
+ request: Request;
+ /** The requested and normalized URLs. */
+ url: {
+ requested: URL;
+ normalized: URL;
+ };
+ /** The requested, normalized, and normalized relative (to the base URL) pathnames. */
+ pathname: {
+ requested: string;
+ normalized: string;
+ relative: string;
+ };
+ /** This server's base URL. */
+ baseURL?: URL;
+ /** Custom app context associated with this request. */
+ ctx: AppTypes["ctx"];
+ /** Yggdrasil Server options. */
+ options: YggdrasilServerOptions<AppTypes>;
+ /** Headers that will be set or appended to the final response. */
+ additionalHeaders: YggdrasilAdditionalHeaders;
+ /** Memoizes the result. */
+ memoize: <T>(key: string, task: () => Promise<T>) => Promise<T>;
+ /** Returns true if the requested task has been completed and its result is immediately available. */
+ hasMemoizedResult: (key: string) => boolean;
+ /**
+ * Returns stored memoized results. Useful if you need to save/restore state without redoing memoized work.
+ * Restore only via handleRequest's memoizedResults app option. The format of the returned value is opaque and subject to change.
+ */
+ getMemoizedResults: () => unknown;
+};
+
+/**
* Data passed by the app to initialize the YggdrasilServer instance.
*/
export type YggdrasilAppData<AppTypes extends YggdrasilAppTypes> = {
@@ -29,6 +93,14 @@
};
/**
+ * Additional headers to set/append to the final response after processing the request.
+ */
+export type YggdrasilAdditionalHeaders = {
+ set: { [headerName: string]: string; };
+ append: string[][];
+};
+
+/**
* Memoized functions.
*/
export type YggdrasilMemoizedFunctions = {
@@ -46,35 +118,28 @@
type MemoizedResultsInternal = { [key: string]: { resolved: false; dispatcher: EventTarget; } | { resolved: true; outcome: unknown; }; }
/**
+ * Applies header modifications to a Response.
+ */
+export function applyHeaders(response: Response, additionalHeaders: YggdrasilAdditionalHeaders) {
+ for (const name in additionalHeaders.set) {
+ response.headers.set(name, additionalHeaders.set[name]);
+ }
+
+ for (const [name, value] of additionalHeaders.append) {
+ response.headers.append(name, value);
+ }
+}
+
+/**
* The main class for processing requests.
*/
-export class YggdrasilServer<AppTypes extends YggdrasilAppTypes, ApiSpec extends YggdrasilConduitAPI = { client: unknown; context: unknown; }> {
+export class YggdrasilServer<AppTypes extends YggdrasilAppTypes> {
constructor() { }
/**
- * Defines a route to use with YggdrasilRouter.
- */
- defineRoute(method: string, route: string, handler: YggdrasilRouterHandler<AppTypes>): YggdrasilRouteConfig<AppTypes> {
- return { method, route, handler };
- }
-
- /**
- * Defines an API to use with YggdrasilConduitServer.
- */
- defineAPI(): YggdrasilConduitApiClientBlueprint<AppTypes, ApiSpec> {
- const implProxy = new Proxy((impl: unknown) => impl, {
- get: (target, name) => {
- return implProxy;
- }
- }) as any;
-
- return implProxy;
- }
-
- /**
* Handles a request.
*/
- async handleRequest(request: Request, handler: YggdrasilHandler<AppTypes>, app: YggdrasilAppData<AppTypes>, options: YggdrasilServerContextOptions<AppTypes> = {}): Promise<Response> {
+ async handleRequest(request: Request, handler: YggdrasilHandler<AppTypes>, app: YggdrasilAppData<AppTypes>, options: YggdrasilServerOptions<AppTypes> = {}): Promise<Response> {
const url = new URL(request.url);
const baseURL = options.baseURL ? new URL(options.baseURL) : undefined;
diff --git a/yggdrasil/src/conduit.ts b/yggdrasil/src/conduit.ts
new file mode 100644
index 0000000..5b56774
--- /dev/null
+++ b/yggdrasil/src/conduit.ts
@@ -0,0 +1,36 @@
+// Yggdrasil
+// Copyright (c) jottocraft 2025
+
+import type { YggdrasilContext } from "~/context";
+import type { YggdrasilAdditionalHeaders, YggdrasilAppTypes } from "~/YggdrasilServer";
+
+export type YggdrasilConduitApi = {
+ client: any;
+ apiCtx?: any;
+};
+
+export type YggdrasilConduitRequest<ApiCtx, T extends unknown[]> = {
+ parameters: T;
+ context: ApiCtx;
+};
+
+export type YggdrasilConduitResponse<T> = YggdrasilConduitResponseSuccess<T> | YggdrasilConduitResponseError;
+
+export type YggdrasilConduitResponseCommon = {
+ headers: YggdrasilAdditionalHeaders;
+};
+
+export type YggdrasilConduitResponseSuccess<T> = YggdrasilConduitResponseCommon & {
+ success: true;
+ data: T;
+};
+
+export type YggdrasilConduitResponseError = YggdrasilConduitResponseCommon & {
+ success: false;
+ error: string;
+ message?: string;
+ debug?: {
+ stack?: string;
+ ygg?: Pick<YggdrasilContext<YggdrasilAppTypes>, "url" | "pathname" | "baseURL" | "additionalHeaders">;
+ };
+};
\ No newline at end of file
diff --git a/yggdrasil/src/conduitClient.ts b/yggdrasil/src/conduitClient.ts
index 0fba96b..d841a66 100644
--- a/yggdrasil/src/conduitClient.ts
+++ b/yggdrasil/src/conduitClient.ts
@@ -1,52 +1,10 @@
// Yggdrasil
// Copyright (c) jottocraft 2024
-import { YggdrasilContext } from "~/context";
+import type { YggdrasilConduitApi, YggdrasilConduitRequest, YggdrasilConduitResponse } from "~/conduit";
+import type { YggdrasilContext } from "~/context";
import { YggdrasilClientStatus } from "~/YggdrasilStatus";
-import { YggdrasilAppTypes } from "~/YggdrasilServer";
-
-export type YggdrasilConduitAPI = {
- client: any;
- context: any;
-};
-
-// TODO: For now, the fact that YggdrasilConduitAPIClient requires the "this" context to be
-// of type YggdrasilContext is hidden. This is because it is difficult to redefine with
-// "this" set since YggdrasilContext and YggdrasilConduitAPIClient would both depend on each other.
-
-export type YggdrasilConduitAPIClient<ApiSpec extends YggdrasilConduitAPI> = () => ApiSpec["client"];
-export type YggdrasilConduitAPIContext<ApiSpec extends YggdrasilConduitAPI> = ApiSpec["context"];
-
-export type YggdrasilConduitRequest<ApiCtx, T extends unknown[]> = {
- parameters: T;
- context: ApiCtx;
-};
-
-export type YggdrasilConduitResponse<T> = YggdrasilConduitResponseSuccess<T> | YggdrasilConduitResponseError;
-
-export type YggdrasilConduitResponseCommon = {
- headers: YggdrasilAdditionalHeaders;
-};
-
-export type YggdrasilAdditionalHeaders = {
- set: { [headerName: string]: string; };
- append: string[][];
-};
-
-export type YggdrasilConduitResponseSuccess<T> = YggdrasilConduitResponseCommon & {
- success: true;
- data: T;
-};
-
-export type YggdrasilConduitResponseError = YggdrasilConduitResponseCommon & {
- success: false;
- error: string;
- message?: string;
- debug?: {
- stack?: string;
- ygg?: Pick<YggdrasilContext<YggdrasilAppTypes>, "url" | "pathname" | "baseURL" | "additionalHeaders">;
- };
-};
+import type { YggdrasilAdditionalHeaders, YggdrasilAppTypes } from "~/YggdrasilServer";
export type YggdrasilConduitClientOptions = {
/**
@@ -59,6 +17,8 @@
baseURL: string;
};
+export type YggdrasilConduitApiClient<ApiSpec extends YggdrasilConduitApi> = () => ApiSpec["client"];
+
export type YggdrasilConduitServerSideClientOptions = YggdrasilConduitClientOptions & {
/**
* Set to true to allow the connected Conduit server to manipulate headers on the highest-level response.
@@ -66,7 +26,7 @@
allowHeaderManipulation?: boolean;
};
-async function doConduitRequest<ApiSpec extends YggdrasilConduitAPI>(path: string[], args: unknown[], apiCtx: ApiSpec["context"], options: YggdrasilConduitClientOptions): Promise<{
+async function doConduitRequest<ApiSpec extends YggdrasilConduitApi>(path: string[], args: unknown[], apiCtx: ApiSpec["apiCtx"], options: YggdrasilConduitClientOptions): Promise<{
response: Response;
outcome: YggdrasilConduitResponse<unknown>;
}> {
@@ -75,7 +35,7 @@
const callURL = new URL(options.baseURL);
callURL.pathname = callURL.pathname + path.join("/");
- const request: YggdrasilConduitRequest<ApiSpec["context"], unknown[]> = {
+ const request: YggdrasilConduitRequest<ApiSpec["apiCtx"], unknown[]> = {
parameters: args,
context: apiCtx
};
@@ -101,7 +61,7 @@
/**
* Creates a client for calling Yggdrasil Server Conduit-powered APIs from another Yggdrasil Server-powered web or API server.
*/
-export function createConduitServerSideClient<ApiSpec extends YggdrasilConduitAPI>(apiCtx: ApiSpec["context"], options: YggdrasilConduitServerSideClientOptions): YggdrasilConduitAPIClient<ApiSpec> {
+export function createConduitServerSideClient<ApiSpec extends YggdrasilConduitApi>(apiCtx: ApiSpec["apiCtx"], options: YggdrasilConduitServerSideClientOptions): YggdrasilConduitApiClient<ApiSpec> {
return function conduitServerSideClient(this: YggdrasilContext<YggdrasilAppTypes>): ApiSpec["client"] {
const createAppFn = (path: string[]) => {
return new Proxy(async (...args: unknown[]) => {
@@ -139,22 +99,25 @@
/**
* Creates a client for calling Yggdrasil Server Conduit-powered APIs from a client application.
*/
-export function createConduitClientSideClient<ApiSpec extends YggdrasilConduitAPI>(apiCtx: ApiSpec["context"], options: YggdrasilConduitClientOptions): YggdrasilConduitAPIClient<ApiSpec> {
- const createAppFn = (path: string[]) => {
- return new Proxy(async (...args: unknown[]) => {
- const { response, outcome } = await doConduitRequest(path, args, apiCtx, options);
+export function createConduitClientSideClient<ApiSpec extends YggdrasilConduitApi>(apiCtx: ApiSpec["apiCtx"], options: YggdrasilConduitClientOptions): YggdrasilConduitApiClient<ApiSpec> {
+ // This nested function isn't technically necessary client-side, but it keeps the client-side and server-side clients consistent.
+ return function conduitClientSideClient(): ApiSpec["client"] {
+ const createAppFn = (path: string[]) => {
+ return new Proxy(async (...args: unknown[]) => {
+ const { response, outcome } = await doConduitRequest(path, args, apiCtx, options);
- if (outcome.success) {
- return outcome.data;
- } else {
- throw new YggdrasilClientStatus(response.status, outcome.error, outcome.message);
- }
- }, {
- get(target, name: string) {
- return createAppFn([...path, name]);
- }
- });
+ if (outcome.success) {
+ return outcome.data;
+ } else {
+ throw new YggdrasilClientStatus(response.status, outcome.error, outcome.message);
+ }
+ }, {
+ get(target, name: string) {
+ return createAppFn([...path, name]);
+ }
+ });
+ }
+
+ return createAppFn([]) as ApiSpec["client"];
}
-
- return createAppFn([]) as ApiSpec["client"];
}
\ No newline at end of file
diff --git a/yggdrasil/src/context.ts b/yggdrasil/src/context.ts
index 8ae9f59..98e9131 100644
--- a/yggdrasil/src/context.ts
+++ b/yggdrasil/src/context.ts
@@ -1,90 +1,8 @@
// Yggdrasil
// Copyright (c) jottocraft 2024
-import { YggdrasilAdditionalHeaders, YggdrasilConduitAPI, YggdrasilConduitAPIContext } from "~/conduitClient";
-import { YggdrasilRouterRequestParams } from "~/YggdrasilRouter";
-import { YggdrasilAppTypes, YggdrasilServer } from "~/YggdrasilServer";
-import { YggdrasilStatus, YggdrasilStatusOptions } from "~/YggdrasilStatus";
+import type { YggdrasilConduitContext } from "~/YggdrasilConduitServer";
+import type { YggdrasilRouterContext } from "~/YggdrasilRouter";
+import type { YggdrasilAppTypes, YggdrasilServerContext } from "~/YggdrasilServer";
-export type YggdrasilServerContextOptions<AppTypes extends YggdrasilAppTypes> = {
- /** True if debug information should be returned on the status pages. */
- debug?: boolean;
- /**
- * The base external URL handled by this server, without a trailing slash, e.g. https://jottocraft.com, https://jottocraft.com/app.
- * All requests must have a pathname that's prefixed with the pathname of this base URL, or an error will be thrown.
- * The host and scheme do not have to match, however, e.g. if using a reverse proxy.
- * The case should match your normalization.lowercase setting.
- */
- baseURL?: string;
- /**
- * The base path used for Conduit API requests. This MUST be specified if you are using Conduit.
- * This path IS case sensitive and will not be normalized.
- * It must start and end with a slash.
- * e.g. /, /conduit/, etc.
- */
- conduitBasePath?: string;
- /** Configures URL path normalization. */
- normalization?: {
- /** True if paths should have trailing slashes, e.g. /page/ instead of /page. False if they should not. Undefined if normalization should not be performed. */
- trailingSlash?: boolean;
- /** True if paths should be all lowercase, e.g. /page instead of /Page or /PaGe. */
- lowercase?: boolean;
- /** True if a redirect should be performed if the normalized path does not match the actual requested path. */
- redirect?: boolean;
- };
- /** A function you can implement to generate HTML status pages for a given YggdrasilStatus object. By default, a plaintext status page will be shown. */
- generateHtmlStatusPage?: (e: YggdrasilStatus<AppTypes>) => Promise<Response>;
-};
-
-export type YggdrasilContext<AppTypes extends YggdrasilAppTypes> = YggdrasilServerContext<AppTypes> | YggdrasilRouterContext<AppTypes> | YggdrasilConduitContext<AppTypes, { client: unknown; context: unknown; }>;
-
-export type YggdrasilServerContext<AppTypes extends YggdrasilAppTypes> = {
- /** Constructs a YggdrasilStatus object based on the current context. */
- status: (status: number, statusCode: string, messageOrOptions?: string | YggdrasilStatusOptions<AppTypes["statusCtx"]>) => YggdrasilStatus<AppTypes>;
- /** Throws a YggdrasilStatus if the condition isn't met. */
- assert: (condition: any, status: number, statusCode: string, messageOrOptions?: string | YggdrasilStatusOptions<AppTypes["statusCtx"]>) => asserts condition;
- /** The Yggdrasil Server instance associated with this request. */
- server: YggdrasilServer<AppTypes>;
- /** The original request. */
- request: Request;
- /** The requested and normalized URLs. */
- url: {
- requested: URL;
- normalized: URL;
- };
- /** The requested, normalized, and normalized relative (to the base URL) pathnames. */
- pathname: {
- requested: string;
- normalized: string;
- relative: string;
- };
- /** This server's base URL. */
- baseURL?: URL;
- /** Custom app context associated with this request. */
- ctx: AppTypes["ctx"];
- /** Yggdrasil Server options. */
- options: YggdrasilServerContextOptions<AppTypes>;
- /** Headers that will be set/appended to the final response. */
- additionalHeaders: YggdrasilAdditionalHeaders;
- /** Memoizes the result. */
- memoize: <T>(key: string, task: () => Promise<T>) => Promise<T>;
- /** Returns true if the requested task has been completed and its result is immediately available. */
- hasMemoizedResult: (key: string) => boolean;
- /**
- * Returns stored memoized results. Useful if you need to save/restore state without redoing memoized work.
- * Restore only via handleRequest's memoizedResults app option. The format of the returned value is opaque and subject to change.
- */
- getMemoizedResults: () => unknown;
-};
-
-export type YggdrasilRouterContext<AppTypes extends YggdrasilAppTypes> = YggdrasilServerContext<AppTypes> & {
- /** The parameters set by variable segments in the router's path. */
- params: YggdrasilRouterRequestParams;
-};
-
-export type YggdrasilConduitContext<AppTypes extends YggdrasilAppTypes, ApiSpec extends YggdrasilConduitAPI> = YggdrasilServerContext<AppTypes> & {
- /** Headers that will be set/appended to the highest-level upstream request. */
- upstreamHeaders: YggdrasilAdditionalHeaders;
- /** Context from the Conduit request. */
- apiCtx: YggdrasilConduitAPIContext<ApiSpec>;
-};
\ No newline at end of file
+export type YggdrasilContext<AppTypes extends YggdrasilAppTypes> = YggdrasilServerContext<AppTypes> | YggdrasilRouterContext<AppTypes> | YggdrasilConduitContext<AppTypes, { client: unknown; }>;
\ No newline at end of file
diff --git a/yggdrasil/src/index.ts b/yggdrasil/src/index.ts
index f511a3f..3d60caf 100644
--- a/yggdrasil/src/index.ts
+++ b/yggdrasil/src/index.ts
@@ -1,6 +1,7 @@
// Yggdrasil
// Copyright (c) jottocraft 2024
+export * from "~/conduit";
export * from "~/conduitClient";
export * from "~/context";
export * from "~/YggdrasilConduitServer";
@@ -9,5 +10,4 @@
export * from "~/YggdrasilSpacer";
export * from "~/YggdrasilStatus";
-export * from "~/util/applyHeaders";
export * from "~/util/generateStatusPage";
\ No newline at end of file
diff --git a/yggdrasil/src/util/applyHeaders.ts b/yggdrasil/src/util/applyHeaders.ts
deleted file mode 100644
index 27b0bd8..0000000
--- a/yggdrasil/src/util/applyHeaders.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-// Yggdrasil
-// Copyright (c) jottocraft 2024
-
-import { YggdrasilAdditionalHeaders } from "~/conduitClient";
-
-export function applyHeaders(response: Response, additionalHeaders: YggdrasilAdditionalHeaders) {
- for (const name in additionalHeaders.set) {
- response.headers.set(name, additionalHeaders.set[name]);
- }
-
- for (const [name, value] of additionalHeaders.append) {
- response.headers.append(name, value);
- }
-}
\ No newline at end of file
diff --git a/yggdrasil/src/util/generateStatusPage.ts b/yggdrasil/src/util/generateStatusPage.ts
index 6304c80..4c016b0 100644
--- a/yggdrasil/src/util/generateStatusPage.ts
+++ b/yggdrasil/src/util/generateStatusPage.ts
@@ -1,10 +1,13 @@
// Yggdrasil
// Copyright (c) jottocraft 2024
-import { YggdrasilConduitResponseError } from "~/conduitClient";
-import { YggdrasilAppTypes } from "~/YggdrasilServer";
-import { YggdrasilStatus } from "~/YggdrasilStatus";
+import type { YggdrasilConduitResponseError } from "~/conduit";
+import type { YggdrasilAppTypes } from "~/YggdrasilServer";
+import type { YggdrasilStatus } from "~/YggdrasilStatus";
+/**
+ * Generates a status page for an uncaught YggdrasilStatus exception.
+ */
export async function generateStatusPage<AppTypes extends YggdrasilAppTypes>(e: YggdrasilStatus<AppTypes>): Promise<Response> {
const accept = e.ygg?.request.headers.get("Accept");
@@ -19,6 +22,9 @@
}
}
+/**
+ * Formats an uncaught YggdrasilStatus exception to be passed to a Conduit client.
+ */
async function generateConduitErrorPage<AppTypes extends YggdrasilAppTypes>(e: YggdrasilStatus<AppTypes>): Promise<Response> {
const result: YggdrasilConduitResponseError = {
success: false,
@@ -47,6 +53,9 @@
});
}
+/**
+ * Generates a JSON status page for an uncaught YggdrasilStatus exception.
+ */
async function generateJsonStatusPage<AppTypes extends YggdrasilAppTypes>(e: YggdrasilStatus<AppTypes>): Promise<Response> {
return new Response(JSON.stringify({
success: false,
@@ -61,6 +70,9 @@
});
}
+/**
+ * Generates a human-readable plaintext status page for an uncaught YggdrasilStatus exception.
+ */
async function generatePlaintextStatusPage<AppTypes extends YggdrasilAppTypes>(e: YggdrasilStatus<AppTypes>): Promise<Response> {
return new Response(`Error ${e.status} ${e.statusCode}${e.statusMessage ? ": " + e.statusMessage : ""}`, {
status: e.status,