Add support for Conduit memoization, rename statusCtx to statusArgs, other minor improvements and fixes
diff --git a/demo/src/DemoAPI.ts b/demo/src/DemoAPI.ts
index 9ba1d70..785ebe1 100644
--- a/demo/src/DemoAPI.ts
+++ b/demo/src/DemoAPI.ts
@@ -15,6 +15,8 @@
/** The first argument to YggdrasilConduitAPI defines your API functions available to the client. */
hello: (time: "morning" | "evening" | "afternoon" | "night") => Promise<string>;
goodbye: () => Promise<string>;
+ datetime: (label: string) => Promise<string>;
+ datetimeMemo: (label: string) => Promise<string>;
};
apiCtx: DemoApiCtx;
};
diff --git a/demo/src/api/datetime.ts b/demo/src/api/datetime.ts
new file mode 100644
index 0000000..f19014e
--- /dev/null
+++ b/demo/src/api/datetime.ts
@@ -0,0 +1,12 @@
+// Yggdrasil
+// Copyright (c) jottocraft 2024. All rights reserved.
+
+import { defineDemoApi } from "../server";
+
+export const datetime = defineDemoApi().datetime(async (ygg, label) => {
+ return label + " " + new Date().toUTCString();
+});
+
+export const datetimeMemo = defineDemoApi().datetimeMemo(async (ygg, label) => {
+ return label + " " + new Date().toUTCString();
+});
\ No newline at end of file
diff --git a/demo/src/api/goodbye.ts b/demo/src/api/goodbye.ts
index fc19d92..44f2123 100644
--- a/demo/src/api/goodbye.ts
+++ b/demo/src/api/goodbye.ts
@@ -5,6 +5,8 @@
export const goodbye = defineDemoApi().goodbye(async (ygg) => {
ygg.upstreamHeaders.set["X-Test-Header"] = "X-Test-Value";
+ ygg.upstreamHeaders.append.push(["X-Test-Header-2", "X-Test-Value-1"]);
+ ygg.upstreamHeaders.append.push(["X-Test-Header-2", "X-Test-Value-2"]);
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/index.ts b/demo/src/api/index.ts
index 9da0086..424874c 100644
--- a/demo/src/api/index.ts
+++ b/demo/src/api/index.ts
@@ -1,5 +1,6 @@
// Yggdrasil
// Copyright (c) jottocraft 2024
+export * from "./datetime";
export * from "./goodbye";
export * from "./hello";
\ No newline at end of file
diff --git a/demo/src/index.ts b/demo/src/index.ts
index 567790c..6431028 100644
--- a/demo/src/index.ts
+++ b/demo/src/index.ts
@@ -1,7 +1,7 @@
// Yggdrasil
// Copyright (c) jottocraft 2024
-import { YggdrasilConduitServer, YggdrasilServerContext, YggdrasilRouter, YggdrasilServerStatus, createConduitServerSideClient } from "@jottocraft/yggdrasil";
+import { YggdrasilConduitServer, YggdrasilRouter, YggdrasilServerStatus, createConduitServerSideClient } from "@jottocraft/yggdrasil";
import { DemoAppTypes, DemoServer } from "./server";
import * as routes from "./routes";
@@ -22,13 +22,19 @@
try {
return await DemoConduitServer.handleRequest(ygg);
} catch (e) {
- if (!(e instanceof YggdrasilServerStatus) || (e.status !== 404)) throw e;
+ if (!(e instanceof YggdrasilServerStatus) || (e.httpStatus !== 404)) throw e;
+ }
+
+ // Redirect to the normalized URL
+ // This must happen AFTER conduit has a chance to handle the request (since conduit URLs are not normalized)
+ if (ygg.url.requested.pathname !== ygg.url.normalized.pathname) {
+ return new Response(null, { status: 301, headers: { Location: ygg.url.normalized.pathname } });
}
try {
return await DemoRouter.handleRequest(ygg);
} catch (e) {
- if (!(e instanceof YggdrasilServerStatus) || (e.status !== 404)) throw e;
+ if (!(e instanceof YggdrasilServerStatus) || (e.httpStatus !== 404)) throw e;
}
throw ygg.status(404, "INVALID_PATH", "Nobody was able to handle your request :(");
@@ -36,15 +42,22 @@
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,
+ memoization: {
+ datetimeMemo: true
+ }
+ })
}
}, {
debug: true,
baseURL: "https://yggdrasil.ns.jottocraft.com/demo",
normalization: {
trailingSlash: false,
- lowercase: true,
- redirect: true
+ lowercase: true
}
});
}
diff --git a/demo/src/routes/datetime.ts b/demo/src/routes/datetime.ts
new file mode 100644
index 0000000..bd7b4a6
--- /dev/null
+++ b/demo/src/routes/datetime.ts
@@ -0,0 +1,25 @@
+// Yggdrasil
+// Copyright (c) jottocraft 2024
+
+import { YggdrasilSpacer } from "@jottocraft/yggdrasil";
+
+import { defineDemoRoute } from "../server";
+
+export const datetime = defineDemoRoute("GET", "/datetime", async (ygg) => {
+ const messages: string[] = [];
+
+ const spacer = new YggdrasilSpacer(2000);
+ if (ygg.url.requested.searchParams.get("memo") === "true") {
+ await spacer.enqueueTask(async () => messages.push(await ygg.ctx.conduit().datetimeMemo("a")));
+ await spacer.enqueueTask(async () => messages.push(await ygg.ctx.conduit().datetimeMemo("b")));
+ await spacer.enqueueTask(async () => messages.push(await ygg.ctx.conduit().datetimeMemo("b")));
+ await spacer.enqueueTask(async () => messages.push(await ygg.ctx.conduit().datetimeMemo("a")));
+ } else {
+ await spacer.enqueueTask(async () => messages.push(await ygg.ctx.conduit().datetime("a")));
+ await spacer.enqueueTask(async () => messages.push(await ygg.ctx.conduit().datetime("b")));
+ await spacer.enqueueTask(async () => messages.push(await ygg.ctx.conduit().datetime("b")));
+ await spacer.enqueueTask(async () => messages.push(await ygg.ctx.conduit().datetime("a")));
+ }
+
+ return new Response(messages.join("\n"), { status: 200 });
+});
\ No newline at end of file
diff --git a/demo/src/routes/index.ts b/demo/src/routes/index.ts
index d5f0113..6e0b8e9 100644
--- a/demo/src/routes/index.ts
+++ b/demo/src/routes/index.ts
@@ -2,6 +2,7 @@
// Copyright (c) jottocraft 2024
export * from "./abc";
+export * from "./datetime";
export * from "./def";
export * from "./goodbye";
export * from "./hij";
diff --git a/docs/docs/features/conduit.md b/docs/docs/features/conduit.md
index d6c169c..15a2400 100644
--- a/docs/docs/features/conduit.md
+++ b/docs/docs/features/conduit.md
@@ -53,6 +53,10 @@
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.
+- Yggdrasil Server Conduit uses case-sensitive URLs. If you redirect clients to normalize their requested URLs, you MUST
+ ensure that any such normalization does not apply to Yggdrasil Server Conduit paths.
+- If you use YggdrasilStatus arguments (`statusArgs`), those MUST be JSON serializable, since Yggdrasil Server Conduit
+ includes those in the serialized response when an YggdrasilStatus object is caught.
## Implementation
@@ -177,7 +181,8 @@
// Do whatever you want based on the outcome
}, {
- // All Conduit clients MUST be defined here (as top-level methods).
+ // Conduit clients MUST be defined here (as top-level methods) for
+ // automatic `ygg` binding.
// They can be named whatever you want.
conduit: createConduitServerSideClient<MyApi>({
// Common context about this request to send to MyApi
@@ -193,6 +198,39 @@
});
```
+If you need to construct a Conduit client dynamically, or otherwise
+keep the Conduit client somewhere outside `ygg.ctx`, you must bind
+the `ygg` context manually when calling it:
+
+```ts
+const conduit = createConduitServerSideClient<MyApi>(/* ... */);
+await conduit.apply(ygg).hello("morning");
+```
+
+#### Memoizing Conduit requests
+
+Conduit requests can be memoized when called from another Yggdrasil Server instance.
+Simply use the `memoization` option to set which functions can be memoized:
+
+```ts
+createConduitServerSideClient<MyApi>({ /* ... */ }, {
+ // Include other options here
+
+ memoization: {
+ hello: true
+ }
+});
+```
+
+The memoization option uses the same shape as your Conduit API client, but instead of containing
+functions, it contains booleans to mark which functions can be memoized. If you have related functions
+in the same nested object, you can set the entire nested object to `true` in the memoization
+object to enable memoization for all those functions. You can also set memoization
+itself to `true` to enable memoization for everything. By default, nothing is memoized.
+
+Memoization is applied on a per-request basis, meaning it only kicks in when the server makes
+duplicate Conduit requests that originate from the same top-level request.
+
### From an external source
Call `createConduitClientSideClient()` to create a client
diff --git a/docs/docs/features/errors.md b/docs/docs/features/errors.md
index 793bb45..7b341b9 100644
--- a/docs/docs/features/errors.md
+++ b/docs/docs/features/errors.md
@@ -36,7 +36,10 @@
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.
+extended Yggdrasil Server Conduit attributes. It also enables the optional
+`generateStatusMessage` function to programmatically generate status messages
+for `YggdrasilServerStatus` thrown by your server. So, you should never throw a
+`YggdrasilStatus` object from within Yggdrasil server.
## Catching errors
@@ -56,9 +59,9 @@
allow users to identify the error through bug reports, web searches, 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
+- `statusArgs`: 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
+ `YggdrasilStatus` object, the `statusArgs` 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)
diff --git a/docs/docs/features/memo.md b/docs/docs/features/memo.md
index 4a3cea6..12cc859 100644
--- a/docs/docs/features/memo.md
+++ b/docs/docs/features/memo.md
@@ -99,5 +99,7 @@
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
+is opaque and subject to change. Since memoized results are only designed
+to be exported and restored on the same server, it is considered an internal
+data structure, and is therefore not covered by SemVer. In other words, its
+format may drastically change between versions, even patch versions.
\ No newline at end of file
diff --git a/docs/docs/index.md b/docs/docs/index.md
index 648b444..17df0e4 100644
--- a/docs/docs/index.md
+++ b/docs/docs/index.md
@@ -31,13 +31,12 @@
env: DemoEnv;
ctx: ExecutionContext;
};
- // The statusCtx object defines any arbitrary custom data you
- // want to include with YggdrasilStatus objects thrown by your
- // application.
+ // The statusArgs object allows you to define custom paramters
+ // for YggdrasilStatus errors thrown by your server.
//
- // One example is including the names of fields responsible that
- // caused the error to be generated.
- statusCtx: {
+ // One example is including the names of fields that caused an
+ // error (e.g. for a MISSING_REQUIRED_FIELD error).
+ statusArgs: {
fields: string[];
};
};
diff --git a/docs/package.json b/docs/package.json
index 2403376..030077d 100644
--- a/docs/package.json
+++ b/docs/package.json
@@ -4,7 +4,7 @@
"scripts": {
"docusaurus": "docusaurus",
"start": "docusaurus start",
- "build": "rmdir /s /q dist && docusaurus build && mkdir dist && move build dist && move dist\\build dist\\docs",
+ "build": "rmdir /s /q dist & docusaurus build && mkdir dist && move build dist && move dist\\build dist\\docs",
"swizzle": "docusaurus swizzle",
"deploy": "wrangler pages deploy dist --project-name yggdrasil-docs",
"clear": "docusaurus clear",
diff --git a/yarn.lock b/yarn.lock
index 957953b..3eb5af5 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -2564,6 +2564,7 @@
dependencies:
npm-run-all: "npm:^4.1.5"
rimraf: "npm:^6.0.1"
+ safe-stable-stringify: "npm:^2.5.0"
tsc-alias: "npm:^1.8.10"
typescript: "npm:^5.5.4"
languageName: unknown
@@ -11347,6 +11348,13 @@
languageName: node
linkType: hard
+"safe-stable-stringify@npm:^2.5.0":
+ version: 2.5.0
+ resolution: "safe-stable-stringify@npm:2.5.0"
+ checksum: 10c0/baea14971858cadd65df23894a40588ed791769db21bafb7fd7608397dbdce9c5aac60748abae9995e0fc37e15f2061980501e012cd48859740796bea2987f49
+ languageName: node
+ linkType: hard
+
"safer-buffer@npm:>= 2.1.2 < 3, safer-buffer@npm:>= 2.1.2 < 3.0.0":
version: 2.1.2
resolution: "safer-buffer@npm:2.1.2"
diff --git a/yggdrasil/package.json b/yggdrasil/package.json
index 7fedf80..b469095 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.19",
+ "description": "A lightweight TypeScript tool that makes handling web requests easier.",
+ "version": "0.0.1-alpha.20",
"homepage": "https://gitlab.com/jottocraft/yggdrasil",
"bugs": {
"url": "https://gitlab.com/jottocraft/yggdrasil/-/issues"
@@ -31,5 +31,8 @@
"files": [
"lib",
"README.md"
- ]
+ ],
+ "dependencies": {
+ "safe-stable-stringify": "^2.5.0"
+ }
}
diff --git a/yggdrasil/src/YggdrasilConduitServer.ts b/yggdrasil/src/YggdrasilConduitServer.ts
index d7bb18a..7f0c155 100644
--- a/yggdrasil/src/YggdrasilConduitServer.ts
+++ b/yggdrasil/src/YggdrasilConduitServer.ts
@@ -66,8 +66,8 @@
* Internal type for recursing through arbitrary segments in the API object.
*/
type ApiSegment<AppTypes extends YggdrasilAppTypes, ApiTypes extends YggdrasilConduitServerApiTypes> = {
- [segment: string]: ApiSegment<AppTypes, ApiTypes> | YggdrasilConduitApiHandler<AppTypes, ApiTypes, AnyFn>;
-};
+ [segment: string]: ApiSegment<AppTypes, ApiTypes>;
+} | YggdrasilConduitApiHandler<AppTypes, ApiTypes, AnyFn> | undefined;
/**
* A helper for defining API routes with type safety.
@@ -86,7 +86,7 @@
* 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"]> = {
+ const result: YggdrasilConduitResponseError<AppTypes["statusArgs"]> = {
success: false,
status: yggdrasilStatusToJson(e),
headers: ("upstreamHeaders" in ygg) ? ygg.upstreamHeaders : { set: {}, append: [] }
@@ -99,9 +99,9 @@
}
return new Response(JSON.stringify(result), {
- status: e.status,
+ status: e.httpStatus,
headers: {
- "Content-Type": "application/json+jottocraft-ygg-res"
+ "Content-Type": "application/vnd.jottocraft.ygg.conduit-res+json"
}
});
}
@@ -123,22 +123,19 @@
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 requestedApi: ApiSegment<AppTypes, ApiTypes> = this.#api;
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];
+ if (requestedApi && (typeof requestedApi === "object")) {
+ requestedApi = requestedApi[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.");
+ if (requestedApi && (typeof requestedApi === "function")) {
+ if (ygg.request.headers.get("Content-Type") !== "application/vnd.jottocraft.ygg.conduit-req+json") throw ygg.status(400, "YGG_BAD_API_REQUEST", "Badly formatted Conduit request.");
let request: YggdrasilConduitRequest<ApiTypes["apiCtx"], unknown[]>;
try {
@@ -147,7 +144,7 @@
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.");
+ if (!request.arguments || !(request.arguments instanceof Array)) throw ygg.status(400, "YGG_BAD_API_REQUEST", "Badly formatted Conduit request.");
const conduitCtx = await this.#options.prepareConduitCtx(ygg, request.context);
@@ -173,9 +170,9 @@
Object.setPrototypeOf(yggConduitCtx, ygg);
try {
- const data = await requestedApi(yggConduitCtx, ...request.parameters.map(param => (param === "__jtc_ygg_undefined" ? undefined : param)));
+ const data = await requestedApi(yggConduitCtx, ...request.arguments.map(arg => (arg === "__jtc_ygg_undefined" ? undefined : arg)));
- const result: YggdrasilConduitResponse<AppTypes["statusCtx"], unknown> = {
+ const result: YggdrasilConduitResponse<AppTypes["statusArgs"], unknown> = {
success: true,
data,
headers: yggConduitCtx.upstreamHeaders
@@ -184,11 +181,11 @@
return new Response(JSON.stringify(result), {
status: 200,
headers: {
- "Content-Type": "application/json+jottocraft-ygg-res"
+ "Content-Type": "application/vnd.jottocraft.ygg.conduit-res+json"
}
});
} catch (e) {
- if ((e instanceof YggdrasilStatus) && yggConduitCtx.request.headers.get("Accept")?.includes("application/json+jottocraft-ygg-res")) {
+ if ((e instanceof YggdrasilStatus) && yggConduitCtx.request.headers.get("Accept")?.includes("application/vnd.jottocraft.ygg.conduit-res+json")) {
return generateConduitErrorResponse(yggConduitCtx, e);
} else {
throw e;
@@ -198,7 +195,7 @@
throw ygg.status(404, "YGG_API_NOT_FOUND", "The requested API can't be located.");
}
} catch (e) {
- if ((e instanceof YggdrasilStatus) && ygg.request.headers.get("Accept")?.includes("application/json+jottocraft-ygg-res")) {
+ if ((e instanceof YggdrasilStatus) && ygg.request.headers.get("Accept")?.includes("application/vnd.jottocraft.ygg.conduit-res+json")) {
return generateConduitErrorResponse(ygg, e);
} else {
throw e;
diff --git a/yggdrasil/src/YggdrasilServer.ts b/yggdrasil/src/YggdrasilServer.ts
index e2fdf1d..a6820d6 100644
--- a/yggdrasil/src/YggdrasilServer.ts
+++ b/yggdrasil/src/YggdrasilServer.ts
@@ -11,7 +11,7 @@
/** 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;
+ statusArgs?: any;
};
/**
@@ -33,11 +33,15 @@
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?: (ygg: YggdrasilServerContext<AppTypes>, e: YggdrasilStatus<unknown>) => Promise<Response>;
+ /**
+ * A function you can implement to generate status messages programmatically.
+ * When implemented, YggdrasilServer will call this to generate messages for YggdrasilStatus objects that do not have a statusMessage.
+ * Returning null or an empty string will keep the status message unset.
+ */
+ generateStatusMessage?: (ygg: YggdrasilServerContext<AppTypes>, statusCode: string, options?: YggdrasilStatusOptions<AppTypes["statusArgs"]>) => string | null;
};
/**
@@ -45,9 +49,9 @@
*/
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"]>) => YggdrasilServerStatus<AppTypes>;
+ status: (status: number, statusCode: string, messageOrOptions?: string | YggdrasilStatusOptions<AppTypes["statusArgs"]>) => 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;
+ assert: (condition: any, status: number, statusCode: string, messageOrOptions?: string | YggdrasilStatusOptions<AppTypes["statusArgs"]>) => asserts condition;
/** The Yggdrasil Server instance associated with this request. */
server: YggdrasilServer<AppTypes>;
/** The original request. */
@@ -212,10 +216,10 @@
},
options,
additionalHeaders: {
- set: {},
- append: [
- ["X-Powered-By", "@jottocraft/yggdrasil"]
- ]
+ set: {
+ "X-Powered-By": "@jottocraft/yggdrasil"
+ },
+ append: []
},
memoize: async <T>(key: string, task: () => Promise<T>) => {
const result = memoizedResults[key];
@@ -257,7 +261,7 @@
},
getMemoizedResults: () => {
const completedResults: MemoizedResultsInternal = {};
-
+
for (const result in memoizedResults) {
if (memoizedResults[result].resolved) {
completedResults[result] = memoizedResults[result];
@@ -281,13 +285,6 @@
if (!ygg.pathname.relative) {
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,
- headers: {
- Location: ygg.pathname.normalized
- }
- });
} else {
try {
response = await handler(ygg);
diff --git a/yggdrasil/src/YggdrasilStatus.ts b/yggdrasil/src/YggdrasilStatus.ts
index f970c87..a9d04a3 100644
--- a/yggdrasil/src/YggdrasilStatus.ts
+++ b/yggdrasil/src/YggdrasilStatus.ts
@@ -3,56 +3,59 @@
import type { YggdrasilAppTypes, YggdrasilServerContext } from "~/YggdrasilServer";
-export type YggdrasilStatusOptions<StatusCtxType> = ErrorOptions & {
- ctx?: StatusCtxType;
+export type YggdrasilStatusOptions<StatusArgsType> = {
+ args?: StatusArgsType;
message?: string;
+ errorOptions?: ErrorOptions;
};
-export type YggdrasilStatusJSON<StatusCtxType> = {
- status: number;
+export type YggdrasilStatusJSON<StatusArgsType> = {
+ http: number;
code: string;
+ args?: StatusArgsType;
message?: string;
- ctx?: StatusCtxType;
};
/**
* Stringifies a YggdrasilStatus object to JSON.
*/
-export function yggdrasilStatusToJson<StatusCtxType>(status: YggdrasilStatus<StatusCtxType>): YggdrasilStatusJSON<StatusCtxType> {
+export function yggdrasilStatusToJson<StatusArgsType>(status: YggdrasilStatus<StatusArgsType>): YggdrasilStatusJSON<StatusArgsType> {
return {
- status: status.status,
+ http: status.httpStatus,
code: status.statusCode,
message: status.statusMessage,
- ctx: status.statusCtx
+ args: status.statusArgs
};
}
/**
* Parses a YggdrasilStatus object from JSON.
*/
-export function jsonToYggdrasilStatus<StatusCtxType>(json: YggdrasilStatusJSON<StatusCtxType>): YggdrasilStatus<StatusCtxType> {
- return new YggdrasilStatus<StatusCtxType>(json.status, json.code, {
+export function jsonToYggdrasilStatus<StatusArgsType>(json: YggdrasilStatusJSON<StatusArgsType>): YggdrasilStatus<StatusArgsType> {
+ return new YggdrasilStatus<StatusArgsType>(json.http, json.code, {
message: json.message,
- ctx: json.ctx
+ args: json.args
});
}
/**
* YggdrasilStatus for clients without a server-side YggdrasilContext.
*/
-export class YggdrasilStatus<StatusCtxType> extends Error {
- constructor(status: number, statusCode: string, messageOrOptions?: string | YggdrasilStatusOptions<StatusCtxType>) {
- super(statusCode, typeof messageOrOptions !== "string" ? messageOrOptions : undefined);
+export class YggdrasilStatus<StatusArgsType> extends Error {
+ constructor(httpStatus: number, statusCode: string, messageOrOptions?: string | YggdrasilStatusOptions<StatusArgsType>) {
+ const statusMessage = typeof messageOrOptions === "string" ? messageOrOptions : messageOrOptions?.message;
- this.#status = status;
+ super(statusMessage ? `${statusCode}: ${statusMessage}` : statusCode, typeof messageOrOptions !== "string" ? messageOrOptions?.errorOptions : undefined);
+
+ this.#httpStatus = httpStatus;
this.#statusCode = statusCode;
- this.#statusMessage = typeof messageOrOptions === "string" ? messageOrOptions : messageOrOptions?.message;
- if (typeof messageOrOptions !== "string") this.#statusCtx = messageOrOptions?.ctx;
+ this.#statusMessage = statusMessage;
+ if (typeof messageOrOptions !== "string") this.#statusArgs = messageOrOptions?.args;
}
- #status: number;
- get status() {
- return this.#status;
+ #httpStatus: number;
+ get httpStatus() {
+ return this.#httpStatus;
}
#statusCode: string;
@@ -65,18 +68,24 @@
return this.#statusMessage;
}
- #statusCtx?: StatusCtxType;
- get statusCtx() {
- return this.#statusCtx;
+ #statusArgs?: StatusArgsType;
+ get statusArgs() {
+ return this.#statusArgs;
}
};
/**
* An Error that will cause an HTTP status page to show.
*/
-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);
+export class YggdrasilServerStatus<AppTypes extends YggdrasilAppTypes> extends YggdrasilStatus<AppTypes["statusArgs"]> {
+ constructor(ygg: YggdrasilServerContext<AppTypes>, status: number, statusCode: string, messageOrOptions?: string | YggdrasilStatusOptions<AppTypes["statusArgs"]>) {
+ const options: YggdrasilStatusOptions<AppTypes["statusArgs"]> = typeof messageOrOptions === "string" ? ({ message: messageOrOptions }) : (messageOrOptions ?? {});
+ if (!options.message && ygg.options.generateStatusMessage) {
+ const generatedMessage = ygg.options.generateStatusMessage(ygg, statusCode, options);
+ if (generatedMessage) options.message = generatedMessage;
+ }
+
+ super(status, statusCode, options);
this.#ygg = ygg;
}
diff --git a/yggdrasil/src/conduit.ts b/yggdrasil/src/conduit.ts
index 49de1fc..c6ac53c 100644
--- a/yggdrasil/src/conduit.ts
+++ b/yggdrasil/src/conduit.ts
@@ -10,11 +10,11 @@
};
export type YggdrasilConduitRequest<ApiCtx, T extends unknown[]> = {
- parameters: T;
+ arguments: T;
context: ApiCtx;
};
-export type YggdrasilConduitResponse<StatusCtx, T> = YggdrasilConduitResponseSuccess<T> | YggdrasilConduitResponseError<StatusCtx>;
+export type YggdrasilConduitResponse<StatusArgs, T> = YggdrasilConduitResponseSuccess<T> | YggdrasilConduitResponseError<StatusArgs>;
export type YggdrasilConduitResponseCommon = {
headers: YggdrasilAdditionalHeaders;
@@ -25,9 +25,9 @@
data: T;
};
-export type YggdrasilConduitResponseError<StatusCtx> = YggdrasilConduitResponseCommon & {
+export type YggdrasilConduitResponseError<StatusArgs> = YggdrasilConduitResponseCommon & {
success: false;
- status: YggdrasilStatusJSON<StatusCtx>;
+ status: YggdrasilStatusJSON<StatusArgs>;
debug?: {
stack?: string;
};
diff --git a/yggdrasil/src/conduitClient.ts b/yggdrasil/src/conduitClient.ts
index db7234a..3d02368 100644
--- a/yggdrasil/src/conduitClient.ts
+++ b/yggdrasil/src/conduitClient.ts
@@ -1,32 +1,65 @@
// Yggdrasil
// Copyright (c) jottocraft 2024
+import stringify from "safe-stable-stringify";
+
import type { YggdrasilConduitApi, YggdrasilConduitRequest, YggdrasilConduitResponse } from "~/conduit";
import { YggdrasilConduitContext } from "~/YggdrasilConduitServer";
import type { YggdrasilAdditionalHeaders, YggdrasilAppTypes, YggdrasilServerContext } from "~/YggdrasilServer";
import { jsonToYggdrasilStatus } from "~/YggdrasilStatus";
-export type YggdrasilConduitClientOptions = {
- /**
- * The fetcher used to submit requests to the Yggdrasil Server instance hosting these Conduit functions.
- */
- fetcher?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
+export type YggdrasilConduitClientOptions<ApiSpec extends YggdrasilConduitApi> = {
/**
* The base URL of the Yggdrasil Server instance hosting these Conduit functions, WITH a trailing slash.
*/
baseURL: string;
+ /**
+ * The fetcher used to submit requests to the Yggdrasil Server instance hosting these Conduit functions.
+ */
+ fetcher?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
};
-export type YggdrasilConduitApiClient<ApiSpec extends YggdrasilConduitApi> = () => ApiSpec["client"];
-
-export type YggdrasilConduitServerSideClientOptions = YggdrasilConduitClientOptions & {
+export type YggdrasilConduitServerSideClientOptions<ApiSpec extends YggdrasilConduitApi> = YggdrasilConduitClientOptions<ApiSpec> & {
/**
* Set to true to allow the connected Conduit server to manipulate headers on the highest-level response.
*/
allowHeaderManipulation?: boolean;
+ /**
+ * An object defining which Conduit functions can be memoized. This object has the same structure as your Conduit API client,
+ * but it has booleans to indicate whether memoization is allowed.
+ *
+ * @example
+ * // If we have some Conduit API with a client that looks like this:
+ * const API = { users: { readBasic: () => {}, readFull: () => {}, write: () => {} }, licenses: { readBasic: () => {}, readFull: () => {} } };
+ *
+ * // Then, we can mark users.readBasic, users.readFull, and licenses.* as memoizable like this:
+ * const memoization = { users: { readBasic: true, readFull: true }, licenses: true };
+ */
+ memoization?: YggdrasilConduitClientMemoizationOption<ApiSpec["client"]>;
};
-async function doConduitRequest<ApiSpec extends YggdrasilConduitApi>(path: string[], params: unknown[], apiCtx: ApiSpec["apiCtx"], options: YggdrasilConduitClientOptions): Promise<{
+/**
+ * An object that defines which Conduit functions can be memoized.
+ */
+export type YggdrasilConduitClientMemoizationOption<ApiSpecClient> = undefined | boolean | {
+ [Property in keyof ApiSpecClient]?: ApiSpecClient[Property] extends (...args: any[]) => any ? boolean : YggdrasilConduitClientMemoizationOption<ApiSpecClient[Property]>;
+};
+
+export type YggdrasilConduitApiClient<ApiSpec extends YggdrasilConduitApi> = () => ApiSpec["client"];
+
+/**
+ * Maps an array of function arguments into a consistent JSON.stringify-safe array.
+ */
+function mapArgumentsToJsonSafe(args: unknown[]) {
+ let lastDefinedIndex: number;
+ for (lastDefinedIndex = args.length - 1; lastDefinedIndex >= 0; --lastDefinedIndex) {
+ if (args[lastDefinedIndex] !== undefined) break;
+ }
+
+ return args.slice(0, lastDefinedIndex + 1).map(arg => (arg === undefined ? "__jtc_ygg_conduit_undefined" : arg));
+}
+
+async function doConduitRequest<ApiSpec extends YggdrasilConduitApi>(path: string[], mappedArgs: unknown[], apiCtx: ApiSpec["apiCtx"], options: YggdrasilConduitClientOptions<ApiSpec>): Promise<{
response: Response;
outcome: YggdrasilConduitResponse<unknown, unknown>;
}> {
@@ -36,22 +69,22 @@
callURL.pathname = callURL.pathname + path.join("/");
const request: YggdrasilConduitRequest<ApiSpec["apiCtx"], unknown[]> = {
- parameters: params.map(param => (param === undefined ? "__jtc_ygg_undefined" : param)),
+ arguments: mappedArgs,
context: apiCtx
};
const response = await fetcher(callURL.href, {
method: "POST",
headers: {
- "Accept": "application/json+jottocraft-ygg-res",
- "Content-Type": "application/json+jottocraft-ygg-req"
+ "Accept": "application/vnd.jottocraft.ygg.conduit-res+json",
+ "Content-Type": "application/vnd.jottocraft.ygg.conduit-req+json"
},
body: JSON.stringify(request)
});
let outcome: YggdrasilConduitResponse<unknown, unknown>;
- if (response.headers.get("Content-Type") !== "application/json+jottocraft-ygg-res") {
- outcome = { success: false, status: { status: 500, code: "YGG_BAD_API_RESPONSE", message: "An unexpected response was received from the backend server." }, headers: { set: {}, append: [] } };
+ if (response.headers.get("Content-Type") !== "application/vnd.jottocraft.ygg.conduit-res+json") {
+ outcome = { success: false, status: { http: 500, code: "YGG_BAD_API_RESPONSE", message: "An unexpected response was received from the Conduit server." }, headers: { set: {}, append: [] } };
} else {
outcome = await response.json();
}
@@ -62,11 +95,25 @@
/**
* 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> {
+export function createConduitServerSideClient<ApiSpec extends YggdrasilConduitApi>(apiCtx: ApiSpec["apiCtx"], options: YggdrasilConduitServerSideClientOptions<ApiSpec>): YggdrasilConduitApiClient<ApiSpec> {
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);
+ const mappedArgs = mapArgumentsToJsonSafe(args);
+
+ let memoOption: YggdrasilConduitClientMemoizationOption<unknown> = options.memoization;
+ for (const segment of path) {
+ if (!memoOption || (typeof memoOption !== "object")) break;
+ memoOption = memoOption[segment as keyof typeof memoOption];
+ }
+
+ let outcome: YggdrasilConduitResponse<unknown, unknown>;
+ if (memoOption === true) {
+ const memoKey = "Yggdrasil::ConduitClient::" + stringify([path, mappedArgs]);
+ ({ outcome } = await this.memoize(memoKey, () => doConduitRequest(path, mappedArgs, apiCtx, options)));
+ } else {
+ ({ outcome } = await doConduitRequest(path, mappedArgs, apiCtx, options));
+ }
if (options.allowHeaderManipulation) {
const passHeadersTo: YggdrasilAdditionalHeaders = "upstreamHeaders" in this ? this.upstreamHeaders : this.additionalHeaders;
@@ -100,12 +147,13 @@
/**
* Creates a client for calling Yggdrasil Server Conduit-powered APIs from a client application.
*/
-export function createConduitClientSideClient<ApiSpec extends YggdrasilConduitApi>(apiCtx: ApiSpec["apiCtx"], options: YggdrasilConduitClientOptions): YggdrasilConduitApiClient<ApiSpec> {
+export function createConduitClientSideClient<ApiSpec extends YggdrasilConduitApi>(apiCtx: ApiSpec["apiCtx"], options: YggdrasilConduitClientOptions<ApiSpec>): 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);
+ const mappedArgs = mapArgumentsToJsonSafe(args);
+ const { outcome } = await doConduitRequest(path, mappedArgs, apiCtx, options);
if (outcome.success) {
return outcome.data;
diff --git a/yggdrasil/src/util/generateStatusPage.ts b/yggdrasil/src/util/generateStatusPage.ts
index c9a7172..99c184a 100644
--- a/yggdrasil/src/util/generateStatusPage.ts
+++ b/yggdrasil/src/util/generateStatusPage.ts
@@ -25,11 +25,11 @@
async function generateJsonStatusPage<AppTypes extends YggdrasilAppTypes>(ygg: YggdrasilServerContext<AppTypes>, e: YggdrasilStatus<unknown>): Promise<Response> {
return new Response(JSON.stringify({
success: false,
- status: e.status,
+ status: e.httpStatus,
error: e.statusCode,
message: e.statusMessage
}), {
- status: e.status,
+ status: e.httpStatus,
headers: {
"Content-Type": "application/json"
}
@@ -40,8 +40,8 @@
* Generates a human-readable plaintext status page for an uncaught YggdrasilStatus exception.
*/
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,
+ return new Response(`Error ${e.httpStatus} ${e.statusCode}${e.statusMessage ? ": " + e.statusMessage : ""}`, {
+ status: e.httpStatus,
headers: {
"Content-Type": "text/plain"
}
diff --git a/yggdrasil/tsconfig.json b/yggdrasil/tsconfig.json
index 0b181c4..3b10e3b 100644
--- a/yggdrasil/tsconfig.json
+++ b/yggdrasil/tsconfig.json
@@ -28,9 +28,9 @@
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
- "module": "commonjs", /* Specify what module code is generated. */
+ "module": "nodenext", /* Specify what module code is generated. */
"rootDir": "src", /* Specify the root folder within your source files. */
- "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
+ "moduleResolution": "nodenext", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
"paths": { /* Specify a set of entries that re-map imports to additional lookup locations. */
"~/*": ["./src/*"]