@tschk/moonshine-server 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,29 @@
1
+ # `@tschk/moonshine-server`
2
+
3
+ Web-standard request pipeline: middleware, loaders, actions, error boundaries,
4
+ and static files.
5
+
6
+ ```ts
7
+ import { createRequestHandler } from "@tschk/moonshine-server";
8
+
9
+ const fetch = createRequestHandler({
10
+ manifest,
11
+ modules,
12
+ renderer: reactRenderer,
13
+ staticDir: "./.moonshine",
14
+ });
15
+
16
+ Bun.serve({ fetch });
17
+ ```
18
+
19
+ Features:
20
+
21
+ - `createRequestHandler` matches routes and runs the full pipeline.
22
+ - Loaders and actions receive `RouteContext` with `request`, `params`, `signal`,
23
+ and `data`.
24
+ - `redirect`, `json`, `errorResponse` helpers.
25
+ - `serializeData` escapes HTML-sensitive characters and rejects cycles.
26
+ - `resolveStaticPath` / `tryServeStatic` for static file serving.
27
+
28
+ See [docs/ROUTING.md](../../docs/ROUTING.md) and
29
+ [DESIGN.md](../../DESIGN.md).
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "@tschk/moonshine-server",
3
+ "version": "0.3.1",
4
+ "license": "ISC",
5
+ "type": "module",
6
+ "main": "./src/index.ts",
7
+ "types": "./src/index.ts",
8
+ "exports": {
9
+ ".": "./src/index.ts"
10
+ },
11
+ "scripts": {
12
+ "format": "bunx prettier --check .",
13
+ "lint": "bunx oxlint .",
14
+ "typecheck": "bunx tsc --noEmit",
15
+ "test": "bun test"
16
+ },
17
+ "dependencies": {
18
+ "@tschk/moonshine-framework": "^0.3.1",
19
+ "@tschk/moonshine-router": "^0.3.1"
20
+ },
21
+ "devDependencies": {
22
+ "@types/bun": "1.3.14",
23
+ "typescript": "7.0.2"
24
+ },
25
+ "files": [
26
+ "src",
27
+ "README.md",
28
+ "LICENSE"
29
+ ]
30
+ }
package/src/data.ts ADDED
@@ -0,0 +1,76 @@
1
+ import type {
2
+ MoonshineManifest,
3
+ Renderer,
4
+ RouteDefinition,
5
+ } from "@tschk/moonshine-framework";
6
+ import type { RouteGraph } from "@tschk/moonshine-router";
7
+
8
+ export type RouteContext = {
9
+ request: Request;
10
+ params: Record<string, string>;
11
+ signal: AbortSignal;
12
+ data: Record<string, unknown>;
13
+ };
14
+
15
+ export type Loader = (context: RouteContext) => unknown | Promise<unknown>;
16
+
17
+ export type Action = (
18
+ context: RouteContext,
19
+ ) => unknown | Response | Promise<unknown | Response>;
20
+
21
+ export type Middleware = (
22
+ context: RouteContext,
23
+ next: () => Promise<Response>,
24
+ ) => Promise<Response>;
25
+
26
+ export type ErrorBoundary = (
27
+ context: RouteContext,
28
+ error: unknown,
29
+ ) => Response | Promise<Response>;
30
+
31
+ export type RouteModule = {
32
+ before?: Middleware[];
33
+ after?: Middleware[];
34
+ loader?: Loader;
35
+ action?: Action;
36
+ errorBoundary?: ErrorBoundary;
37
+ headers?: Record<string, string>;
38
+ };
39
+
40
+ export type RequestHandlerOptions = {
41
+ graph?: RouteGraph<RouteDefinition>;
42
+ routes?: RouteDefinition[];
43
+ manifest?: MoonshineManifest;
44
+ modules?: Record<string, RouteModule>;
45
+ renderer?: Renderer;
46
+ staticDir?: string;
47
+ mode?: "development" | "production";
48
+ defaultMeta?: ResponseInit;
49
+ notFound?: (context: RouteContext) => Response | Promise<Response>;
50
+ };
51
+
52
+ export function createRouteContext(
53
+ request: Request,
54
+ params: Record<string, string>,
55
+ ): RouteContext {
56
+ return {
57
+ request,
58
+ params,
59
+ signal: request.signal,
60
+ data: {},
61
+ };
62
+ }
63
+
64
+ export async function callLoader(
65
+ loader: Loader,
66
+ context: RouteContext,
67
+ ): Promise<unknown> {
68
+ return await loader(context);
69
+ }
70
+
71
+ export async function callAction(
72
+ action: Action,
73
+ context: RouteContext,
74
+ ): Promise<unknown | Response> {
75
+ return await action(context);
76
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,34 @@
1
+ export class Redirect extends Error {
2
+ status: number;
3
+ location: string;
4
+
5
+ constructor(location: string, status = 302) {
6
+ super(`Redirect to ${location}`);
7
+ this.name = "Redirect";
8
+ this.location = location;
9
+ this.status = status;
10
+ }
11
+ }
12
+
13
+ export function redirect(location: string, status = 302): never {
14
+ throw new Redirect(location, status);
15
+ }
16
+
17
+ export function json(data: unknown, init?: ResponseInit): Response {
18
+ const headers = new Headers(init?.headers);
19
+ if (!headers.has("content-type")) {
20
+ headers.set("content-type", "application/json; charset=utf-8");
21
+ }
22
+ return new Response(JSON.stringify(data), { ...init, headers });
23
+ }
24
+
25
+ export function errorResponse(
26
+ error: unknown,
27
+ mode?: "development" | "production",
28
+ ): Response {
29
+ const isDev = mode === "development";
30
+ const message = error instanceof Error ? error.message : String(error);
31
+ const stack = error instanceof Error ? error.stack : undefined;
32
+ const body = isDev && stack ? { error: message, stack } : { error: message };
33
+ return json(body, { status: 500 });
34
+ }
package/src/index.ts ADDED
@@ -0,0 +1,14 @@
1
+ export { createRequestHandler } from "./pipeline.js";
2
+ export { callAction, callLoader, createRouteContext } from "./data.js";
3
+ export { redirect, json, errorResponse, Redirect } from "./errors.js";
4
+ export { serializeData } from "./serialize.js";
5
+ export { resolveStaticPath, tryServeStatic } from "./static.js";
6
+ export type {
7
+ Action,
8
+ ErrorBoundary,
9
+ Loader,
10
+ Middleware,
11
+ RequestHandlerOptions,
12
+ RouteContext,
13
+ RouteModule,
14
+ } from "./data.js";
@@ -0,0 +1,308 @@
1
+ import { createRouteGraph, matchRoutes } from "@tschk/moonshine-router";
2
+ import type { RouteDefinition } from "@tschk/moonshine-framework";
3
+ import type {
4
+ ErrorBoundary,
5
+ Middleware,
6
+ RequestHandlerOptions,
7
+ RouteContext,
8
+ RouteModule,
9
+ } from "./data.js";
10
+ import { callAction, callLoader, createRouteContext } from "./data.js";
11
+ import { errorResponse, json, Redirect } from "./errors.js";
12
+ import { tryServeStatic } from "./static.js";
13
+
14
+ function hasControlChars(value: string): boolean {
15
+ for (let i = 0; i < value.length; i++) {
16
+ const code = value.charCodeAt(i);
17
+ if (code <= 0x1f || code === 0x7f) return true;
18
+ }
19
+ return false;
20
+ }
21
+
22
+ function isSafeRedirect(location: string, request: Request): boolean {
23
+ try {
24
+ if (hasControlChars(location)) return false;
25
+ const base = new URL(request.url);
26
+ const url = new URL(location, request.url);
27
+ return url.origin === base.origin;
28
+ } catch {
29
+ return false;
30
+ }
31
+ }
32
+
33
+ type ModuleChainItem = {
34
+ key: string;
35
+ module: RouteModule;
36
+ };
37
+
38
+ function buildModuleChain(
39
+ route: RouteDefinition,
40
+ modules: Record<string, RouteModule>,
41
+ ): ModuleChainItem[] {
42
+ const chain: ModuleChainItem[] = [];
43
+
44
+ for (const key of route.layouts ?? []) {
45
+ const module = modules[key];
46
+ if (module) chain.push({ key, module });
47
+ }
48
+
49
+ for (const key of route.middleware ?? []) {
50
+ const module = modules[key];
51
+ if (module) chain.push({ key, module });
52
+ }
53
+
54
+ const leafKeys: string[] = [
55
+ ...(route.dataFile ? [route.dataFile] : []),
56
+ route.id,
57
+ ...(route.file ? [route.file] : []),
58
+ ];
59
+
60
+ for (const key of leafKeys) {
61
+ const module = modules[key];
62
+ if (module) {
63
+ chain.push({ key, module });
64
+ break;
65
+ }
66
+ }
67
+
68
+ return chain;
69
+ }
70
+
71
+ function mergeHeaders(
72
+ ...sources: (HeadersInit | Record<string, string> | undefined)[]
73
+ ): Headers {
74
+ const headers = new Headers();
75
+
76
+ for (const source of sources) {
77
+ if (!source) continue;
78
+
79
+ if (source instanceof Headers) {
80
+ for (const [key, value] of source.entries()) {
81
+ headers.set(key, value);
82
+ }
83
+ } else if (Array.isArray(source)) {
84
+ for (const [key, value] of source) {
85
+ headers.set(key, value);
86
+ }
87
+ } else {
88
+ for (const [key, value] of Object.entries(
89
+ source as Record<string, string>,
90
+ )) {
91
+ headers.set(key, value);
92
+ }
93
+ }
94
+ }
95
+
96
+ return headers;
97
+ }
98
+
99
+ function finalizeResponse(
100
+ response: Response,
101
+ baseHeaders?: HeadersInit,
102
+ ): Response {
103
+ const headers = new Headers(baseHeaders);
104
+ for (const [key, value] of response.headers.entries()) {
105
+ headers.set(key, value);
106
+ }
107
+ return new Response(response.body, {
108
+ status: response.status,
109
+ statusText: response.statusText,
110
+ headers,
111
+ });
112
+ }
113
+
114
+ function findErrorBoundary(
115
+ chain: ModuleChainItem[],
116
+ route: RouteDefinition,
117
+ modules: Record<string, RouteModule>,
118
+ ): ErrorBoundary | undefined {
119
+ for (let i = chain.length - 1; i >= 0; i--) {
120
+ if (chain[i].module.errorBoundary) return chain[i].module.errorBoundary;
121
+ }
122
+
123
+ if (route.errorBoundary) {
124
+ const module = modules[route.errorBoundary];
125
+ if (module?.errorBoundary) return module.errorBoundary;
126
+ }
127
+
128
+ return undefined;
129
+ }
130
+
131
+ function resolveBaseHeaders(
132
+ chain: ModuleChainItem[],
133
+ route: RouteDefinition,
134
+ defaultMeta?: ResponseInit,
135
+ ): HeadersInit {
136
+ return mergeHeaders(
137
+ defaultMeta?.headers,
138
+ ...chain.map((c) => c.module.headers),
139
+ (route as { headers?: Record<string, string> }).headers,
140
+ );
141
+ }
142
+
143
+ async function runCoreAndAfters(
144
+ ctx: RouteContext,
145
+ chain: ModuleChainItem[],
146
+ options: RequestHandlerOptions,
147
+ route: RouteDefinition,
148
+ ): Promise<Response> {
149
+ const method = ctx.request.method;
150
+ const leaf = chain[chain.length - 1];
151
+
152
+ if (method !== "GET" && method !== "HEAD" && leaf?.module.action) {
153
+ const result = await callAction(leaf.module.action, ctx);
154
+ if (result instanceof Response) return result;
155
+ if (result !== undefined) {
156
+ if (leaf.module.loader) ctx.data.__action = result;
157
+ else ctx.data[leaf.key] = result;
158
+ }
159
+ }
160
+
161
+ const loaderEntries = chain.filter((c) => c.module.loader);
162
+ if (loaderEntries.length > 0) {
163
+ ctx.signal.throwIfAborted();
164
+ const results = await Promise.all(
165
+ loaderEntries.map(async (c) => {
166
+ const value = await callLoader(c.module.loader!, ctx);
167
+ return { key: c.key, value };
168
+ }),
169
+ );
170
+ for (const { key, value } of results) {
171
+ if (value !== undefined) ctx.data[key] = value;
172
+ }
173
+ }
174
+
175
+ ctx.signal.throwIfAborted();
176
+
177
+ let response: Response;
178
+ if (route.mode === "api") {
179
+ const leafData = leaf ? ctx.data[leaf.key] : undefined;
180
+ response = leafData instanceof Response ? leafData : json(ctx.data);
181
+ } else if (route.mode === "static" && options.staticDir) {
182
+ const pathname = new URL(ctx.request.url).pathname;
183
+ const staticRes = await tryServeStatic(options.staticDir, pathname);
184
+ if (staticRes) {
185
+ response = staticRes;
186
+ } else if (options.renderer) {
187
+ response = await options.renderer.render({
188
+ request: ctx.request,
189
+ route: route as any,
190
+ params: ctx.params,
191
+ data: ctx.data,
192
+ signal: ctx.signal,
193
+ });
194
+ } else {
195
+ throw new Error("No renderer for static route");
196
+ }
197
+ } else if (options.renderer) {
198
+ response = await options.renderer.render({
199
+ request: ctx.request,
200
+ route: route as any,
201
+ params: ctx.params,
202
+ data: ctx.data,
203
+ signal: ctx.signal,
204
+ });
205
+ } else {
206
+ response = json(ctx.data);
207
+ }
208
+
209
+ for (let i = chain.length - 1; i >= 0; i--) {
210
+ for (const after of chain[i].module.after ?? []) {
211
+ const next = async () => response;
212
+ response = await after(ctx, next);
213
+ }
214
+ }
215
+
216
+ return response;
217
+ }
218
+
219
+ function runBefores(
220
+ ctx: RouteContext,
221
+ index: number,
222
+ befores: Middleware[],
223
+ chain: ModuleChainItem[],
224
+ options: RequestHandlerOptions,
225
+ route: RouteDefinition,
226
+ ): Promise<Response> {
227
+ if (index >= befores.length) {
228
+ return runCoreAndAfters(ctx, chain, options, route);
229
+ }
230
+
231
+ const mw = befores[index]!;
232
+ const next = () => runBefores(ctx, index + 1, befores, chain, options, route);
233
+ return mw(ctx, next);
234
+ }
235
+
236
+ export function createRequestHandler(
237
+ options: RequestHandlerOptions,
238
+ ): (request: Request) => Promise<Response> {
239
+ return async (request) => {
240
+ const url = new URL(request.url);
241
+ const pathname = url.pathname.replace(/\/+$/, "") || "/";
242
+ const method = request.method;
243
+
244
+ if (
245
+ options.staticDir &&
246
+ (method === "GET" || method === "HEAD") &&
247
+ pathname !== "/"
248
+ ) {
249
+ const staticRes = await tryServeStatic(options.staticDir, pathname);
250
+ if (staticRes) return staticRes;
251
+ }
252
+
253
+ const graph =
254
+ options.graph ??
255
+ (options.routes
256
+ ? createRouteGraph(options.routes)
257
+ : options.manifest
258
+ ? createRouteGraph(options.manifest.routes)
259
+ : undefined);
260
+ if (!graph) {
261
+ return new Response("No route graph configured", { status: 500 });
262
+ }
263
+
264
+ const match = matchRoutes(graph, pathname);
265
+ if (!match) {
266
+ const ctx = createRouteContext(request, {});
267
+ return options.notFound
268
+ ? await options.notFound(ctx)
269
+ : new Response("Not Found", { status: 404 });
270
+ }
271
+
272
+ const route = match.route;
273
+ const ctx = createRouteContext(request, match.params);
274
+ const chain = buildModuleChain(route, options.modules ?? {});
275
+ const baseHeaders = resolveBaseHeaders(chain, route, options.defaultMeta);
276
+
277
+ try {
278
+ const befores: Middleware[] = [];
279
+ for (const c of chain) befores.push(...(c.module.before ?? []));
280
+ const response = await runBefores(ctx, 0, befores, chain, options, route);
281
+ return finalizeResponse(response, baseHeaders);
282
+ } catch (error) {
283
+ if (error instanceof Redirect) {
284
+ if (!isSafeRedirect(error.location, request)) {
285
+ return new Response("Invalid redirect", {
286
+ status: 400,
287
+ headers: baseHeaders,
288
+ });
289
+ }
290
+ const headers = new Headers(baseHeaders);
291
+ headers.set("location", error.location);
292
+ return new Response(null, { status: error.status, headers });
293
+ }
294
+
295
+ const boundary = findErrorBoundary(chain, route, options.modules ?? {});
296
+ if (boundary) {
297
+ const res = await boundary(ctx, error);
298
+ return finalizeResponse(res, baseHeaders);
299
+ }
300
+
301
+ if (error instanceof Response) {
302
+ return finalizeResponse(error, baseHeaders);
303
+ }
304
+
305
+ return finalizeResponse(errorResponse(error, options.mode), baseHeaders);
306
+ }
307
+ };
308
+ }
@@ -0,0 +1,86 @@
1
+ const ESCAPE_PATTERN = /[<>&\u2028\u2029]/g;
2
+
3
+ function escapeJsonChar(char: string): string {
4
+ return `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`;
5
+ }
6
+
7
+ export function serializeData(value: unknown): string {
8
+ const seen = new Set<unknown>();
9
+
10
+ function visit(v: unknown): string {
11
+ if (v === undefined || v === null) return "null";
12
+
13
+ const type = typeof v;
14
+
15
+ if (type === "boolean" || type === "number") {
16
+ if (Number.isNaN(v as number) || !Number.isFinite(v as number)) {
17
+ return "null";
18
+ }
19
+ return String(v);
20
+ }
21
+
22
+ if (type === "string") {
23
+ const raw = JSON.stringify(v);
24
+ if (raw === undefined)
25
+ throw new TypeError("serializeData: cannot serialize");
26
+ return raw;
27
+ }
28
+
29
+ if (type === "bigint" || type === "function" || type === "symbol") {
30
+ throw new TypeError(`serializeData: cannot serialize ${type}`);
31
+ }
32
+
33
+ if (seen.has(v)) throw new TypeError("serializeData: cyclic reference");
34
+
35
+ if (Array.isArray(v)) {
36
+ seen.add(v);
37
+ try {
38
+ const parts: string[] = [];
39
+ for (const item of v) {
40
+ parts.push(visit(item));
41
+ }
42
+ return `[${parts.join(",")}]`;
43
+ } finally {
44
+ seen.delete(v);
45
+ }
46
+ }
47
+
48
+ const proto = Object.prototype.toString.call(v);
49
+
50
+ if (proto === "[object Date]" || proto === "[object RegExp]") {
51
+ seen.add(v);
52
+ try {
53
+ const raw = JSON.stringify(v);
54
+ if (raw === undefined)
55
+ throw new TypeError("serializeData: cannot serialize");
56
+ return raw;
57
+ } finally {
58
+ seen.delete(v);
59
+ }
60
+ }
61
+
62
+ const symbols = Object.getOwnPropertySymbols(v);
63
+ if (symbols.length) {
64
+ throw new TypeError("serializeData: cannot serialize symbol");
65
+ }
66
+
67
+ seen.add(v);
68
+ try {
69
+ const parts: string[] = [];
70
+ for (const [key, val] of Object.entries(v as Record<string, unknown>)) {
71
+ if (typeof val === "function" || typeof val === "symbol") {
72
+ throw new TypeError(
73
+ "serializeData: cannot serialize function/symbol",
74
+ );
75
+ }
76
+ parts.push(`${visit(key)}:${visit(val)}`);
77
+ }
78
+ return `{${parts.join(",")}}`;
79
+ } finally {
80
+ seen.delete(v);
81
+ }
82
+ }
83
+
84
+ const raw = visit(value);
85
+ return raw.replace(ESCAPE_PATTERN, escapeJsonChar);
86
+ }
package/src/static.ts ADDED
@@ -0,0 +1,76 @@
1
+ import { join, normalize, resolve, sep } from "node:path";
2
+
3
+ function decodeSegment(part: string): string | null {
4
+ try {
5
+ return decodeURIComponent(part);
6
+ } catch {
7
+ return null;
8
+ }
9
+ }
10
+
11
+ const MIME: Record<string, string> = {
12
+ ".css": "text/css; charset=utf-8",
13
+ ".gif": "image/gif",
14
+ ".html": "text/html; charset=utf-8",
15
+ ".ico": "image/x-icon",
16
+ ".jpeg": "image/jpeg",
17
+ ".jpg": "image/jpeg",
18
+ ".js": "text/javascript; charset=utf-8",
19
+ ".json": "application/json; charset=utf-8",
20
+ ".map": "application/json; charset=utf-8",
21
+ ".mjs": "text/javascript; charset=utf-8",
22
+ ".png": "image/png",
23
+ ".svg": "image/svg+xml",
24
+ ".txt": "text/plain; charset=utf-8",
25
+ ".wasm": "application/wasm",
26
+ ".webp": "image/webp",
27
+ ".woff": "font/woff",
28
+ ".woff2": "font/woff2",
29
+ };
30
+
31
+ function extOf(path: string): string {
32
+ const i = path.lastIndexOf(".");
33
+ return i >= 0 ? path.slice(i).toLowerCase() : "";
34
+ }
35
+
36
+ export function resolveStaticPath(
37
+ staticDir: string,
38
+ pathname: string,
39
+ ): string | null {
40
+ const root = resolve(staticDir);
41
+ const parts = pathname.split("/").filter(Boolean);
42
+ const decoded: string[] = [];
43
+ for (const part of parts) {
44
+ const d = decodeSegment(part);
45
+ if (
46
+ d === null ||
47
+ d === "." ||
48
+ d === ".." ||
49
+ d.includes("\0") ||
50
+ d.includes(sep) ||
51
+ d.includes("/")
52
+ )
53
+ return null;
54
+ decoded.push(d);
55
+ }
56
+ if (decoded.length === 0) return null;
57
+ const candidate = normalize(join(root, ...decoded));
58
+ if (candidate !== root && !candidate.startsWith(root + sep)) return null;
59
+ return candidate;
60
+ }
61
+
62
+ export async function tryServeStatic(
63
+ staticDir: string,
64
+ pathname: string,
65
+ ): Promise<Response | null> {
66
+ if (typeof Bun === "undefined") return null;
67
+ const filePath = resolveStaticPath(staticDir, pathname);
68
+ if (!filePath) return null;
69
+ const file = Bun.file(filePath);
70
+ if (!(await file.exists())) return null;
71
+ const type =
72
+ MIME[extOf(filePath)] ?? (file.type || "application/octet-stream");
73
+ return new Response(file, {
74
+ headers: { "content-type": type },
75
+ });
76
+ }