@mastrojs/mastro 0.0.0-stage → 0.9.0

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.
Files changed (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +60 -2
  3. package/dist/cli.d.ts +3 -0
  4. package/dist/cli.d.ts.map +1 -0
  5. package/dist/cli.js +92 -0
  6. package/dist/core/fs.d.ts +67 -0
  7. package/dist/core/fs.d.ts.map +1 -0
  8. package/dist/core/fs.js +114 -0
  9. package/dist/core/fsHelpers.d.ts +18 -0
  10. package/dist/core/fsHelpers.d.ts.map +1 -0
  11. package/dist/core/fsHelpers.js +17 -0
  12. package/dist/core/html.d.ts +67 -0
  13. package/dist/core/html.d.ts.map +1 -0
  14. package/dist/core/html.js +201 -0
  15. package/dist/core/responses.d.ts +98 -0
  16. package/dist/core/responses.d.ts.map +1 -0
  17. package/dist/core/responses.js +145 -0
  18. package/dist/core/routeHelpers.d.ts +12 -0
  19. package/dist/core/routeHelpers.d.ts.map +1 -0
  20. package/dist/core/routeHelpers.js +51 -0
  21. package/dist/generator.d.ts +16 -0
  22. package/dist/generator.d.ts.map +1 -0
  23. package/dist/generator.js +124 -0
  24. package/dist/index.d.ts +13 -0
  25. package/dist/index.d.ts.map +1 -0
  26. package/dist/index.js +10 -0
  27. package/dist/mastro.d.ts +58 -0
  28. package/dist/mastro.d.ts.map +1 -0
  29. package/dist/mastro.js +93 -0
  30. package/dist/middleware.d.ts +4 -0
  31. package/dist/middleware.d.ts.map +1 -0
  32. package/dist/middleware.js +21 -0
  33. package/dist/middlewares/fingerprintAssets.d.ts +3 -0
  34. package/dist/middlewares/fingerprintAssets.d.ts.map +1 -0
  35. package/dist/middlewares/fingerprintAssets.js +35 -0
  36. package/dist/middlewares/logger.d.ts +4 -0
  37. package/dist/middlewares/logger.d.ts.map +1 -0
  38. package/dist/middlewares/logger.js +41 -0
  39. package/dist/middlewares/staticFiles/mediaTypes.d.ts +6 -0
  40. package/dist/middlewares/staticFiles/mediaTypes.d.ts.map +1 -0
  41. package/dist/middlewares/staticFiles/mediaTypes.js +26 -0
  42. package/dist/middlewares/staticFiles/mediaTypes.json +910 -0
  43. package/dist/middlewares/staticFiles/staticFiles.d.ts +10 -0
  44. package/dist/middlewares/staticFiles/staticFiles.d.ts.map +1 -0
  45. package/dist/middlewares/staticFiles/staticFiles.js +119 -0
  46. package/dist/middlewares/tsToJs.d.ts +13 -0
  47. package/dist/middlewares/tsToJs.d.ts.map +1 -0
  48. package/dist/middlewares/tsToJs.js +49 -0
  49. package/dist/servers/fileRouter.d.ts +11 -0
  50. package/dist/servers/fileRouter.d.ts.map +1 -0
  51. package/dist/servers/fileRouter.js +74 -0
  52. package/dist/servers/fileRoutes.d.ts +2 -0
  53. package/dist/servers/fileRoutes.d.ts.map +1 -0
  54. package/dist/servers/fileRoutes.js +1 -0
  55. package/dist/servers/server.d.ts +22 -0
  56. package/dist/servers/server.d.ts.map +1 -0
  57. package/dist/servers/server.js +21 -0
  58. package/dist/types/mastro.d.ts +80 -0
  59. package/dist/types/middleware.d.ts +157 -0
  60. package/dist/types/standard-schema.d.ts +76 -0
  61. package/package.json +52 -3
  62. package/src/README.md +29 -0
  63. package/src/cli.ts +89 -0
  64. package/src/core/fs.ts +131 -0
  65. package/src/core/fsHelpers.ts +24 -0
  66. package/src/core/html.ts +226 -0
  67. package/src/core/responses.ts +175 -0
  68. package/src/core/routeHelpers.ts +60 -0
  69. package/src/generator.ts +139 -0
  70. package/src/index.ts +14 -0
  71. package/src/mastro.ts +116 -0
  72. package/src/middleware.ts +28 -0
  73. package/src/middlewares/fingerprintAssets.ts +37 -0
  74. package/src/middlewares/logger.ts +43 -0
  75. package/src/middlewares/staticFiles/mediaTypes.json +910 -0
  76. package/src/middlewares/staticFiles/mediaTypes.ts +28 -0
  77. package/src/middlewares/staticFiles/staticFiles.ts +136 -0
  78. package/src/middlewares/tsToJs.ts +43 -0
  79. package/src/servers/fileRouter.ts +83 -0
  80. package/src/servers/fileRoutes.ts +1 -0
  81. package/src/servers/server.ts +29 -0
  82. package/src/types/mastro.d.ts +80 -0
  83. package/src/types/middleware.d.ts +157 -0
  84. package/src/types/standard-schema.d.ts +76 -0
@@ -0,0 +1,175 @@
1
+ import { readTextFile } from "./fs.ts";
2
+ import { type Html, isAsyncIterable, renderToStream } from "./html.ts";
3
+
4
+ /**
5
+ * Create a standard Response object with `Content-Type: text/html` from a string
6
+ * or `AsyncIterable<string>` (in which case it will stream it).
7
+ */
8
+ export const htmlResponse = (
9
+ body: string | AsyncIterable<string>,
10
+ status = 200,
11
+ headers?: Record<string, string>,
12
+ ): Response =>
13
+ new Response(
14
+ isAsyncIterable(body) ? toReadableStream(body) : body,
15
+ { status, headers: { "Content-Type": "text/html; charset=utf-8", ...headers } },
16
+ );
17
+
18
+ /**
19
+ * Create a standard Response object from an `Html` node.
20
+ */
21
+ export const htmlToResponse = (node: Html): Response =>
22
+ htmlResponse(renderToStream(node));
23
+
24
+ /**
25
+ * Create a standard Response object with `Content-Type: application/json`.
26
+ */
27
+ export const jsonResponse = (
28
+ body: object,
29
+ status = 200,
30
+ headers?: Record<string, string>,
31
+ ): Response =>
32
+ new Response(JSON.stringify(body), {
33
+ status,
34
+ headers: { "Content-Type": "application/json", ...headers },
35
+ });
36
+
37
+ /**
38
+ * Create a standard Response object to stream an `AsyncIterable` of JSON data as
39
+ * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events).
40
+ */
41
+ export const sseResponse = <T extends object>(
42
+ stream: AsyncIterable<T>,
43
+ headers?: Record<string, string>,
44
+ ): Response =>
45
+ new Response(
46
+ toReadableStream(mapIterable(stream, (chunk) => `data: ${JSON.stringify(chunk)}\n\n`)),
47
+ { headers: { "Content-Type": "text/event-stream", ...headers } },
48
+ );
49
+
50
+ /**
51
+ * Returns the hashed path of a fingerprinted asset, as set by the fingerprintAssets middleware.
52
+ *
53
+ * - During static site generation, it reads from an in-memory map.
54
+ * - When running a production server, you need to run `mastro generate --only-pregenerate` in your
55
+ * CI, which will create a `generatedAssets.json` file, which this function will then read from.
56
+ * See the [Mastro Guide](https://mastrojs.github.io/guide/caching-service-workers-streaming/#fingerprinting-assets-with-hash-based-file-names).
57
+ * Don't forget to set your CDN's caching headers for `/_assets/*` to something like
58
+ * `Cache-Control: public, max-age=31556952, immutable` (1 year), otherwise hashing is little use.
59
+ *
60
+ * - Finally, when running the dev server, hashing all assets would be too slow. Thus if no
61
+ * `generatedAssets.json` file is present on server start, this function returns the unhashed
62
+ * input path prefixed with `/_assets/`. Therefore, be sure to delete `generatedAssets.json` after
63
+ * trying out `mastro generate --only-pregenerate` locally.
64
+ *
65
+ * Usage in your template, if you have e.g. a `routes/_assets/logo.webp` file:
66
+ *
67
+ * ```
68
+ * import { asset, html } from "@mastrojs/mastro";
69
+ *
70
+ * export const Header = () =>
71
+ * html`<header><img src=${asset("logo.webp")}></header>`;
72
+ * ```
73
+ */
74
+ export const asset = (path: string): string =>
75
+ (globalThis as any)._mastroAssets?.[path] || (/_assets/ + path);
76
+
77
+ /**
78
+ * [Identity tag literal](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw#building_an_identity_tag)
79
+ * which does no escaping: do not pass it untrusted input.
80
+ *
81
+ * ```ts
82
+ * export const styles = css`
83
+ * p {
84
+ * font-size: ${2 * 3}em;
85
+ * }
86
+ * `;
87
+ * ```
88
+ *
89
+ * For more usage examples, see
90
+ * [Component-scoped CSS without a build step](https://mastrojs.github.io/blog/2026-05-26-component-scoped-css-without-build-step/).
91
+ */
92
+ export const css = (strings: TemplateStringsArray, ...values: Array<string | number>): string =>
93
+ String.raw({ raw: strings }, ...values);
94
+
95
+ const toReadableStream = (iterable: AsyncIterable<string>) => {
96
+ // TODO: check back when and if something like the following works and is more performant:
97
+ // return ReadableStream.from(iterable.map(str => encoder.encode(str)));
98
+
99
+ const encoder = new TextEncoder();
100
+ const iterator = iterable[Symbol.asyncIterator]();
101
+ let canceled = false;
102
+ return new ReadableStream({
103
+ async pull(controller) {
104
+ try {
105
+ const { value, done } = await iterator.next();
106
+ if (done) {
107
+ controller.close();
108
+ } else {
109
+ controller.enqueue(encoder.encode(value));
110
+ }
111
+ } catch (e) {
112
+ if (canceled) return;
113
+ console.error("Response failed mid-stream", e);
114
+ controller.error(e);
115
+ }
116
+ },
117
+ async cancel() {
118
+ canceled = true;
119
+ await iterator.return?.();
120
+ },
121
+ });
122
+ };
123
+
124
+ /**
125
+ * Returns the GitHub Pages base path (or an empty string).
126
+ *
127
+ * If you're hosting your website with GitHub Pages on a sub-directory
128
+ * (e.g. `https://my-name.github.io/my-repo` instead of `https://my-name.github.io`
129
+ * or instead of a custom domain), then you need to prefix all absolute links
130
+ * that start with a slash with your base path (`/my-repo` in this case),
131
+ * which is what this function returns when run on GitHub Actions.
132
+ *
133
+ * For example in your `Layout.ts` file:
134
+ *
135
+ * ```ts
136
+ * import { ghPagesBasePath, html } from "@mastrojs/mastro";
137
+ * export const basePath = ghPagesBasePath(); // export for use in other modules
138
+ * export const Layout = () =>
139
+ * html`
140
+ * <html>
141
+ * <head>
142
+ * <link href=${basePath + "/styles.css"}>
143
+ * `;
144
+ * ```
145
+ *
146
+ * btw. if you're not on GitHub Pages, but still hosting in a sub-directory, you can
147
+ * change the `generate` command in `package.json` to `BASEPATH='/my-path' mastro generate`,
148
+ * and use that like:
149
+ *
150
+ * ```ts
151
+ * export const basePath = process.env.BASEPATH || ""; // export for use in other modules
152
+ * export const Layout = () =>
153
+ * html`
154
+ * <html>
155
+ * <head>
156
+ * <link href=${basePath + "/styles.css"}>
157
+ * `;
158
+ * ```
159
+ */
160
+ export const ghPagesBasePath = (): string => {
161
+ if (typeof window === "undefined") {
162
+ // see https://docs.github.com/en/actions/reference/workflows-and-actions/variables
163
+ const repo = process.env.GITHUB_REPOSITORY?.split("/")[1];
164
+ if (repo && !repo.endsWith(".github.io")) {
165
+ return "/" + repo;
166
+ }
167
+ }
168
+ return "";
169
+ };
170
+
171
+ async function* mapIterable<T, R>(iter: AsyncIterable<T>, cb: (val: T) => R): AsyncIterable<R> {
172
+ for await (const val of iter) {
173
+ yield cb(val);
174
+ }
175
+ }
@@ -0,0 +1,60 @@
1
+ import type { Handler, Route } from "../types/mastro.d.ts";
2
+ import type { Context } from "../types/middleware.d.ts";
3
+
4
+ /**
5
+ * Attempts to determine whether we're running a development or production server.
6
+ *
7
+ * Currently this is done by checking whether the hostname is localhost, which is not perfect
8
+ * but allows you to test production behaviour by connecting to `127.0.0.1` and
9
+ * is easy to do without messing with environment variables.
10
+ */
11
+ export const isDevServer = (url: URL): boolean => url.hostname === "localhost";
12
+
13
+ export const routeHandler =
14
+ <E>(rs: Route<Context<E>>[] | Promise<Route<Context<E>>[]>): Handler<Context<E>> =>
15
+ async (req, ctx) => {
16
+ const routes = await rs;
17
+ const method = req.method.toUpperCase();
18
+ const isDev = ctx.mode === "generator" || ctx.environment === "development";
19
+
20
+ let urlMatched: string | undefined;
21
+ let params: Record<string, string | undefined> = {};
22
+ const findRoute = (method: string) =>
23
+ routes.find((r) => {
24
+ const match = r.pattern.exec(req.url);
25
+ if (!match) return false;
26
+ urlMatched = r.name;
27
+ if ((r.method === method || r.method === "all") && typeof r.handler === "function") {
28
+ params = match.pathname.groups;
29
+ return true;
30
+ }
31
+ });
32
+ const route = findRoute(method) ?? (method === "HEAD" ? findRoute("GET") : undefined);
33
+
34
+ if (route) {
35
+ if (route.pregenerate && !isDev && ctx.mode === "server") {
36
+ return new Response(
37
+ "404 Route was hit on non-localhost but has `pregenerate` set. " +
38
+ "Did you forget to run `mastro/generator --only-pregenerate` as a build step?",
39
+ { status: 404 },
40
+ );
41
+ }
42
+ let res = await route.handler(req, { ...ctx, params });
43
+ if (!(res instanceof Response)) {
44
+ throw Error(`${method} handler in ${route.name} ${noResponseErr}`);
45
+ }
46
+ if (method === "HEAD") {
47
+ res.body?.cancel().catch(() => {});
48
+ res = new Response(null, res);
49
+ }
50
+ return isDev ? Object.assign(res, { routeName: route.name }) : res;
51
+ } else if (urlMatched) {
52
+ const msg = `405 Method Not Allowed\n\nNo ${method} handler found`;
53
+ const m = isDev ? ` by ${urlMatched}\n\nsee https://mastrojs.github.io/docs/routing/` : "";
54
+ return new Response(msg + m, { status: 405 });
55
+ } else {
56
+ const res = new Response("404 Not Found", { status: 404 });
57
+ return isDev ? Object.assign(res, { error: "No route match" }) : res;
58
+ }
59
+ };
60
+ const noResponseErr = "must return a Response object. Did you forget \`htmlToResponse\`?";
@@ -0,0 +1,139 @@
1
+ /**
2
+ * This module contains all functions related to static site generation.
3
+ * It is used both by the [vscode-extension](../../../vscode-extension/) and
4
+ * by the [static site generator on the CLI](https://mastrojs.github.io/docs/install-setup/#generate-a-static-site).
5
+ * @module
6
+ */
7
+
8
+ import fs from "node:fs/promises";
9
+ import { dirname, join, posix } from "node:path";
10
+
11
+ import { urlPathToFilePath } from "./core/fsHelpers.ts";
12
+ import { routeHandler } from "./core/routeHelpers.ts";
13
+ import type { Mastro } from "./mastro.ts";
14
+ import { chainMiddlewares } from "./middleware.ts";
15
+ import { middlewares } from "./servers/server.ts";
16
+ import type { Handler, Route, Simplify } from "./types/mastro.d.ts";
17
+ import type { Context, GeneratorCtxSimple } from "./types/middleware.d.ts";
18
+
19
+ /**
20
+ * Generate all pages for the static site and write them to disk.
21
+ *
22
+ * Can not be used in the VSCode extension.
23
+ */
24
+ export const generate = async <E extends unknown[], L>(
25
+ app: Mastro<E, L>,
26
+ opts: Simplify<Partial<GeneratorCtxSimple<Context<E>>>> = {},
27
+ ): Promise<boolean> => {
28
+ const ctx = {
29
+ baseUrl: opts.baseUrl || "http://127.0.0.1",
30
+ extras: (opts.extras || []) as E,
31
+ onlyPregenerate: !!opts.onlyPregenerate,
32
+ outFolder: opts.outFolder || "generated",
33
+ mode: "generator",
34
+ } satisfies GeneratorCtxSimple<Context<E>>;
35
+ const { outFolder } = ctx;
36
+
37
+ const resetP = fs.rm(outFolder, { force: true, recursive: true }).then(() => fs.mkdir(outFolder));
38
+
39
+ const ms = app.getMiddlewares();
40
+ if (ms.every((m) => m.name !== "staticFiles")) {
41
+ // when we get passed an app for Cloudflare Workers or similar, we add staticFiles etc.
42
+ console.info("Did not find a staticFiles middleware, adding defaultMiddlewares.\n");
43
+ ms.unshift(...middlewares);
44
+ }
45
+
46
+ const routes = await app.getRoutes();
47
+ const handler = chainMiddlewares(ms, routeHandler(routes));
48
+
49
+ await resetP;
50
+ await Promise.all(ms.map((m) => ("beforeGenerate" in m ? m.beforeGenerate?.(ctx) : null)));
51
+ let completeSuccess = true;
52
+
53
+ for (const path of await getPaths(ctx, ...ms, routePaths(routes))) {
54
+ // TODO: parallelize without opening too many file handles at once
55
+ const url = new URL(path, ctx.baseUrl);
56
+ const context = { ...ctx, locals: {}, params: {} };
57
+ const { response, outFilePath } = await generatePage(handler, url, context);
58
+ if (response.ok) {
59
+ const outPath = join(outFolder, outFilePath);
60
+ await fs.mkdir(dirname(outPath), { recursive: true });
61
+ if (response.body) {
62
+ await fs.writeFile(outPath, response.body);
63
+ } else {
64
+ console.warn(`\nWARNING: ${path} returned no body (HTTP ${response.status})\n.`);
65
+ }
66
+ } else if (response.status !== 404) {
67
+ completeSuccess = false;
68
+ }
69
+ }
70
+ if (completeSuccess) {
71
+ await Promise.all(ms.map((m) => ("afterGenerate" in m ? m.afterGenerate?.(ctx) : null)));
72
+ console.info(`Generated static site and wrote to \`${outFolder}\` folder.`);
73
+ }
74
+ return completeSuccess;
75
+ };
76
+
77
+ /**
78
+ * call getStaticPaths of all middlewares and set things up for the fingerprintAssets middleware.
79
+ */
80
+ const getPaths = async <E, C = GeneratorCtxSimple<Context<E>>>(ctx: C, ...middlewares: Ms<C>[]) => {
81
+ (globalThis as any)._mastroAssets = {};
82
+ const paths = middlewares.flatMap(async (m) =>
83
+ m.getStaticPaths ? validateStaticPaths(m.name, await m.getStaticPaths(ctx)) : [],
84
+ );
85
+ const assetPaths: string[] = [];
86
+ const otherPaths: string[] = [];
87
+ for (const p of (await Promise.all(paths)).flat()) {
88
+ (p.startsWith("/_assets/") ? assetPaths : otherPaths).push(p);
89
+ }
90
+ return assetPaths.concat(otherPaths);
91
+ };
92
+ type Ms<C> = { name: string; getStaticPaths?: (ctx: C) => Promise<string[]> | string[] };
93
+
94
+ const generatePage = async <C>(handler: Handler<C>, url: URL, ctx: C) => {
95
+ const req = new Request(url);
96
+ const response = await handler(req, ctx);
97
+ const filename = parseContentDisposition(response.headers.get("Content-Disposition"));
98
+ const directory = url.pathname.slice(0, url.pathname.lastIndexOf("/") + 1);
99
+ const path = filename ? directory + filename : url.pathname;
100
+ const outFilePath = urlPathToFilePath(path.endsWith("/") ? `${path}index.html` : path);
101
+ return { response, outFilePath };
102
+ };
103
+
104
+ const parseContentDisposition = (val: string | null) => val?.match(/filename="?([^";]+)"?/i)?.[1];
105
+
106
+ const validateStaticPaths = (name: string, paths: string[]) => {
107
+ const prefix = `${name}"#getStaticPaths`;
108
+ const notStringMsg = " must return an array of strings";
109
+ if (!Array.isArray(paths)) throw Error(prefix + notStringMsg);
110
+ for (const path of paths) {
111
+ if (typeof path !== "string") throw Error(prefix + notStringMsg);
112
+ if (path[0] !== "/") throw Error(prefix + ": paths must start with a slash (/)");
113
+ if (path.includes("#") || path.includes("?") || path.includes("\\")) {
114
+ throw Error(`${prefix} must return encoded URL paths. Use encodeURIComponent.`);
115
+ }
116
+ if (!path.endsWith("/") && !posix.extname(path) && !path.startsWith("/.well-known/")) {
117
+ console.warn(`\nWARNING: ${name} has path ${path} without file extension.
118
+ Consider renaming route to e.g. ${name.replace(".server", ".html.server")}\n`);
119
+ }
120
+ }
121
+ return paths;
122
+ };
123
+
124
+ const routePaths = <E>(routes: Route<Context<E>>[]) => ({
125
+ name: "router",
126
+ getStaticPaths: async (ctx: GeneratorCtxSimple<Context<E>>) => {
127
+ const paths = (ctx.onlyPregenerate ? routes.filter((r) => r.pregenerate) : routes)
128
+ .filter((r) => r.method === "GET" || r.method === "all")
129
+ .map(async (r) => {
130
+ if (typeof r.getStaticPaths === "function") return r.getStaticPaths();
131
+ if (hasRouteParams.test(r.pattern.pathname)) throw Error(r.name + staticPathErrMsg);
132
+ return r.pattern.pathname.replace(/\\(.)/g, "$1"); // unescape URLPattern syntax
133
+ });
134
+ return (await Promise.all(paths.reverse())).flat();
135
+ },
136
+ });
137
+ // URLPattern parameters, wildcards, and groups require concrete paths:
138
+ const hasRouteParams = /(?<!\\)[:*{(]/;
139
+ const staticPathErrMsg = " should provide a getStaticPaths function returning an array of strings.";
package/src/index.ts ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * `@mastrojs/mastro` is the main entry point and exports
3
+ * all functions runnable in both Deno/Node.js/Bun and the browser
4
+ * (i.e. the VSCode extension environment).
5
+ * @module
6
+ */
7
+
8
+ export * from "./core/fs.ts";
9
+ export * from "./core/html.ts";
10
+ export * from "./core/responses.ts";
11
+ export * from "./mastro.ts";
12
+
13
+ export type { Handler, Route, RouteParams } from "./types/mastro.d.ts";
14
+ export type { Context, Middleware, MiddlewareContext } from "./types/middleware.d.ts";
package/src/mastro.ts ADDED
@@ -0,0 +1,116 @@
1
+ import { isDevServer, routeHandler } from "./core/routeHelpers.ts";
2
+ import { chainMiddlewares } from "./middleware.ts";
3
+ import type { Handler, Pathname, Route, RouteHandler, Simplify } from "./types/mastro.d.ts";
4
+ import type { CompatibleLocals, Context, Middleware } from "./types/middleware.d.ts";
5
+
6
+ /** Array of HTTP methods */
7
+ const httpMethods = ["GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "PATCH", "QUERY"] as const;
8
+ export { httpMethods };
9
+
10
+ /** HTTP methods */
11
+ export type HttpMethod = (typeof httpMethods)[number];
12
+
13
+ /**
14
+ * Class to construct an app instance.
15
+
16
+ * ```ts
17
+ * const app = new Mastro()
18
+ * .use(myMiddleware)
19
+ * .get("/", (req, ctx) => new Response("Hi"))
20
+ * ```
21
+ *
22
+ * For Node.js and Bun, use the `createApp` or `createFileRouterApp`
23
+ * factories that you can import from "@mastrojs/mastro/server".
24
+ *
25
+ * For the types to get passed through correctly, be sure to chain the method calls as shown above.
26
+ * Otherwise, the generics for URL path parameters, and locals set by middleware, won't be inferred
27
+ * correctly. When using TypeScript, do NOT do something like the following:
28
+ *
29
+ * ```js
30
+ * const badApp = new Mastro();
31
+ * badApp.use(authMiddleware);
32
+ * badApp.get("/", handler);
33
+ * ```
34
+ */
35
+ export class Mastro<E extends unknown[] = unknown[], L = {}> {
36
+ private middlewares: Middleware<{}, Context<E>>[] = [];
37
+ private routes: Route<Context<E>>[] = [];
38
+ private routesPromise?: Route<Context<E>>[] | Promise<Route<Context<E>>[]>;
39
+
40
+ constructor(opts?: { routes?: Route<Context<E>>[] | Promise<Route<Context<E>>[]> }) {
41
+ this.routesPromise = opts?.routes;
42
+ }
43
+
44
+ /** Get a read-only snapshot of registered middleware in execution order. */
45
+ getMiddlewares(): Middleware<{}, Context<E>>[] {
46
+ return [...this.middlewares];
47
+ }
48
+
49
+ /** Get all routes. */
50
+ async getRoutes(): Promise<Route<Context<E>>[]> {
51
+ return ((await this.routesPromise) || []).concat(this.routes);
52
+ }
53
+
54
+ /** Add a {@link Middleware} to the stack. Chain calls to pass locals to subsequent middleware. */
55
+ use<SetL = {}>(
56
+ middleware: Middleware<SetL, Context<E, L>> & CompatibleLocals<L, SetL>,
57
+ ): Mastro<E, Simplify<L & Omit<SetL, keyof L>>> {
58
+ this.middlewares.push(middleware as any);
59
+ return this as any;
60
+ }
61
+
62
+ /** Add route */
63
+ addRoute<P extends Pathname>(
64
+ method: "all" | HttpMethod,
65
+ pathname: P,
66
+ opts: RouteHandler<E, L, P>,
67
+ ): this {
68
+ if (typeof opts === "function") opts = { handler: opts };
69
+ this.routes.push({
70
+ getStaticPaths: opts.getStaticPaths,
71
+ handler: opts.handler as Handler<Context<E>>,
72
+ method,
73
+ name: pathname,
74
+ pattern: new URLPattern({ pathname }),
75
+ pregenerate: opts.pregenerate,
76
+ });
77
+ return this;
78
+ }
79
+
80
+ /** Add HTTP GET route */
81
+ get<P extends Pathname>(pathname: P, handler: RouteHandler<E, L, P>): this {
82
+ return this.addRoute("GET", pathname, handler);
83
+ }
84
+
85
+ /** Add HTTP POST route */
86
+ post<P extends Pathname>(pathname: P, handler: RouteHandler<E, L, P>): this {
87
+ return this.addRoute("POST", pathname, handler);
88
+ }
89
+
90
+ /** Add HTTP PUT route */
91
+ put<P extends Pathname>(pathname: P, handler: RouteHandler<E, L, P>): this {
92
+ return this.addRoute("PUT", pathname, handler);
93
+ }
94
+
95
+ /** Add HTTP DELETE route */
96
+ delete<P extends Pathname>(pathname: P, handler: RouteHandler<E, L, P>): this {
97
+ return this.addRoute("DELETE", pathname, handler);
98
+ }
99
+
100
+ /** Create fetch handler */
101
+ createHandler(ctx?: {
102
+ environment?: "development" | "production";
103
+ }): (req: Request, ...extras: E) => Promise<Response> {
104
+ const handler = chainMiddlewares<E>(this.middlewares, routeHandler(this.getRoutes()));
105
+ return async (req, ...extras) => {
106
+ const url = new URL(req.url);
107
+ const environment = isDevServer(url) ? ("development" as const) : ("production" as const);
108
+ const mode = "server" as const;
109
+ const c = { environment, ...ctx, extras, locals: {}, params: {}, mode };
110
+ const res = await handler(req, c);
111
+ // if the logger middleware is not present, we let the platform (e.g. wrangler) show errors:
112
+ if (c.environment === "development" && res.status >= 500 && "error" in res) throw res.error;
113
+ return res;
114
+ };
115
+ }
116
+ }
@@ -0,0 +1,28 @@
1
+ import type { Handler } from "./types/mastro.d.ts";
2
+ import type { Context, Middleware } from "./types/middleware.d.ts";
3
+
4
+ export const chainMiddlewares = <E = unknown[]>(
5
+ middlewares: Middleware<{}, Context<E>>[],
6
+ terminal: Handler<Context<E>>,
7
+ index = 0,
8
+ ): Handler<Context<E>> => {
9
+ const middleware = middlewares[index];
10
+ const handler = typeof middleware === "function" ? middleware : middleware?.handler;
11
+ const next = handler ? chainMiddlewares<E>(middlewares, terminal, index + 1) : terminal;
12
+ return async (req, ctx) => {
13
+ try {
14
+ const res = handler
15
+ ? await handler(req, {
16
+ ...ctx,
17
+ fetchNext: (r, locals) => next(r, { ...ctx, locals: { ...ctx.locals, ...locals } }),
18
+ })
19
+ : await next(req, ctx);
20
+ if (res instanceof Response) return res;
21
+ throw new Error(
22
+ `Function '${(handler || terminal).name || "<anonymous>"}' did not return a Response object`,
23
+ );
24
+ } catch (error) {
25
+ return Object.assign(new Response("500 Internal Server Error", { status: 500 }), { error });
26
+ }
27
+ };
28
+ };
@@ -0,0 +1,37 @@
1
+ import { createHash } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import { posix } from "node:path";
4
+
5
+ import { readTextFile } from "../core/fs.ts";
6
+ import type { Middleware } from "../types/middleware.d.ts";
7
+
8
+ const g = globalThis as typeof globalThis & { _mastroAssets: Record<string, string | undefined> };
9
+ g._mastroAssets = await readTextFile("generatedAssets.json").then(JSON.parse).catch(() => ({}));
10
+
11
+ export const fingerprintAssets: Middleware = {
12
+ name: "fingerprintAssets",
13
+ handler: async (req, ctx) => {
14
+ const res = await ctx.fetchNext(req);
15
+ if (!res.ok) return res;
16
+ const { pathname } = new URL(req.url);
17
+ if (ctx.mode === "generator" && pathname.startsWith("/_assets/")) {
18
+ const ext = posix.extname(pathname);
19
+ const data = await res.arrayBuffer().then(Buffer.from);
20
+ const digest = createHash("sha256").update(data).digest("hex").slice(0, 8);
21
+ const hashedPath = `${pathname.slice(0, pathname.length - ext.length)}-${digest}${ext}`;
22
+ g._mastroAssets[pathname.slice("/_assets/".length)] = hashedPath;
23
+ res.headers.set("Content-Disposition", `attachment; filename=${posix.basename(hashedPath)}`);
24
+ return new Response(data, res);
25
+ } else {
26
+ return res;
27
+ }
28
+ },
29
+ beforeGenerate: async () => {
30
+ g._mastroAssets = {};
31
+ },
32
+ afterGenerate: async (ctx) => {
33
+ if (ctx.onlyPregenerate && Object.keys(g._mastroAssets).length > 0) {
34
+ await fs.writeFile("generatedAssets.json", JSON.stringify(g._mastroAssets, null, 2) + "\n");
35
+ }
36
+ },
37
+ };
@@ -0,0 +1,43 @@
1
+ import type { Middleware } from "../types/middleware.d.ts";
2
+
3
+ /** Basic logging middleware. Place this first in the middleware stack. */
4
+ export const logger: Middleware = {
5
+ name: "logger",
6
+ handler: async (req, ctx) => {
7
+ const { method, url } = req;
8
+ const res = await ctx.fetchNext(req);
9
+ const { status } = res;
10
+ if (status < 400) {
11
+ if (ctx.mode === "server" && ctx.environment === "development") {
12
+ log("info", { method, url, status, e: "routeName" in res ? res.routeName : "" });
13
+ }
14
+ } else {
15
+ const isDev = ctx.mode === "generator" || ctx.environment === "development";
16
+ const e = "error" in res ? (res.error as any) : "";
17
+
18
+ if (e?.name === "NotFound" || e?.code === "ENOENT") {
19
+ // this is mainly for the functions in core/fs.ts: move this to the catch in middleware.ts ?
20
+ log("warn", { method, url, status: 404, e });
21
+ return new Response(`404 Not Found\n\n${isDev ? e.message : ""}`, { status: 404 });
22
+ }
23
+
24
+ if (isDev) {
25
+ const urlObj = new URL(url);
26
+ if (urlObj.pathname === "/favicon.ico" && status == 404) return res;
27
+ log(status >= 500 ? "error" : "warn", { method, url: urlObj, status, e });
28
+ if ("error" in res) return new Response(`${await res.text()}\n\n${e?.stack || e}`, res);
29
+ } else if (status >= 500) {
30
+ const message = String(e) || `HTTP ${status}`;
31
+ console.error(JSON.stringify({ method, url, status, message, stack: e?.stack }));
32
+ }
33
+ }
34
+ return res;
35
+ },
36
+ };
37
+
38
+ type logPayload = { method: string; url: URL | string; status: number; e: unknown };
39
+ const log = (level: "error" | "warn" | "info", p: logPayload) => {
40
+ const { pathname, search } = typeof p.url === "string" ? new URL(p.url) : p.url;
41
+ const [ansiStart, ansiReset] = level === "info" ? ["", ""] : ["\x1b[35m", "\x1b[0m"];
42
+ console[level](`${ansiStart}${p.method} ${pathname + search} => ${p.status}${ansiReset}`, p.e);
43
+ };