Rework interface names and dependencies; update logo and documentation
diff --git a/demo/src/index.ts b/demo/src/index.ts
index dca92fc..567790c 100644
--- a/demo/src/index.ts
+++ b/demo/src/index.ts
@@ -1,7 +1,7 @@
// Yggdrasil
// Copyright (c) jottocraft 2024
-import { YggdrasilConduitServer, YggdrasilServerContext, YggdrasilRouter, YggdrasilStatus, createConduitServerSideClient } from "@jottocraft/yggdrasil";
+import { YggdrasilConduitServer, YggdrasilServerContext, YggdrasilRouter, YggdrasilServerStatus, createConduitServerSideClient } from "@jottocraft/yggdrasil";
import { DemoAppTypes, DemoServer } from "./server";
import * as routes from "./routes";
@@ -22,13 +22,13 @@
try {
return await DemoConduitServer.handleRequest(ygg);
} catch (e) {
- if (!(e instanceof YggdrasilStatus) || (e.status !== 404)) throw e;
+ if (!(e instanceof YggdrasilServerStatus) || (e.status !== 404)) throw e;
}
try {
return await DemoRouter.handleRequest(ygg);
} catch (e) {
- if (!(e instanceof YggdrasilStatus) || (e.status !== 404)) throw e;
+ if (!(e instanceof YggdrasilServerStatus) || (e.status !== 404)) throw e;
}
throw ygg.status(404, "INVALID_PATH", "Nobody was able to handle your request :(");
diff --git a/docs/docs/features/conduit.md b/docs/docs/features/conduit.md
index ba0a76c..d6c169c 100644
--- a/docs/docs/features/conduit.md
+++ b/docs/docs/features/conduit.md
@@ -49,9 +49,10 @@
At runtime, the client constructs functions dynamically, so nothing stops it from making invalid requests.
For example, TypeScript would stop you from calling `client.this.path.does.not.exist()`,
but this would work at runtime for any arbitrary path (this example makes a request to `/this/path/does/not/exist`).
-- The Conduit server client must be called from a Yggdrasil context. This means that you must include it as
- a top-level function in your ctx, and call it via ygg.ctx.\<the name of your conduit client\>().
- Please refer to the "Context" documentation for more information.
+- The Yggdrasil Conduit server-side client must be bound to a Yggdrasil context. The intention is for Conduit clients to
+ be top-level functions in your `ctx` or `conduitCtx`, and called via ygg.ctx.\<the name of your conduit client\>(). If
+ you need to create and use a Yggdrasil Conduit server-side client outside of `ygg.ctx`, please use `.bind(ygg)`, being
+ careful to follow the rules described in the "Context" documentation.
## Implementation
@@ -62,15 +63,15 @@
involve putting it in an NPM package, git submodule, etc.
```ts title="my-shared-library/conduit.ts"
-// This defines the type of your Conduit API.
-export type MyAPI = {
+// This defines the public types of your Conduit API.
+export type MyApi = {
/** The client object defines your API functions available to the client. */
client: {
hello: (time: "morning" | "evening" | "afternoon" | "night") => Promise<string>;
goodbye: () => Promise<string>;
};
- /** The context object defines common context parameters passed to all Conduit API calls. */
- context: {
+ /** The apiCtx object defines common context parameters clients include in all Conduit API calls. */
+ apiCtx: {
name: string;
};
};
@@ -82,12 +83,22 @@
};
```
-### Add your API type to YggdrasilServer
+### Create your typed defineApi function
```ts title="src/server.ts"
-// Adding MyAPI here lets YggdrasilServer know what to expect so it
-// can throw an error if you forget to implement a function.
-export const DemoServer = new YggdrasilServer<AppType, MyAPI>();
+import { defineApi } from "@jottocraft/yggdrasil";
+
+// You should create your YggdrasilServer somewhere here.
+
+// This extends your API definition to include private server types.
+export type MyApiServer = MyApi & {
+ /** The conduitCtx object defines common context parameters passed to all of your server's Conduit API implementations. **/
+ conduitCtx: {
+ name: string;
+ };
+};
+
+export const defineMyApi = defineApi<AppTypes, MyApiServer>;
```
### Implement your API
@@ -100,9 +111,9 @@
the ability to add headers to the upstream request.
```ts title="src/api/hello.ts"
-import { DemoServer } from "../server";
+import { defineMyApi } from "../server";
-export const hello = DemoServer.defineAPI().hello(async (ygg, time) => {
+export const hello = defineMyApi().hello(async (ygg, time) => {
// Adds a sample header to the upstream request. If a web server is calling
// this API, this header will be sent not on the API response, but on the final
// web server's response given to the user.
@@ -122,15 +133,23 @@
### Handle requests
-Once you have your API handlers defined, simply call YggdrasilConduitServer.handleRequest
-to serve your API:
+Once you have your API handlers defined, simply call YggdrasilConduitServer.handleRequest to serve your API:
```ts title="src/index.ts"
+import { MyApiServer } from "./server";
import * as api from "./api";
// This should ideally be defined outside your request handler
-const DemoConduitServer = new YggdrasilConduitServer(DemoServer, api);
-
+const DemoConduitServer = new YggdrasilConduitServer<AppTypes, MyApiServer>(DemoServer, api, {
+ // The base path tells the conduit server where to listen for incoming API calls.
+ conduitBasePath: "/conduit/",
+ // You must have a function that maps between apiCtx and conduitCtx.
+ // This can perform input sanitization, or do some other lookups/transformations
+ // to flesh out your server-side context. Please note that this runs before
+ // your YggdrasilConduitContext is created, so you can't set upstream headers
+ // from within this function.
+ prepareConduitCtx: async (ygg, apiCtx) => apiCtx
+});
// Additional required setup omitted for brevity
// Inside DemoServer.handleRequest:
@@ -144,12 +163,12 @@
To call a Conduit API from another Yggdrasil Server instance,
call `createConduitClientSideClient()` to create a client.
-The client **must** be stored and called as a top-level method in
-your app's context so that the request's context can be bound to it.
+The client **must** be bound to your `ygg` context, ideally
+included in your YggdrasilServer `ctx` for automatic binding.
See the "Context" documentation for more details.
```ts title="src/index.ts"
-import { MyAPI } from "my-shared-library/conduit.ts";
+import { MyApi } from "my-shared-library/conduit.ts";
import { createConduitServerSideClient } from "@jottocraft/yggdrasil";
AnotherDemoServer.handleRequest(request, async (ygg) => {
@@ -160,8 +179,8 @@
}, {
// All Conduit clients MUST be defined here (as top-level methods).
// They can be named whatever you want.
- conduit: createConduitServerSideClient<MyAPI>({
- // Common context about this request to send to MyAPI
+ conduit: createConduitServerSideClient<MyApi>({
+ // Common context about this request to send to MyApi
name: "jottocraft"
}, {
// Options (baseURL is required)
@@ -181,18 +200,13 @@
Conduit API from this client, `upstreamHeaders` from the API will
be discarded, and you'll need to handle errors yourself.
-When an error occurs, a `YggdrasilClientStatus` object will
-be thrown. `YggdrasilClientStatus` is nearly identical to
-its server counterpart (`YggdrasilStatus`), but without an
-associated server context.
-
```ts title="src/index.ts"
-import { MyAPI } from "my-shared-library/conduit.ts";
+import { MyApi } from "my-shared-library/conduit.ts";
import { createConduitClientSideClient } from "@jottocraft/yggdrasil";
async function fetchConduitData() {
- const conduit = createConduitClientSideClient<MyAPI>({
- // Common context about this request to send to MyAPI
+ const conduit = createConduitClientSideClient<MyApi>({
+ // Common context about this request to send to MyApi
name: "jottocraft"
}, {
// Options (baseURL is required)
diff --git a/docs/docs/features/context.md b/docs/docs/features/context.md
index 245695e..ddfc9a5 100644
--- a/docs/docs/features/context.md
+++ b/docs/docs/features/context.md
@@ -14,37 +14,71 @@
This extended version uses prototype-based inheritance so that methods implemented in
the original object continue to run there.
-To make it so that you don't have to pass `ygg` into every function you call, and to
-ensure the correct context (base/extended) is being referenced, built-in functions
-that live in the `ygg` context object uses the `this` keyword to access the context.
-Additionally, functions that you add as top-level members to your app's context object
-will be appropriately bound so that they can access the context through `this` (the
-Conduit server client requires this).
+## Context-bound functions
-Please observe the following practices to avoid inadvertently breaking Yggdrasil Server's context:
+For your convenience, built-in functions that live in the `ygg` context object
+are bound to the `ygg` object so they can access the context with the `this` keyword
+instead of requiring an explicit parameter. Since accessing the active `ygg` context
+is a common need, Yggdrasil Server automatically binds all top-level functions in
+your app's `ctx` and `conduitCtx` (for Yggdrasil Server Conduit) to `ygg`.
+
+Here's a brief example showing how this can help simplify your app:
+
+```ts title="Setting headers with a global function"
+export function setDarkTheme(ygg: YggdrasilServerContext<AppTypes>) {
+ ygg.additionalHeaders.append.push(["Set-Cookie", "use-dark-theme=1"]);
+}
+```
+
+```ts title="Setting headers with a function defined in ctx"
+// This only works when accessing the method through ygg.ctx.setDarkTheme()
+const ctx = {
+ setDarkTheme(this: YggdrasilServerContext<AppTypes>) {
+ this.additionalHeaders.append.push(["Set-Cookie", "use-dark-theme=1"]);
+ }
+}
+```
+
+### Important side effects of binding
+
+The important side effects of this convention are:
+
+- Anything you access through the `ygg` context should not be stored or accessed
+through a separate variable. Always access members (including nested members) of
+the `ygg` context from `ygg` (you might be able to do this for your own `ctx` or
+`conduitCtx` through, depending on your implementation).
+- Never call `ygg` member functions with `.bind()`, `.apply()`, or anything else
+that would re-bind the member functions you're calling.
+- If you include a function bound to something else in your app's `ctx` or
+`conduitCtx` contexts, they will be re-bound to `ygg` on access, so you must either
+re-bind them every time you access them, or include those functions inside an object
+in your app's `ctx` or `conduitCtx` to avoid re-binding.
## Accessing context
-Always use the `ygg` variable passed to you, if provided to you by Yggdrasil Server.
-While you can and should pass the `ygg` variable to your own helper functions, you
-should not use the base context object from a Conduit handler, for example (the Conduit
-context provided by Yggdrasil Server should be used instead). Additionally, do not
-store the `ygg` variable outside or beyond the scope of a request.
+The `ygg` context is only provided to you through functions you implement (e.g. the
+callback of `handleRequest`). Only use the `ygg` context within the function it was
+passed to or any other functions invoked as part of its execution. Do not store or
+use the `ygg` context outside of that scope. Because the `ygg` context is
+request-specific, you should never store or pass the `ygg` context through
+global variables, or you will risk leaking data between requests.
-## Calling context-based functions
+In some cases, you may be able to access multiple `ygg` contexts simultaneously:
-Always access context functions and members directly through the context object.
-Do not store them in another variable, or the `this` context will be broken.
-For example, do `throw ygg.status(400, "NOT_FOUND")` instead of
-`const status = ygg.status; throw status(400, "NOT_FOUND");`. Furthermore,
-do not use `.bind`, `.apply`, or anything else that changes the `this` context.
+```ts title="Dealing with multiple ygg objects"
+DemoServer.handleRequest(request, async (ygg) => {
+ const RequestSpecificConduitServer = new YggdrasilConduitServer<AppTypes, ApiTypes>(FlowServer, {
+ async greeter(ygg: YggdrasilConduitContext<AppTypes, ApiTypes>, name: string) {
+ return new Response("Hello " + name + "!", { status: 200 });
+ }
+ });
-## Using your own context-based functions
+ return RequestSpecificConduitServer.handleRequest(ygg);
+} /* ... */ );
+```
-Any top-level member functions present in your app context will be automatically
-bound to the appropriate context, so you can use `this` inside them to access
-the context without requiring a separate `ygg` parameter.
-Please note that this strategy is intended only
-for accessing whatever context is available. If you specifically need a Conduit
-context, for example, it is recommended to use an explicit `ygg` parameter to
-enforce that.
\ No newline at end of file
+You should always use the `ygg` context nearest to your implementation. In this
+example, it would be incorrect to use the `ygg` context from `DemoServer.handleRequest`
+in the `greeter` function, which should use the `ygg` context passed directly to it.
+Any functions invoked as part of the `greeter` functions's execution must also use
+the `ygg` context passed to `greeter`. Otherwise, data loss may occur.
\ No newline at end of file
diff --git a/docs/docs/features/errors.md b/docs/docs/features/errors.md
index cc0a519..793bb45 100644
--- a/docs/docs/features/errors.md
+++ b/docs/docs/features/errors.md
@@ -4,32 +4,64 @@
# Error handling
-Yggdrasil Server has a built-in error handling mechanism. To use it, simply throw
-a `YggdrasilStatus` object from inside a request handler:
+Yggdrasil Server has a built-in error handling mechanism to generate status
+pages when something goes wrong. To use it, throw a `YggdrasilServerStatus`
+object anywhere in your request handler:
```ts
-throw new YggdrasilStatus(404, "INVALID_ROUTE", "The page you're trying to load doesn't exist.");
+if (route === undefined) throw new YggdrasilServerStatus(ygg, 404, "INVALID_ROUTE", "The page you're trying to load doesn't exist.");
```
-For your convenience, Yggdrasil Server also provides an assert function that throws
-a `YggdrasilStatus` for you upon failure:
+For your convenience, Yggdrasil Server also provides a `ygg.status` function that
+creates a `YggdrasilServerStatus` with the context pre-set, and an assert function
+that throws a `YggdrasilServerStatus` for you upon failure:
```ts
-ygg.assert(user.isAuthenticated, 401, "AUTH_REQUIRED", "You need to be signed in to load this page.");
+if (route === undefined) throw ygg.status(404, "INVALID_ROUTE", "The page you're trying to load doesn't exist.");
+// or
+ygg.assert(route !== undefined, 404, "INVALID_ROUTE", "The page you're trying to load doesn't exist.");
```
-## YggdrasilStatus parameters
+## YggdrasilStatus and server context
-The `YggdrasilStatus` constructor and `ygg.assert` function share a common set of parameters.
-Those parameters are:
+Yggdrasil Server also provides a `YggdrasilStatus` object that is functionally
+the same as `YggdrasilServerStatus`. However, `YggdrasilServerStatus` keeps
+a reference to the `ygg` context at the time of the error, while `YggdrasilStatus`
+does not have an associated `ygg` context. `YggdrasilStatus` is therefore
+primarily designed for handling `YggdrasilServerStatus` exceptions outside
+of Yggdrasil Server, like exceptions from a client-side Yggdrasil Server Conduit
+client.
-1. [The HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) to return.
- The name of the status code should match the nature of the error.
-2. A custom status code (something like "AUTH_REQUIRED"). This should be a brief error ID
- that should allow you to identify where the error was thrown from in your code, and also
+The `ygg` context included with `YggdrasilServerStatus` is useful for getting
+helpful values for debugging out from the context when the error is caught.
+For example, if an `YggdrasilServerStatus` is thrown in a Yggdrasil Server Conduit
+handler, the `ygg` context in the thrown `YggdrasilServerStatus` will have
+extended Yggdrasil Server Conduit attributes.
+
+## Catching errors
+
+You should always check if a caught Error is an instance of `YggdrasilStatus` when
+catching Yggdrasil Server errors. You should only check for `YggdrasilServerStatus`
+to get the associated `ygg` context, keeping in mind that it is only available on
+a best-effort basis.
+
+## YggdrasilStatus attributes
+
+The `YggdrasilStatus` object contains the following attributes:
+
+- `status`: [The HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) to return.
+ The name of the status code should match the nature of the exception.
+- `statusCode`: A custom status code (something like "AUTH_REQUIRED"). This should be a brief exception ID
+ that should allow you to identify where the exception was thrown from in your code, and also
allow users to identify the error through bug reports, web searches, etc.
-3. (optional) A custom status message to show to the user to help them understand the nature
- of the error, how they might resolve it, additional details, etc.
+- `statusMessage`: A custom status message to show to the user to help them understand the nature of
+ the error, how they might resolve it, additional details, etc.
+- `statusCtx`: Any custom properties you may want to associate with the thrown status. The type of
+ this attribute is set by your YggdrasilServer app types for construction, but when you catch a
+ `YggdrasilStatus` object, the `statusCtx` may be different if it was thrown internally by
+ Yggdrasil Server or by some other part of code.
+- `ygg`: The `ygg` context active when the exception was thrown. (Only on `YggdrasilServerStatus`
+ objects)
## Built-in errors
@@ -53,6 +85,7 @@
| 405 | `YGG_ROUTE_METHOD_MISMATCH` | Thrown when YggdrasilRouter finds route(s) that matches the request's path, but none of them match the request's method. |
| 404 | `YGG_API_NOT_FOUND` | Thrown when YggdrasilConduitServer can't find a Conduit API implementation that matches the request. |
| 400 | `YGG_BAD_API_REQUEST` | Thrown when YggdrasilConduitServer detects an invalid Conduit API request. |
+| 500 | `YGG_BAD_API_RESPONSE` | Thrown when the Yggdrasil Conduit client cannot parse the response received from a Yggdrasil Conduit server.
| 500 | `YGG_BADLY_CONFIGURED` | Thrown when Yggdrasil Server is unable to proceed due to a misconfiguration, such as missing a required option, contradictory settings, etc. The error message describes the nature of the misconfiguration. |
## Status pages
@@ -62,8 +95,7 @@
| Request Accept | Response type | Description |
| - | - | - |
-| `application/json+jottocraft-ygg-res` | `application/json+jottocraft-ygg-res` | Returns all the information necessary to pass along the status to the callee's instance of Yggdrasil Server. Please see the Conduit feature documentation for more information. |
-| `application/json` | `application/json` | This currently does the same thing as requests accepting `application/json+jottocraft-ygg-res`. |
+| `application/json` | `application/json` | Returns a JSON object with the following keys: `success`: `false`, `status`: the HTTP status code, `error`: the `YggdrasilStatus` status code, `message`: the status message. |
| `text/html` | `text/html` | Calls `ygg.options.generateHtmlStatusPage()` if this is something you've implemented. |
| Anything else | `text/plain` | Returns a presentable plaintext status page detailing the error. |
diff --git a/docs/docs/features/memo.md b/docs/docs/features/memo.md
index ac35d5f..4a3cea6 100644
--- a/docs/docs/features/memo.md
+++ b/docs/docs/features/memo.md
@@ -96,4 +96,8 @@
It is important to emphasize that this should only be done in the
same short-lived context (e.g. one request/operation). Sharing results in a
larger scope can lead to data leaks (a security issue) or stale
-results (a correctness issue).
\ No newline at end of file
+results (a correctness issue).
+
+The format of memoized results returned by `ygg.getMemoizedResults()`
+is opaque and subject to change. It is also not covered by SemVer; you should
+only store and restore memoized results on the same server.
\ No newline at end of file
diff --git a/docs/docs/features/router.md b/docs/docs/features/router.md
index 653def8..4cb6883 100644
--- a/docs/docs/features/router.md
+++ b/docs/docs/features/router.md
@@ -13,8 +13,8 @@
### Setup routes
-To define routes, simply use YggdrasilServer.defineRoute to create a
-route object. Then, pass all of your route objects into YggdrasilRouter's
+To define routes, simply use `defineRoute` to create a type-safe route
+definition function. Then, pass all of your route objects into YggdrasilRouter's
constructor to register them.
Please note that route handlers are passed a YggdrasilRouterContext,
@@ -23,12 +23,19 @@
The following sample shows how to define and register routes using
the recommended convention that keeps each route defined in its own file:
+```ts title="src/server.ts"
+import { YggdrasilServer, defineRoute } from "@jottocraft/yggdrasil";
+
+export const DemoServer = new YggdrasilServer<DemoAppTypes>();
+export const defineDemoRoute = defineRoute<DemoAppTypes>;
+```
+
```ts title="src/routes/hello.ts"
-import { DemoServer } from "../server";
+import { defineDemoRoute } from "../server";
// The first parameter is the HTTP method, or * to match all methods.
// The second parameter is the route to match (see the Routing section below)
-export const hello = DemoServer.defineRoute("GET", "/hello", async (ygg) => {
+export const hello = defineDemoRoute("GET", "/hello", async (ygg) => {
return new Response("Hello world!", { status: 200 });
});
```
@@ -49,7 +56,7 @@
import * as routes from "./routes";
// This should ideally be defined outside your request handler
-const DemoRouter = new YggdrasilRouter(DemoServer, routes);
+const DemoRouter = new YggdrasilRouter<DemoAppTypes>(DemoServer, routes);
// Additional required setup omitted for brevity
@@ -124,8 +131,8 @@
YggdrasilRouter only checks each path segment once. If it sees that a
segment can be matched with either a variable segment or a literal match,
it will prefer the literal match. This can lead to some potentially unexpected
-behavior, however. It's best to avoid allowing a route to be matched with different
-paths for this reason.
+behavior, however. It's best to avoid allowing a path to be matched with different
+routes for this reason.
For example, assume you have routes `/posts/$postId` and `/posts/$postId/likes`.
Then, you create a new route to render a special post, e.g. `/posts/specialPost`.
diff --git a/docs/docs/index.md b/docs/docs/index.md
index 89d30d5..648b444 100644
--- a/docs/docs/index.md
+++ b/docs/docs/index.md
@@ -22,17 +22,27 @@
```ts title="src/server.ts"
import { YggdrasilServer } from "@jottocraft/yggdrasil";
-export type AppType = {
- // The ctx object defines any arbitrary custom data
- // to pass to your request handlers.
+export type AppTypes = {
+ // The ctx object defines any arbitrary custom data to pass to
+ // your request handlers.
+ //
// Examples include environment variables, database bindings, etc.
ctx: {
env: DemoEnv;
ctx: ExecutionContext;
};
+ // The statusCtx object defines any arbitrary custom data you
+ // want to include with YggdrasilStatus objects thrown by your
+ // application.
+ //
+ // One example is including the names of fields responsible that
+ // caused the error to be generated.
+ statusCtx: {
+ fields: string[];
+ };
};
-export const DemoServer = new YggdrasilServer<AppType>();
+export const DemoServer = new YggdrasilServer<AppTypes>();
```
### Step 3: Handle requests
@@ -61,7 +71,7 @@
}
},
// Yggdrasil Server options. These are specified here rather than in
- // the YggdrasilServer object to support multi-tenancy.
+ // the YggdrasilServer constructor to allow changing options per-request.
{
debug: true
});
diff --git a/docs/static/favicon.png b/docs/static/favicon.png
index 5974ba1..68264c3 100644
--- a/docs/static/favicon.png
+++ b/docs/static/favicon.png
Binary files differ
diff --git a/yggdrasil/package.json b/yggdrasil/package.json
index f91df5d..47f689e 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.14",
+ "version": "0.0.1-alpha.16",
"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 8c98e3d..e16e4bc 100644
--- a/yggdrasil/src/YggdrasilConduitServer.ts
+++ b/yggdrasil/src/YggdrasilConduitServer.ts
@@ -1,8 +1,9 @@
// Yggdrasil
// Copyright (c) jottocraft 2024
-import type { YggdrasilConduitApi, YggdrasilConduitRequest, YggdrasilConduitResponse } from "~/conduit";
+import type { YggdrasilConduitApi, YggdrasilConduitRequest, YggdrasilConduitResponse, YggdrasilConduitResponseError } from "~/conduit";
import type { YggdrasilAdditionalHeaders, YggdrasilAppTypes, YggdrasilServer, YggdrasilServerContext } from "~/YggdrasilServer";
+import { YggdrasilStatus, yggdrasilStatusToJson } from "~/YggdrasilStatus";
/**
* Types defining your Conduit API, extended with an additional server-side attributes.
@@ -82,6 +83,30 @@
}
/**
+ * Formats an uncaught YggdrasilStatus exception to be passed to a Conduit client.
+ */
+async function generateConduitErrorResponse<AppTypes extends YggdrasilAppTypes, ApiTypes extends YggdrasilConduitServerApiTypes>(ygg: YggdrasilServerContext<AppTypes> | YggdrasilConduitContext<AppTypes, ApiTypes>, e: YggdrasilStatus<unknown>): Promise<Response> {
+ const result: YggdrasilConduitResponseError<AppTypes["statusCtx"]> = {
+ success: false,
+ status: yggdrasilStatusToJson(e),
+ headers: ("upstreamHeaders" in ygg) ? ygg.upstreamHeaders : { set: {}, append: [] }
+ };
+
+ if (ygg.options.debug) {
+ result.debug = {
+ stack: e.stack
+ };
+ }
+
+ return new Response(JSON.stringify(result), {
+ status: e.status,
+ headers: {
+ "Content-Type": "application/json+jottocraft-ygg-res"
+ }
+ });
+}
+
+/**
* A server for handling Conduit requests made to Yggdrasil Server.
*/
export class YggdrasilConduitServer<AppTypes extends YggdrasilAppTypes, ApiTypes extends YggdrasilConduitServerApiTypes> {
@@ -92,68 +117,96 @@
}
async handleRequest(ygg: YggdrasilServerContext<AppTypes>): Promise<Response> {
- if (!this.#options.conduitBasePath) throw ygg.status(500, "YGG_BADLY_CONFIGURED", "conduitBasePath must be configured to use Yggdrasil Server Conduit.");
+ try {
+ 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(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 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, ApiTypes>;
- let requestedApi: YggdrasilConduitApiHandler<AppTypes, ApiTypes, 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) {
- if (!requestedApi && (typeof requestedApiSegment[segment] === "function")) {
- requestedApi = requestedApiSegment[segment];
- } else if (!requestedApi && (typeof requestedApiSegment[segment] === "object")) {
- requestedApiSegment = requestedApiSegment[segment];
+ const segments = requestedPath.split("/");
+ for (const segment of segments) {
+ if (!requestedApi && (typeof requestedApiSegment[segment] === "function")) {
+ requestedApi = requestedApiSegment[segment];
+ } else if (!requestedApi && (typeof requestedApiSegment[segment] === "object")) {
+ requestedApiSegment = requestedApiSegment[segment];
+ } else {
+ throw ygg.status(404, "YGG_API_NOT_FOUND", "The requested API can't be located.");
+ }
+ }
+
+ 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<ApiTypes["apiCtx"], unknown[]>;
+ try {
+ request = await ygg.request.json();
+ } catch (e) {
+ throw ygg.status(400, "YGG_BAD_API_REQUEST", "Failed to parse Conduit request body.");
+ }
+
+ 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: []
+ },
+ get conduitCtx() {
+ const boundCtx: ApiTypes["conduitCtx"] = {} as ApiTypes["conduitCtx"];
+
+ for (const key in conduitCtx) {
+ if (typeof conduitCtx[key] === "function") {
+ boundCtx[key] = conduitCtx[key].bind(this);
+ } else {
+ boundCtx[key] = conduitCtx[key];
+ }
+ }
+
+ return boundCtx;
+ }
+ } satisfies Omit<YggdrasilConduitContext<AppTypes, ApiTypes>, keyof YggdrasilServerContext<AppTypes>> as unknown as YggdrasilConduitContext<AppTypes, ApiTypes>;
+ Object.setPrototypeOf(yggConduitCtx, ygg);
+
+ try {
+ const data = await requestedApi(yggConduitCtx, ...request.parameters);
+
+ const result: YggdrasilConduitResponse<AppTypes["statusCtx"], unknown> = {
+ success: true,
+ data,
+ headers: yggConduitCtx.upstreamHeaders
+ };
+
+ return new Response(JSON.stringify(result), {
+ status: 200,
+ headers: {
+ "Content-Type": "application/json+jottocraft-ygg-res"
+ }
+ });
+ } catch (e) {
+ if ((e instanceof YggdrasilStatus) && yggConduitCtx.request.headers.get("Accept")?.includes("application/json+jottocraft-ygg-res")) {
+ return generateConduitErrorResponse(yggConduitCtx, e);
+ } else {
+ throw e;
+ }
+ }
} else {
throw ygg.status(404, "YGG_API_NOT_FOUND", "The requested API can't be located.");
}
- }
-
- 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<ApiTypes["apiCtx"], unknown[]>;
- try {
- request = await ygg.request.json();
- } catch (e) {
- throw ygg.status(400, "YGG_BAD_API_REQUEST", "Failed to parse Conduit request body.");
+ } catch (e) {
+ if ((e instanceof YggdrasilStatus) && ygg.request.headers.get("Accept")?.includes("application/json+jottocraft-ygg-res")) {
+ return generateConduitErrorResponse(ygg, e);
+ } else {
+ throw e;
}
-
- 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: []
- },
- 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);
-
- const result: YggdrasilConduitResponse<AppTypes["statusCtx"], unknown> = {
- success: true,
- data,
- headers: yggConduitCtx.upstreamHeaders
- };
-
- return new Response(JSON.stringify(result), {
- status: 200,
- headers: {
- "Content-Type": "application/json+jottocraft-ygg-res"
- }
- });
- } else {
- throw ygg.status(404, "YGG_API_NOT_FOUND", "The requested API can't be located.");
}
}
#server: YggdrasilServer<AppTypes>;
#api: YggdrasilConduitApiClientImpl<AppTypes, ApiTypes>;
#options: YggdrasilConduitServerOptions<AppTypes, ApiTypes>;
-};
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/yggdrasil/src/YggdrasilServer.ts b/yggdrasil/src/YggdrasilServer.ts
index 8566358..093608f 100644
--- a/yggdrasil/src/YggdrasilServer.ts
+++ b/yggdrasil/src/YggdrasilServer.ts
@@ -2,7 +2,7 @@
// Copyright (c) jottocraft 2024
import { generateStatusPage } from "~/util/generateStatusPage";
-import { YggdrasilStatus, type YggdrasilStatusOptions } from "~/YggdrasilStatus";
+import { YggdrasilServerStatus, YggdrasilStatus, type YggdrasilStatusOptions } from "~/YggdrasilStatus";
/**
* Defines the app's types.
@@ -37,7 +37,7 @@
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>;
+ generateHtmlStatusPage?: (ygg: YggdrasilServerContext<AppTypes>, e: YggdrasilStatus<unknown>) => Promise<Response>;
};
/**
@@ -45,7 +45,7 @@
*/
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>;
+ status: (status: number, statusCode: string, messageOrOptions?: string | YggdrasilStatusOptions<AppTypes["statusCtx"]>) => YggdrasilServerStatus<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. */
@@ -177,7 +177,7 @@
const ygg: YggdrasilServerContext<AppTypes> = {
status(...args) {
- return new YggdrasilStatus(this, ...args);
+ return new YggdrasilServerStatus(this, ...args);
},
assert(condition, ...args) {
if (!condition) {
@@ -222,13 +222,13 @@
if (result.resolved) {
return result.outcome as T;
} else {
- return await new Promise((resolve, reject) => {
+ return await new Promise<T>((resolve, reject) => {
result.dispatcher.addEventListener("resolved", () => {
const resolvedOutcome = memoizedResults[key];
if (!resolvedOutcome.resolved) {
reject(new Error("A resolved event was illegally fired before the memoized outcome was set."));
} else {
- resolve(resolvedOutcome.outcome as any); // I have no idea why "as T" doesn't work here.
+ resolve(resolvedOutcome.outcome as T);
}
});
});
@@ -270,7 +270,7 @@
let response: Response;
if (!ygg.pathname.relative) {
- response = await generateStatusPage(new YggdrasilStatus(ygg, 404, "YGG_BASE_URL_MISMATCH"));
+ response = await generateStatusPage(ygg, new YggdrasilServerStatus(ygg, 404, "YGG_BASE_URL_MISMATCH"));
} else if (options.normalization?.redirect && (ygg.pathname.normalized !== ygg.pathname.requested)) {
response = new Response(null, {
status: 301,
@@ -283,7 +283,7 @@
response = await handler(ygg);
} catch (e) {
if (e instanceof YggdrasilStatus) {
- response = await generateStatusPage(e);
+ response = await generateStatusPage(ygg, e);
} else {
throw e;
}
diff --git a/yggdrasil/src/YggdrasilStatus.ts b/yggdrasil/src/YggdrasilStatus.ts
index 7c790ac..f970c87 100644
--- a/yggdrasil/src/YggdrasilStatus.ts
+++ b/yggdrasil/src/YggdrasilStatus.ts
@@ -1,24 +1,53 @@
// Yggdrasil
// Copyright (c) jottocraft 2024
-import { YggdrasilContext } from "~/context";
-import { YggdrasilAppTypes } from "~/YggdrasilServer";
+import type { YggdrasilAppTypes, YggdrasilServerContext } from "~/YggdrasilServer";
export type YggdrasilStatusOptions<StatusCtxType> = ErrorOptions & {
- ctx: StatusCtxType;
- statusMessage?: string;
+ ctx?: StatusCtxType;
+ message?: string;
};
+export type YggdrasilStatusJSON<StatusCtxType> = {
+ status: number;
+ code: string;
+ message?: string;
+ ctx?: StatusCtxType;
+};
+
+/**
+ * Stringifies a YggdrasilStatus object to JSON.
+ */
+export function yggdrasilStatusToJson<StatusCtxType>(status: YggdrasilStatus<StatusCtxType>): YggdrasilStatusJSON<StatusCtxType> {
+ return {
+ status: status.status,
+ code: status.statusCode,
+ message: status.statusMessage,
+ ctx: status.statusCtx
+ };
+}
+
+/**
+ * Parses a YggdrasilStatus object from JSON.
+ */
+export function jsonToYggdrasilStatus<StatusCtxType>(json: YggdrasilStatusJSON<StatusCtxType>): YggdrasilStatus<StatusCtxType> {
+ return new YggdrasilStatus<StatusCtxType>(json.status, json.code, {
+ message: json.message,
+ ctx: json.ctx
+ });
+}
+
/**
* YggdrasilStatus for clients without a server-side YggdrasilContext.
*/
-export class YggdrasilClientStatus<StatusCtxType> extends Error {
+export class YggdrasilStatus<StatusCtxType> extends Error {
constructor(status: number, statusCode: string, messageOrOptions?: string | YggdrasilStatusOptions<StatusCtxType>) {
super(statusCode, typeof messageOrOptions !== "string" ? messageOrOptions : undefined);
this.#status = status;
this.#statusCode = statusCode;
- this.#statusMessage = typeof messageOrOptions === "string" ? messageOrOptions : messageOrOptions?.statusMessage;
+ this.#statusMessage = typeof messageOrOptions === "string" ? messageOrOptions : messageOrOptions?.message;
+ if (typeof messageOrOptions !== "string") this.#statusCtx = messageOrOptions?.ctx;
}
#status: number;
@@ -36,23 +65,23 @@
return this.#statusMessage;
}
- #ctx?: StatusCtxType;
+ #statusCtx?: StatusCtxType;
get statusCtx() {
- return this.#ctx;
+ return this.#statusCtx;
}
};
/**
* An Error that will cause an HTTP status page to show.
*/
-export class YggdrasilStatus<AppTypes extends YggdrasilAppTypes> extends YggdrasilClientStatus<AppTypes["statusCtx"]> {
- constructor(ygg: YggdrasilContext<AppTypes>, status: number, statusCode: string, messageOrOptions?: string | YggdrasilStatusOptions<AppTypes["statusCtx"]>) {
+export class YggdrasilServerStatus<AppTypes extends YggdrasilAppTypes> extends YggdrasilStatus<AppTypes["statusCtx"]> {
+ constructor(ygg: YggdrasilServerContext<AppTypes>, status: number, statusCode: string, messageOrOptions?: string | YggdrasilStatusOptions<AppTypes["statusCtx"]>) {
super(status, statusCode, messageOrOptions);
this.#ygg = ygg;
}
- #ygg: YggdrasilContext<AppTypes>;
+ #ygg: YggdrasilServerContext<AppTypes>;
get ygg() {
return this.#ygg;
}
diff --git a/yggdrasil/src/conduit.ts b/yggdrasil/src/conduit.ts
index 1b69596..49de1fc 100644
--- a/yggdrasil/src/conduit.ts
+++ b/yggdrasil/src/conduit.ts
@@ -1,8 +1,8 @@
// Yggdrasil
// Copyright (c) jottocraft 2025
-import type { YggdrasilContext } from "~/context";
-import type { YggdrasilAdditionalHeaders, YggdrasilAppTypes } from "~/YggdrasilServer";
+import type { YggdrasilAdditionalHeaders } from "~/YggdrasilServer";
+import { YggdrasilStatusJSON } from "~/YggdrasilStatus";
export type YggdrasilConduitApi = {
client: any;
@@ -27,11 +27,8 @@
export type YggdrasilConduitResponseError<StatusCtx> = YggdrasilConduitResponseCommon & {
success: false;
- error: string;
- message?: string;
- ctx?: StatusCtx;
+ status: YggdrasilStatusJSON<StatusCtx>;
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 77448b8..0b8c663 100644
--- a/yggdrasil/src/conduitClient.ts
+++ b/yggdrasil/src/conduitClient.ts
@@ -2,9 +2,9 @@
// Copyright (c) jottocraft 2024
import type { YggdrasilConduitApi, YggdrasilConduitRequest, YggdrasilConduitResponse } from "~/conduit";
-import type { YggdrasilContext } from "~/context";
-import { YggdrasilClientStatus } from "~/YggdrasilStatus";
-import type { YggdrasilAdditionalHeaders, YggdrasilAppTypes } from "~/YggdrasilServer";
+import { YggdrasilConduitContext } from "~/YggdrasilConduitServer";
+import type { YggdrasilAdditionalHeaders, YggdrasilAppTypes, YggdrasilServerContext } from "~/YggdrasilServer";
+import { jsonToYggdrasilStatus } from "~/YggdrasilStatus";
export type YggdrasilConduitClientOptions = {
/**
@@ -51,7 +51,7 @@
let outcome: YggdrasilConduitResponse<unknown, unknown>;
if (response.headers.get("Content-Type") !== "application/json+jottocraft-ygg-res") {
- outcome = { success: false, error: "YGG_CONDUIT_BAD_RESPONSE", message: "An unexpected response was received from the backend server.", headers: { set: {}, append: [] } };
+ outcome = { success: false, status: { status: 500, code: "YGG_BAD_API_RESPONSE", message: "An unexpected response was received from the backend server." }, headers: { set: {}, append: [] } };
} else {
outcome = await response.json();
}
@@ -63,7 +63,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["apiCtx"], options: YggdrasilConduitServerSideClientOptions): YggdrasilConduitApiClient<ApiSpec> {
- return function conduitServerSideClient(this: YggdrasilContext<YggdrasilAppTypes>): ApiSpec["client"] {
+ return function conduitServerSideClient(this: YggdrasilServerContext<YggdrasilAppTypes> | YggdrasilConduitContext<YggdrasilAppTypes, ApiSpec>): ApiSpec["client"] {
const createAppFn = (path: string[]) => {
return new Proxy(async (...args: unknown[]) => {
const { response, outcome } = await doConduitRequest(path, args, apiCtx, options);
@@ -84,7 +84,7 @@
if (outcome.success) {
return outcome.data;
} else {
- throw this.status(response.status, outcome.error, { statusMessage: outcome.message, ctx: outcome.ctx });
+ throw jsonToYggdrasilStatus(outcome.status);
}
}, {
get(target, name: string) {
@@ -110,7 +110,7 @@
if (outcome.success) {
return outcome.data;
} else {
- throw new YggdrasilClientStatus(response.status, outcome.error, { statusMessage: outcome.message, ctx: outcome.ctx });
+ throw jsonToYggdrasilStatus(outcome.status);
}
}, {
get(target, name: string) {
diff --git a/yggdrasil/src/context.ts b/yggdrasil/src/context.ts
deleted file mode 100644
index 98e9131..0000000
--- a/yggdrasil/src/context.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-// Yggdrasil
-// Copyright (c) jottocraft 2024
-
-import type { YggdrasilConduitContext } from "~/YggdrasilConduitServer";
-import type { YggdrasilRouterContext } from "~/YggdrasilRouter";
-import type { YggdrasilAppTypes, YggdrasilServerContext } from "~/YggdrasilServer";
-
-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 3d60caf..0c116ae 100644
--- a/yggdrasil/src/index.ts
+++ b/yggdrasil/src/index.ts
@@ -3,7 +3,6 @@
export * from "~/conduit";
export * from "~/conduitClient";
-export * from "~/context";
export * from "~/YggdrasilConduitServer";
export * from "~/YggdrasilRouter";
export * from "~/YggdrasilServer";
diff --git a/yggdrasil/src/util/generateStatusPage.ts b/yggdrasil/src/util/generateStatusPage.ts
index 1260a84..c9a7172 100644
--- a/yggdrasil/src/util/generateStatusPage.ts
+++ b/yggdrasil/src/util/generateStatusPage.ts
@@ -1,63 +1,28 @@
// Yggdrasil
// Copyright (c) jottocraft 2024
-import type { YggdrasilConduitResponseError } from "~/conduit";
-import type { YggdrasilAppTypes } from "~/YggdrasilServer";
-import type { YggdrasilStatus } from "~/YggdrasilStatus";
+import type { YggdrasilAppTypes, YggdrasilServerContext } from "~/YggdrasilServer";
+import { 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");
+export async function generateStatusPage<AppTypes extends YggdrasilAppTypes>(ygg: YggdrasilServerContext<AppTypes>, e: YggdrasilStatus<unknown>): Promise<Response> {
+ const accept = ygg.request.headers.get("Accept");
- if (accept === "application/json+jottocraft-ygg-res") {
- return generateConduitErrorPage(e);
- } else if (accept?.includes("application/json")) {
- return generateJsonStatusPage(e);
- } else if (accept?.includes("text/html") && e.ygg?.options.generateHtmlStatusPage) {
- return e.ygg.options.generateHtmlStatusPage(e);
+ if (accept?.includes("application/json")) {
+ return generateJsonStatusPage(ygg, e);
+ } else if (accept?.includes("text/html") && ygg.options.generateHtmlStatusPage) {
+ return ygg.options.generateHtmlStatusPage(ygg, e);
} else {
- return generatePlaintextStatusPage(e);
+ return generatePlaintextStatusPage(ygg, e);
}
}
/**
- * 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<AppTypes["statusCtx"]> = {
- success: false,
- error: e.statusCode,
- message: e.statusMessage,
- ctx: e.statusCtx,
- headers: "upstreamHeaders" in e.ygg ? e.ygg.upstreamHeaders : { set: {}, append: [] }
- };
-
- if (e.ygg.options.debug) {
- result.debug = {
- stack: e.stack,
- ygg: {
- url: e.ygg.url,
- pathname: e.ygg.pathname,
- baseURL: e.ygg.baseURL,
- additionalHeaders: e.ygg.additionalHeaders
- }
- };
- }
-
- return new Response(JSON.stringify(result), {
- status: e.status,
- headers: {
- "Content-Type": "application/json+jottocraft-ygg-res"
- }
- });
-}
-
-/**
* Generates a JSON status page for an uncaught YggdrasilStatus exception.
*/
-async function generateJsonStatusPage<AppTypes extends YggdrasilAppTypes>(e: YggdrasilStatus<AppTypes>): Promise<Response> {
+async function generateJsonStatusPage<AppTypes extends YggdrasilAppTypes>(ygg: YggdrasilServerContext<AppTypes>, e: YggdrasilStatus<unknown>): Promise<Response> {
return new Response(JSON.stringify({
success: false,
status: e.status,
@@ -74,7 +39,7 @@
/**
* Generates a human-readable plaintext status page for an uncaught YggdrasilStatus exception.
*/
-async function generatePlaintextStatusPage<AppTypes extends YggdrasilAppTypes>(e: YggdrasilStatus<AppTypes>): Promise<Response> {
+async function generatePlaintextStatusPage<AppTypes extends YggdrasilAppTypes>(ygg: YggdrasilServerContext<AppTypes>, e: YggdrasilStatus<unknown>): Promise<Response> {
return new Response(`Error ${e.status} ${e.statusCode}${e.statusMessage ? ": " + e.statusMessage : ""}`, {
status: e.status,
headers: {