@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,13 @@
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
+ export * from "./core/fs.ts";
8
+ export * from "./core/html.ts";
9
+ export * from "./core/responses.ts";
10
+ export * from "./mastro.ts";
11
+ export type { Handler, Route, RouteParams } from "./types/mastro.d.ts";
12
+ export type { Context, Middleware, MiddlewareContext } from "./types/middleware.d.ts";
13
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,cAAc,cAAc,CAAC;AAC7B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,qBAAqB,CAAC;AACpC,cAAc,aAAa,CAAC;AAE5B,YAAY,EAAE,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AACvE,YAAY,EAAE,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
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
+ export * from "./core/fs.js";
8
+ export * from "./core/html.js";
9
+ export * from "./core/responses.js";
10
+ export * from "./mastro.js";
@@ -0,0 +1,58 @@
1
+ import type { Pathname, Route, RouteHandler, Simplify } from "./types/mastro.d.ts";
2
+ import type { CompatibleLocals, Context, Middleware } from "./types/middleware.d.ts";
3
+ /** Array of HTTP methods */
4
+ declare const httpMethods: readonly ["GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "PATCH", "QUERY"];
5
+ export { httpMethods };
6
+ /** HTTP methods */
7
+ export type HttpMethod = (typeof httpMethods)[number];
8
+ /**
9
+ * Class to construct an app instance.
10
+
11
+ * ```ts
12
+ * const app = new Mastro()
13
+ * .use(myMiddleware)
14
+ * .get("/", (req, ctx) => new Response("Hi"))
15
+ * ```
16
+ *
17
+ * For Node.js and Bun, use the `createApp` or `createFileRouterApp`
18
+ * factories that you can import from "@mastrojs/mastro/server".
19
+ *
20
+ * For the types to get passed through correctly, be sure to chain the method calls as shown above.
21
+ * Otherwise, the generics for URL path parameters, and locals set by middleware, won't be inferred
22
+ * correctly. When using TypeScript, do NOT do something like the following:
23
+ *
24
+ * ```js
25
+ * const badApp = new Mastro();
26
+ * badApp.use(authMiddleware);
27
+ * badApp.get("/", handler);
28
+ * ```
29
+ */
30
+ export declare class Mastro<E extends unknown[] = unknown[], L = {}> {
31
+ private middlewares;
32
+ private routes;
33
+ private routesPromise?;
34
+ constructor(opts?: {
35
+ routes?: Route<Context<E>>[] | Promise<Route<Context<E>>[]>;
36
+ });
37
+ /** Get a read-only snapshot of registered middleware in execution order. */
38
+ getMiddlewares(): Middleware<{}, Context<E>>[];
39
+ /** Get all routes. */
40
+ getRoutes(): Promise<Route<Context<E>>[]>;
41
+ /** Add a {@link Middleware} to the stack. Chain calls to pass locals to subsequent middleware. */
42
+ use<SetL = {}>(middleware: Middleware<SetL, Context<E, L>> & CompatibleLocals<L, SetL>): Mastro<E, Simplify<L & Omit<SetL, keyof L>>>;
43
+ /** Add route */
44
+ addRoute<P extends Pathname>(method: "all" | HttpMethod, pathname: P, opts: RouteHandler<E, L, P>): this;
45
+ /** Add HTTP GET route */
46
+ get<P extends Pathname>(pathname: P, handler: RouteHandler<E, L, P>): this;
47
+ /** Add HTTP POST route */
48
+ post<P extends Pathname>(pathname: P, handler: RouteHandler<E, L, P>): this;
49
+ /** Add HTTP PUT route */
50
+ put<P extends Pathname>(pathname: P, handler: RouteHandler<E, L, P>): this;
51
+ /** Add HTTP DELETE route */
52
+ delete<P extends Pathname>(pathname: P, handler: RouteHandler<E, L, P>): this;
53
+ /** Create fetch handler */
54
+ createHandler(ctx?: {
55
+ environment?: "development" | "production";
56
+ }): (req: Request, ...extras: E) => Promise<Response>;
57
+ }
58
+ //# sourceMappingURL=mastro.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mastro.d.ts","sourceRoot":"","sources":["../src/mastro.ts"],"names":[],"mappings":"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"}
package/dist/mastro.js ADDED
@@ -0,0 +1,93 @@
1
+ import { isDevServer, routeHandler } from "./core/routeHelpers.js";
2
+ import { chainMiddlewares } from "./middleware.js";
3
+ /** Array of HTTP methods */
4
+ const httpMethods = ["GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "PATCH", "QUERY"];
5
+ export { httpMethods };
6
+ /**
7
+ * Class to construct an app instance.
8
+
9
+ * ```ts
10
+ * const app = new Mastro()
11
+ * .use(myMiddleware)
12
+ * .get("/", (req, ctx) => new Response("Hi"))
13
+ * ```
14
+ *
15
+ * For Node.js and Bun, use the `createApp` or `createFileRouterApp`
16
+ * factories that you can import from "@mastrojs/mastro/server".
17
+ *
18
+ * For the types to get passed through correctly, be sure to chain the method calls as shown above.
19
+ * Otherwise, the generics for URL path parameters, and locals set by middleware, won't be inferred
20
+ * correctly. When using TypeScript, do NOT do something like the following:
21
+ *
22
+ * ```js
23
+ * const badApp = new Mastro();
24
+ * badApp.use(authMiddleware);
25
+ * badApp.get("/", handler);
26
+ * ```
27
+ */
28
+ export class Mastro {
29
+ middlewares = [];
30
+ routes = [];
31
+ routesPromise;
32
+ constructor(opts) {
33
+ this.routesPromise = opts?.routes;
34
+ }
35
+ /** Get a read-only snapshot of registered middleware in execution order. */
36
+ getMiddlewares() {
37
+ return [...this.middlewares];
38
+ }
39
+ /** Get all routes. */
40
+ async getRoutes() {
41
+ return ((await this.routesPromise) || []).concat(this.routes);
42
+ }
43
+ /** Add a {@link Middleware} to the stack. Chain calls to pass locals to subsequent middleware. */
44
+ use(middleware) {
45
+ this.middlewares.push(middleware);
46
+ return this;
47
+ }
48
+ /** Add route */
49
+ addRoute(method, pathname, opts) {
50
+ if (typeof opts === "function")
51
+ opts = { handler: opts };
52
+ this.routes.push({
53
+ getStaticPaths: opts.getStaticPaths,
54
+ handler: opts.handler,
55
+ method,
56
+ name: pathname,
57
+ pattern: new URLPattern({ pathname }),
58
+ pregenerate: opts.pregenerate,
59
+ });
60
+ return this;
61
+ }
62
+ /** Add HTTP GET route */
63
+ get(pathname, handler) {
64
+ return this.addRoute("GET", pathname, handler);
65
+ }
66
+ /** Add HTTP POST route */
67
+ post(pathname, handler) {
68
+ return this.addRoute("POST", pathname, handler);
69
+ }
70
+ /** Add HTTP PUT route */
71
+ put(pathname, handler) {
72
+ return this.addRoute("PUT", pathname, handler);
73
+ }
74
+ /** Add HTTP DELETE route */
75
+ delete(pathname, handler) {
76
+ return this.addRoute("DELETE", pathname, handler);
77
+ }
78
+ /** Create fetch handler */
79
+ createHandler(ctx) {
80
+ const handler = chainMiddlewares(this.middlewares, routeHandler(this.getRoutes()));
81
+ return async (req, ...extras) => {
82
+ const url = new URL(req.url);
83
+ const environment = isDevServer(url) ? "development" : "production";
84
+ const mode = "server";
85
+ const c = { environment, ...ctx, extras, locals: {}, params: {}, mode };
86
+ const res = await handler(req, c);
87
+ // if the logger middleware is not present, we let the platform (e.g. wrangler) show errors:
88
+ if (c.environment === "development" && res.status >= 500 && "error" in res)
89
+ throw res.error;
90
+ return res;
91
+ };
92
+ }
93
+ }
@@ -0,0 +1,4 @@
1
+ import type { Handler } from "./types/mastro.d.ts";
2
+ import type { Context, Middleware } from "./types/middleware.d.ts";
3
+ export declare const chainMiddlewares: <E = unknown[]>(middlewares: Middleware<{}, Context<E>>[], terminal: Handler<Context<E>>, index?: number) => Handler<Context<E>>;
4
+ //# sourceMappingURL=middleware.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../src/middleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,KAAK,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAEnE,eAAO,MAAM,gBAAgB,GAAI,CAAC,GAAG,OAAO,EAAE,eAC/B,UAAU,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,YAC/B,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,qBAE5B,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAoBpB,CAAC"}
@@ -0,0 +1,21 @@
1
+ export const chainMiddlewares = (middlewares, terminal, index = 0) => {
2
+ const middleware = middlewares[index];
3
+ const handler = typeof middleware === "function" ? middleware : middleware?.handler;
4
+ const next = handler ? chainMiddlewares(middlewares, terminal, index + 1) : terminal;
5
+ return async (req, ctx) => {
6
+ try {
7
+ const res = handler
8
+ ? await handler(req, {
9
+ ...ctx,
10
+ fetchNext: (r, locals) => next(r, { ...ctx, locals: { ...ctx.locals, ...locals } }),
11
+ })
12
+ : await next(req, ctx);
13
+ if (res instanceof Response)
14
+ return res;
15
+ throw new Error(`Function '${(handler || terminal).name || "<anonymous>"}' did not return a Response object`);
16
+ }
17
+ catch (error) {
18
+ return Object.assign(new Response("500 Internal Server Error", { status: 500 }), { error });
19
+ }
20
+ };
21
+ };
@@ -0,0 +1,3 @@
1
+ import type { Middleware } from "../types/middleware.d.ts";
2
+ export declare const fingerprintAssets: Middleware;
3
+ //# sourceMappingURL=fingerprintAssets.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fingerprintAssets.d.ts","sourceRoot":"","sources":["../../src/middlewares/fingerprintAssets.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AAK3D,eAAO,MAAM,iBAAiB,EAAE,UA0B/B,CAAC"}
@@ -0,0 +1,35 @@
1
+ import { createHash } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import { posix } from "node:path";
4
+ import { readTextFile } from "../core/fs.js";
5
+ const g = globalThis;
6
+ g._mastroAssets = await readTextFile("generatedAssets.json").then(JSON.parse).catch(() => ({}));
7
+ export const fingerprintAssets = {
8
+ name: "fingerprintAssets",
9
+ handler: async (req, ctx) => {
10
+ const res = await ctx.fetchNext(req);
11
+ if (!res.ok)
12
+ return res;
13
+ const { pathname } = new URL(req.url);
14
+ if (ctx.mode === "generator" && pathname.startsWith("/_assets/")) {
15
+ const ext = posix.extname(pathname);
16
+ const data = await res.arrayBuffer().then(Buffer.from);
17
+ const digest = createHash("sha256").update(data).digest("hex").slice(0, 8);
18
+ const hashedPath = `${pathname.slice(0, pathname.length - ext.length)}-${digest}${ext}`;
19
+ g._mastroAssets[pathname.slice("/_assets/".length)] = hashedPath;
20
+ res.headers.set("Content-Disposition", `attachment; filename=${posix.basename(hashedPath)}`);
21
+ return new Response(data, res);
22
+ }
23
+ else {
24
+ return res;
25
+ }
26
+ },
27
+ beforeGenerate: async () => {
28
+ g._mastroAssets = {};
29
+ },
30
+ afterGenerate: async (ctx) => {
31
+ if (ctx.onlyPregenerate && Object.keys(g._mastroAssets).length > 0) {
32
+ await fs.writeFile("generatedAssets.json", JSON.stringify(g._mastroAssets, null, 2) + "\n");
33
+ }
34
+ },
35
+ };
@@ -0,0 +1,4 @@
1
+ import type { Middleware } from "../types/middleware.d.ts";
2
+ /** Basic logging middleware. Place this first in the middleware stack. */
3
+ export declare const logger: Middleware;
4
+ //# sourceMappingURL=logger.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../../src/middlewares/logger.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AAE3D,0EAA0E;AAC1E,eAAO,MAAM,MAAM,EAAE,UAgCpB,CAAC"}
@@ -0,0 +1,41 @@
1
+ /** Basic logging middleware. Place this first in the middleware stack. */
2
+ export const logger = {
3
+ name: "logger",
4
+ handler: async (req, ctx) => {
5
+ const { method, url } = req;
6
+ const res = await ctx.fetchNext(req);
7
+ const { status } = res;
8
+ if (status < 400) {
9
+ if (ctx.mode === "server" && ctx.environment === "development") {
10
+ log("info", { method, url, status, e: "routeName" in res ? res.routeName : "" });
11
+ }
12
+ }
13
+ else {
14
+ const isDev = ctx.mode === "generator" || ctx.environment === "development";
15
+ const e = "error" in res ? res.error : "";
16
+ if (e?.name === "NotFound" || e?.code === "ENOENT") {
17
+ // this is mainly for the functions in core/fs.ts: move this to the catch in middleware.ts ?
18
+ log("warn", { method, url, status: 404, e });
19
+ return new Response(`404 Not Found\n\n${isDev ? e.message : ""}`, { status: 404 });
20
+ }
21
+ if (isDev) {
22
+ const urlObj = new URL(url);
23
+ if (urlObj.pathname === "/favicon.ico" && status == 404)
24
+ return res;
25
+ log(status >= 500 ? "error" : "warn", { method, url: urlObj, status, e });
26
+ if ("error" in res)
27
+ return new Response(`${await res.text()}\n\n${e?.stack || e}`, res);
28
+ }
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
+ const log = (level, p) => {
38
+ const { pathname, search } = typeof p.url === "string" ? new URL(p.url) : p.url;
39
+ const [ansiStart, ansiReset] = level === "info" ? ["", ""] : ["\x1b[35m", "\x1b[0m"];
40
+ console[level](`${ansiStart}${p.method} ${pathname + search} => ${p.status}${ansiReset}`, p.e);
41
+ };
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Returns the `Content-Type` header value for a given file extension. For example:
3
+ * `extensionToContentType("html") === "text/html; charset=UTF-8"`;
4
+ */
5
+ export declare const contentTypeFromExt: (ext: string) => string | undefined;
6
+ //# sourceMappingURL=mediaTypes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mediaTypes.d.ts","sourceRoot":"","sources":["../../../src/middlewares/staticFiles/mediaTypes.ts"],"names":[],"mappings":"AAsBA;;;GAGG;AACH,eAAO,MAAM,kBAAkB,QAAS,MAAM,KAAG,MAAM,GAAG,SACV,CAAC"}
@@ -0,0 +1,26 @@
1
+ /*
2
+ Source of mediaTypes.json is https://github.com/denoland/std/blob/9145d20d86f897d21afc3cfda0f0219e79fd02c1/media_types/vendor/db.ts
3
+ Copyright 2018-2026 the Deno authors. MIT license.
4
+
5
+ It was transformed into its current shape with:
6
+
7
+ JSON.stringify(Object.keys(db).reduce((acc, type) => {
8
+ const { extensions, charset, source } = db[type];
9
+ if (extensions && (source === "iana" || !source)) {
10
+ const cs = charset || (type.startsWith("text/") ? "UTF-8" : null);
11
+ for (const ext of extensions) {
12
+ const current = acc[ext];
13
+ if (!current || current === "application/octet-stream" || current === "application/mp4") {
14
+ acc[ext] = type + (cs ? `; charset=${cs}` : "");
15
+ }
16
+ }
17
+ }
18
+ return acc;
19
+ }, {}))
20
+ */
21
+ import types from "./mediaTypes.json" with { type: "json" };
22
+ /**
23
+ * Returns the `Content-Type` header value for a given file extension. For example:
24
+ * `extensionToContentType("html") === "text/html; charset=UTF-8"`;
25
+ */
26
+ export const contentTypeFromExt = (ext) => types[ext.toLowerCase()];