@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.
- package/LICENSE +21 -0
- package/README.md +60 -2
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +92 -0
- package/dist/core/fs.d.ts +67 -0
- package/dist/core/fs.d.ts.map +1 -0
- package/dist/core/fs.js +114 -0
- package/dist/core/fsHelpers.d.ts +18 -0
- package/dist/core/fsHelpers.d.ts.map +1 -0
- package/dist/core/fsHelpers.js +17 -0
- package/dist/core/html.d.ts +67 -0
- package/dist/core/html.d.ts.map +1 -0
- package/dist/core/html.js +201 -0
- package/dist/core/responses.d.ts +98 -0
- package/dist/core/responses.d.ts.map +1 -0
- package/dist/core/responses.js +145 -0
- package/dist/core/routeHelpers.d.ts +12 -0
- package/dist/core/routeHelpers.d.ts.map +1 -0
- package/dist/core/routeHelpers.js +51 -0
- package/dist/generator.d.ts +16 -0
- package/dist/generator.d.ts.map +1 -0
- package/dist/generator.js +124 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +10 -0
- package/dist/mastro.d.ts +58 -0
- package/dist/mastro.d.ts.map +1 -0
- package/dist/mastro.js +93 -0
- package/dist/middleware.d.ts +4 -0
- package/dist/middleware.d.ts.map +1 -0
- package/dist/middleware.js +21 -0
- package/dist/middlewares/fingerprintAssets.d.ts +3 -0
- package/dist/middlewares/fingerprintAssets.d.ts.map +1 -0
- package/dist/middlewares/fingerprintAssets.js +35 -0
- package/dist/middlewares/logger.d.ts +4 -0
- package/dist/middlewares/logger.d.ts.map +1 -0
- package/dist/middlewares/logger.js +41 -0
- package/dist/middlewares/staticFiles/mediaTypes.d.ts +6 -0
- package/dist/middlewares/staticFiles/mediaTypes.d.ts.map +1 -0
- package/dist/middlewares/staticFiles/mediaTypes.js +26 -0
- package/dist/middlewares/staticFiles/mediaTypes.json +910 -0
- package/dist/middlewares/staticFiles/staticFiles.d.ts +10 -0
- package/dist/middlewares/staticFiles/staticFiles.d.ts.map +1 -0
- package/dist/middlewares/staticFiles/staticFiles.js +119 -0
- package/dist/middlewares/tsToJs.d.ts +13 -0
- package/dist/middlewares/tsToJs.d.ts.map +1 -0
- package/dist/middlewares/tsToJs.js +49 -0
- package/dist/servers/fileRouter.d.ts +11 -0
- package/dist/servers/fileRouter.d.ts.map +1 -0
- package/dist/servers/fileRouter.js +74 -0
- package/dist/servers/fileRoutes.d.ts +2 -0
- package/dist/servers/fileRoutes.d.ts.map +1 -0
- package/dist/servers/fileRoutes.js +1 -0
- package/dist/servers/server.d.ts +22 -0
- package/dist/servers/server.d.ts.map +1 -0
- package/dist/servers/server.js +21 -0
- package/dist/types/mastro.d.ts +80 -0
- package/dist/types/middleware.d.ts +157 -0
- package/dist/types/standard-schema.d.ts +76 -0
- package/package.json +52 -3
- package/src/README.md +29 -0
- package/src/cli.ts +89 -0
- package/src/core/fs.ts +131 -0
- package/src/core/fsHelpers.ts +24 -0
- package/src/core/html.ts +226 -0
- package/src/core/responses.ts +175 -0
- package/src/core/routeHelpers.ts +60 -0
- package/src/generator.ts +139 -0
- package/src/index.ts +14 -0
- package/src/mastro.ts +116 -0
- package/src/middleware.ts +28 -0
- package/src/middlewares/fingerprintAssets.ts +37 -0
- package/src/middlewares/logger.ts +43 -0
- package/src/middlewares/staticFiles/mediaTypes.json +910 -0
- package/src/middlewares/staticFiles/mediaTypes.ts +28 -0
- package/src/middlewares/staticFiles/staticFiles.ts +136 -0
- package/src/middlewares/tsToJs.ts +43 -0
- package/src/servers/fileRouter.ts +83 -0
- package/src/servers/fileRoutes.ts +1 -0
- package/src/servers/server.ts +29 -0
- package/src/types/mastro.d.ts +80 -0
- package/src/types/middleware.d.ts +157 -0
- package/src/types/standard-schema.d.ts +76 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Mastro
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,61 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Mastro
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**[Website](https://mastrojs.github.io/)** | [Try Mastro online](https://vscode.dev/github/mastrojs/template-basic)
|
|
4
|
+
|
|
5
|
+
**No dependencies. No build step. Just a simple web framework.**
|
|
6
|
+
|
|
7
|
+
Mastro is a web framework and site generator for people who care about their users and web standards. It’s is implemented in just ~800 lines of TypeScript.
|
|
8
|
+
|
|
9
|
+
Use JavaScript/TypeScript’s mature tooling to build fast MPA websites. Instead of going through layers of abstraction, work directly with the browser and your JavaScript runtime – Node.js, Deno, Bun, or Workers.
|
|
10
|
+
|
|
11
|
+
## Minimal yet powerful
|
|
12
|
+
|
|
13
|
+
- **Static site generation** – ideal for blogs, marketing sites or webshops that are [fast](https://mastrojs.github.io/#fast-for-everyone).
|
|
14
|
+
- **Server-side rendering** – use Mastro as a [full-stack web framework](https://mastrojs.github.io/guide/forms-and-rest-apis/#a-mock-database).
|
|
15
|
+
- **Everything is a route**: serve [JSON REST APIs](https://mastrojs.github.io/guide/forms-and-rest-apis/#client-side-fetching-a-rest-api), [CSS](https://mastrojs.github.io/blog/2026-05-26-component-scoped-css-without-build-step/), or [images](https://mastrojs.github.io/guide/bundling-assets/#transforming-images), with the [same API](https://mastrojs.github.io/blog/2026-01-29-everything-is-a-route-one-interface-for-servers-static-sites-and-assets/) as HTML.
|
|
16
|
+
- **Composable**: a [router](https://mastrojs.github.io/docs/routing/) and plain [helper functions](https://mastrojs.github.io/docs/html-components/) – it's that simple.
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
## No bloat
|
|
20
|
+
|
|
21
|
+
- **No overhead**: implemented in just [~800 lines](https://github.com/mastrojs/mastro/tree/main/libs/mastro/src#readme) of TypeScript with no dependencies.
|
|
22
|
+
- **No client-side JavaScript** (until you [add some](https://mastrojs.github.io/guide/interactivity-with-javascript-in-the-browser/)): create [MPA](https://mastrojs.github.io/guide/client-side-vs-server-side-javascript-static-vs-ondemand-spa-vs-mpa/) websites that load [fast](https://mastrojs.github.io#fast-for-everyone).
|
|
23
|
+
- **No bundler** (until you [add one](https://mastrojs.github.io/guide/bundling-assets/)): your code ships exactly how you wrote it.
|
|
24
|
+
- **No magic**: use plain `<img>` and `<a>` tags referencing [asset routes](https://mastrojs.github.io/blog/2026-01-29-everything-is-a-route-one-interface-for-servers-static-sites-and-assets/).
|
|
25
|
+
- **No VC-money**: no eventual enshitification – selling is none of our business.
|
|
26
|
+
- **No update treadmill**: we use web standards instead [dependencies](https://jsr.io/@mastrojs/mastro/dependencies).
|
|
27
|
+
- **No lock-in**: swap out Mastro later or fork it – it's only [~800 lines](https://github.com/mastrojs/mastro/tree/main/libs/mastro/src#readme) after all.
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
## Documentation
|
|
31
|
+
|
|
32
|
+
- [Get started](https://mastrojs.github.io/docs/getting-started/)
|
|
33
|
+
- [Mastro Docs](https://mastrojs.github.io/docs/)
|
|
34
|
+
- [Mastro Guide to web dev](https://mastrojs.github.io/guide/)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
## Extensions
|
|
38
|
+
|
|
39
|
+
The core of Mastro is tiny. But to get you started quickly for common use-cases, there is a growing list of extensions that are tailored to be used with Mastro. Often, it's just a single file wrapping a carefully chosen external dependency.
|
|
40
|
+
|
|
41
|
+
- Tiny libs in the `@mastrojs` namespace:
|
|
42
|
+
- [Reactive Mastro](https://mastrojs.github.io/reactive/) – a tiny client-side reactive GUI library for MPAs
|
|
43
|
+
- [markdown](https://github.com/mastrojs/markdown) to HTML
|
|
44
|
+
- [images](https://github.com/mastrojs/images) – resize/compress/etc.
|
|
45
|
+
- [og-image](https://github.com/mastrojs/og-image) – generate images from text
|
|
46
|
+
- [feed](https://github.com/mastrojs/feed) – generate RSS/Atom feeds
|
|
47
|
+
- [atproto](https://github.com/mastrojs/atproto) – add support for [Standard.site](https://mastrojs.github.io/blog/2026-06-05-how-to-add-standard-site-support-to-your-website/)
|
|
48
|
+
- [api](https://github.com/mastrojs/api) – type-safe REST APIs and clients
|
|
49
|
+
- [result](https://github.com/mastrojs/result) – a minimal `Result` type
|
|
50
|
+
- [Install](https://mastrojs.github.io/guide/third-party-packages/) 3rd-party packages like:
|
|
51
|
+
- [Kysely](https://www.kysely.dev/) – type-safe SQL query builder
|
|
52
|
+
- [Sveltia CMS](https://github.com/mastrojs/template-sveltia-cms) – git-based CMS
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
## Join the community
|
|
56
|
+
|
|
57
|
+
We’re building an inclusive community, where people of all kinds of backgrounds and experience levels feel welcome and safe, and help each other. A place to ask questions and learn new things.
|
|
58
|
+
|
|
59
|
+
Please start a [GitHub Discussion](https://github.com/mastrojs/mastro/discussions/) or join us on [our Discord](https://discord.gg/gmw2VEW5Rw) or [our Stoat](https://stt.gg/k7QMEaP1).
|
|
60
|
+
|
|
61
|
+
Something not working as expected or confusing? We consider that a bug. Please open a [GitHub issue](https://github.com/mastrojs/mastro/issues/).
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":""}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
3
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
4
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
5
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
6
|
+
});
|
|
7
|
+
}
|
|
8
|
+
return path;
|
|
9
|
+
};
|
|
10
|
+
import { statSync } from "node:fs";
|
|
11
|
+
import fs from "node:fs/promises";
|
|
12
|
+
import { resolve } from "node:path";
|
|
13
|
+
import { pathToFileURL } from "node:url";
|
|
14
|
+
import { parseArgs } from "node:util";
|
|
15
|
+
import { generate } from "./generator.js";
|
|
16
|
+
import { findRoutes } from "./servers/fileRouter.js";
|
|
17
|
+
class GenerateError extends Error {
|
|
18
|
+
}
|
|
19
|
+
const main = async () => {
|
|
20
|
+
const options = {
|
|
21
|
+
"base-url": {
|
|
22
|
+
description: "Base URL for the synthetic requests, defaults to http://127.0.0.1",
|
|
23
|
+
type: "string",
|
|
24
|
+
},
|
|
25
|
+
output: {
|
|
26
|
+
description: "Name of output folder that will be created, defaults to `generated`",
|
|
27
|
+
type: "string",
|
|
28
|
+
},
|
|
29
|
+
"only-pregenerate": {
|
|
30
|
+
description: "Only pregenerate routes with `pregenerate` set",
|
|
31
|
+
type: "boolean",
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
const { values, positionals } = parseArgs({ options, allowPositionals: true });
|
|
35
|
+
switch (positionals[0]) {
|
|
36
|
+
case "generate":
|
|
37
|
+
return mastroGenerate(values);
|
|
38
|
+
case "write-file-routes":
|
|
39
|
+
return writeFileRoutes();
|
|
40
|
+
default: {
|
|
41
|
+
const unknownCmd = positionals[0] !== "help";
|
|
42
|
+
if (unknownCmd)
|
|
43
|
+
console.info(`'${positionals[0]}' is not a valid mastro command.`);
|
|
44
|
+
const keys = Object.keys(options);
|
|
45
|
+
const maxKeyLen = Math.max(...keys.map((k) => k.length));
|
|
46
|
+
const opts = keys.map((key) => ` --${key.padEnd(maxKeyLen)} ${options[key]?.description}`);
|
|
47
|
+
console.info(`The 'mastro' CLI has the following commands:\n
|
|
48
|
+
generate a static site\n mastro generate [options]\n${opts.join("\n")}\n
|
|
49
|
+
print this help page\n mastro help\n
|
|
50
|
+
write a \`.routes.ts\` file (e.g. for Cloudflare or Service Workers)\n mastro write-routes\n`);
|
|
51
|
+
if (unknownCmd)
|
|
52
|
+
process.exit(1);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
const mastroGenerate = async (values) => {
|
|
57
|
+
const serverPath = exists("server.ts") || exists("server.js");
|
|
58
|
+
const example = "`export const app = new Mastro()` or similar.";
|
|
59
|
+
if (!serverPath) {
|
|
60
|
+
throw new GenerateError(`No \`server.ts\` or \`server.js\` found in the project directory root.
|
|
61
|
+
Create one containing ${example}`);
|
|
62
|
+
}
|
|
63
|
+
// if we had https://github.com/nodejs/node/issues/63096, we could start server without server.ts:
|
|
64
|
+
// const app = server ? await import(server).then((m) => m.app as Mastro) : createFileRouterApp();
|
|
65
|
+
const { app } = await import(__rewriteRelativeImportExtension(serverPath));
|
|
66
|
+
if (!app)
|
|
67
|
+
throw new GenerateError(serverPath + "\nis missing " + example);
|
|
68
|
+
const success = await generate(app, {
|
|
69
|
+
baseUrl: values["base-url"],
|
|
70
|
+
outFolder: values.output,
|
|
71
|
+
onlyPregenerate: !!values["only-pregenerate"],
|
|
72
|
+
});
|
|
73
|
+
if (!success)
|
|
74
|
+
process.exit(1);
|
|
75
|
+
};
|
|
76
|
+
const exists = (entry) => {
|
|
77
|
+
const path = pathToFileURL(resolve(entry));
|
|
78
|
+
return statSync(path, { throwIfNoEntry: false })?.isFile() ? path.href : undefined;
|
|
79
|
+
};
|
|
80
|
+
const writeFileRoutes = async () => {
|
|
81
|
+
const contents = `// this file was generated by mastro write-file-routes. Do not edit manually!
|
|
82
|
+
import { loadRoutes } from "@mastrojs/mastro/file-routes";
|
|
83
|
+
|
|
84
|
+
export const routes = loadRoutes(${JSON.stringify(await findRoutes(), null, 2)},
|
|
85
|
+
(name: string) => import(\`./routes/\${name.slice(7, -10)}.server.\${name.slice(-2)}\`),
|
|
86
|
+
);\n`;
|
|
87
|
+
return fs.writeFile(".routes.ts", contents);
|
|
88
|
+
};
|
|
89
|
+
await main().catch((e) => {
|
|
90
|
+
console.error(`\n${e instanceof GenerateError ? e.message : e}`);
|
|
91
|
+
process.exit(1);
|
|
92
|
+
});
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lightweight wrapper around Node.js's file system functions. But for better interoperability
|
|
3
|
+
* with incoming URL paths, input and output paths of these functions use URL encoding.
|
|
4
|
+
*
|
|
5
|
+
* - Implementation uses RPC for the [vscode-extension](../../../../vscode-extension/README.md).
|
|
6
|
+
* - Cloudflare Workers work with Node.js compatibility.
|
|
7
|
+
* - For Service Workers (where there is no filesystem), we fall back to undefined
|
|
8
|
+
* and skip Node.js imports so the module can still load.
|
|
9
|
+
*/
|
|
10
|
+
import type { StandardSchemaV1 } from "../types/standard-schema.d.ts";
|
|
11
|
+
/**
|
|
12
|
+
* Read the directory on the local file system and return its files,
|
|
13
|
+
* non-recursive and ignoring symlinks and dotfiles.
|
|
14
|
+
*
|
|
15
|
+
* Input is a URL path relative to project root. Returned filenames are URL-encoded.
|
|
16
|
+
*/
|
|
17
|
+
export declare const readDir: (path: string) => Promise<string[]>;
|
|
18
|
+
/**
|
|
19
|
+
* Return the contents of a text file on the local file system as a string.
|
|
20
|
+
*
|
|
21
|
+
* Input is a URL path relative to project root.
|
|
22
|
+
*/
|
|
23
|
+
export declare const readTextFile: (path: string) => Promise<string>;
|
|
24
|
+
/**
|
|
25
|
+
* Return the contents of a binary file on the local file system.
|
|
26
|
+
*
|
|
27
|
+
* Input is a URL path relative to project root.
|
|
28
|
+
*/
|
|
29
|
+
export declare const readFile: (path: string) => Promise<Uint8Array<ArrayBufferLike>>;
|
|
30
|
+
/**
|
|
31
|
+
* Return the file paths on the local file system, relative to the current working directory,
|
|
32
|
+
* expanding glob patterns like `*` and `**`. Do not pass it untrusted input.
|
|
33
|
+
*
|
|
34
|
+
* Returned paths are sorted alphabetically, are URL-encoded, use forward slashes,
|
|
35
|
+
* and don't start with a slash. Input glob patterns use filesystem names, not URL encoding.
|
|
36
|
+
*
|
|
37
|
+
* Except for when using the Mastro VSCode extension, this is a thin wrapper around
|
|
38
|
+
* [fs.glob](https://nodejs.org/api/fs.html#fspromisesglobpattern-options).
|
|
39
|
+
*
|
|
40
|
+
* In [VSCode for the Web](https://code.visualstudio.com/api/references/vscode-api#GlobPattern)
|
|
41
|
+
* there is a [bug](https://github.com/microsoft/vscode/issues/249197) and we had to roll our own.
|
|
42
|
+
*/
|
|
43
|
+
export declare const findFiles: (pattern: string | string[]) => Promise<string[]>;
|
|
44
|
+
/**
|
|
45
|
+
* Read all files from the local filesystem that match the supplied glob pattern (via `findFiles`)
|
|
46
|
+
* and parse them as JSON. Returns an array with `data`, `path` as a URL path, and `slug` as the
|
|
47
|
+
* URL-encoded filename up to its first dot (e.g. `post.en.json` becomes `post`).
|
|
48
|
+
*
|
|
49
|
+
* The default TypeScript type for the data is `unknown`. You can override that with e.g.
|
|
50
|
+
* `readJsonFiles<{ title: string }>("data/*.json")`. But to actually verify the metadata is
|
|
51
|
+
* correct, you should use a schema. For example using
|
|
52
|
+
* [validate.js](https://github.com/jakelazaroff/validate.js):
|
|
53
|
+
*
|
|
54
|
+
* ```ts
|
|
55
|
+
* import { object, string } from "./validate.js";
|
|
56
|
+
* const schema = object({ title: string });
|
|
57
|
+
* const arr = await readJsonFiles(pattern, { schema });
|
|
58
|
+
* ```
|
|
59
|
+
*/
|
|
60
|
+
export declare const readJsonFiles: <T>(pattern: string, opts?: {
|
|
61
|
+
schema?: StandardSchemaV1<unknown, T>;
|
|
62
|
+
}) => Promise<Array<{
|
|
63
|
+
data: T;
|
|
64
|
+
path: string;
|
|
65
|
+
slug: string;
|
|
66
|
+
}>>;
|
|
67
|
+
//# sourceMappingURL=fs.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fs.d.ts","sourceRoot":"","sources":["../../src/core/fs.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AActE;;;;;GAKG;AACH,eAAO,MAAM,OAAO,SAAgB,MAAM,KAAG,OAAO,CAAC,MAAM,EAAE,CAM5D,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,YAAY,SAAgB,MAAM,KAAG,OAAO,CAAC,MAAM,CAGH,CAAC;AAE9D;;;;GAIG;AACH,eAAO,MAAM,QAAQ,SAAgB,MAAM,KAAG,OAAO,CAAC,UAAU,CAAC,eAAe,CAAC,CAGxB,CAAC;AAE1D;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,SAAS,YAAmB,MAAM,GAAG,MAAM,EAAE,KAAG,OAAO,CAAC,MAAM,EAAE,CAW5E,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,aAAa,GAAU,CAAC,WAC1B,MAAM,SACT;IAAE,MAAM,CAAC,EAAE,gBAAgB,CAAC,OAAO,EAAE,CAAC,CAAC,CAAA;CAAE,KAC9C,OAAO,CAAC,KAAK,CAAC;IAAE,IAAI,EAAE,CAAC,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,CAetD,CAAC"}
|
package/dist/core/fs.js
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
2
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
3
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
4
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
5
|
+
});
|
|
6
|
+
}
|
|
7
|
+
return path;
|
|
8
|
+
};
|
|
9
|
+
import { normalizeSlashes, sep, urlPathToFilePath } from "./fsHelpers.js";
|
|
10
|
+
const nodeFs = "node:fs/promises"; // In a variable to prevent bundling by esbuild
|
|
11
|
+
const cf = "Cloudflare-Workers";
|
|
12
|
+
// @ts-expect-error WorkerGlobalScope
|
|
13
|
+
const worker = typeof self !== "undefined" && self.WorkerGlobalScope && navigator.userAgent !== cf;
|
|
14
|
+
const isWebOrWorker = typeof document === "object" || worker;
|
|
15
|
+
const fs = isWebOrWorker
|
|
16
|
+
? undefined
|
|
17
|
+
: import(__rewriteRelativeImportExtension(nodeFs));
|
|
18
|
+
const vscodeExtensionFs = typeof document === "object" ? document.fs : undefined;
|
|
19
|
+
/**
|
|
20
|
+
* Read the directory on the local file system and return its files,
|
|
21
|
+
* non-recursive and ignoring symlinks and dotfiles.
|
|
22
|
+
*
|
|
23
|
+
* Input is a URL path relative to project root. Returned filenames are URL-encoded.
|
|
24
|
+
*/
|
|
25
|
+
export const readDir = async (path) => {
|
|
26
|
+
if (!fs)
|
|
27
|
+
return (await vscodeExtensionFs.readDir(urlPathToFilePath(path))).map(toUrlPath);
|
|
28
|
+
const files = await (await fs).readdir(urlPathToFilePath(path), { withFileTypes: true });
|
|
29
|
+
return files
|
|
30
|
+
.filter((file) => !file.isSymbolicLink() && !file.isDirectory() && file.name[0] !== ".")
|
|
31
|
+
.map((file) => toUrlPath(file.name));
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* Return the contents of a text file on the local file system as a string.
|
|
35
|
+
*
|
|
36
|
+
* Input is a URL path relative to project root.
|
|
37
|
+
*/
|
|
38
|
+
export const readTextFile = async (path) => fs
|
|
39
|
+
? (await fs).readFile(urlPathToFilePath(path), { encoding: "utf8" })
|
|
40
|
+
: vscodeExtensionFs.readTextFile(urlPathToFilePath(path));
|
|
41
|
+
/**
|
|
42
|
+
* Return the contents of a binary file on the local file system.
|
|
43
|
+
*
|
|
44
|
+
* Input is a URL path relative to project root.
|
|
45
|
+
*/
|
|
46
|
+
export const readFile = async (path) => fs
|
|
47
|
+
? (await fs).readFile(urlPathToFilePath(path))
|
|
48
|
+
: vscodeExtensionFs.readFile(urlPathToFilePath(path));
|
|
49
|
+
/**
|
|
50
|
+
* Return the file paths on the local file system, relative to the current working directory,
|
|
51
|
+
* expanding glob patterns like `*` and `**`. Do not pass it untrusted input.
|
|
52
|
+
*
|
|
53
|
+
* Returned paths are sorted alphabetically, are URL-encoded, use forward slashes,
|
|
54
|
+
* and don't start with a slash. Input glob patterns use filesystem names, not URL encoding.
|
|
55
|
+
*
|
|
56
|
+
* Except for when using the Mastro VSCode extension, this is a thin wrapper around
|
|
57
|
+
* [fs.glob](https://nodejs.org/api/fs.html#fspromisesglobpattern-options).
|
|
58
|
+
*
|
|
59
|
+
* In [VSCode for the Web](https://code.visualstudio.com/api/references/vscode-api#GlobPattern)
|
|
60
|
+
* there is a [bug](https://github.com/microsoft/vscode/issues/249197) and we had to roll our own.
|
|
61
|
+
*/
|
|
62
|
+
export const findFiles = async (pattern) => {
|
|
63
|
+
pattern = typeof pattern === "string" ? validatePattern(pattern) : pattern.map(validatePattern);
|
|
64
|
+
if (!fs)
|
|
65
|
+
return (await vscodeExtensionFs.findFiles(pattern)).map(toUrlPath).sort();
|
|
66
|
+
const paths = [];
|
|
67
|
+
for await (const entry of (await fs).glob(pattern, { withFileTypes: true })) {
|
|
68
|
+
if (entry.isFile()) {
|
|
69
|
+
const relativeToCwd = (entry.parentPath + sep + entry.name).slice(process.cwd().length + 1);
|
|
70
|
+
paths.push(toUrlPath(relativeToCwd));
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return paths.sort();
|
|
74
|
+
};
|
|
75
|
+
/**
|
|
76
|
+
* Read all files from the local filesystem that match the supplied glob pattern (via `findFiles`)
|
|
77
|
+
* and parse them as JSON. Returns an array with `data`, `path` as a URL path, and `slug` as the
|
|
78
|
+
* URL-encoded filename up to its first dot (e.g. `post.en.json` becomes `post`).
|
|
79
|
+
*
|
|
80
|
+
* The default TypeScript type for the data is `unknown`. You can override that with e.g.
|
|
81
|
+
* `readJsonFiles<{ title: string }>("data/*.json")`. But to actually verify the metadata is
|
|
82
|
+
* correct, you should use a schema. For example using
|
|
83
|
+
* [validate.js](https://github.com/jakelazaroff/validate.js):
|
|
84
|
+
*
|
|
85
|
+
* ```ts
|
|
86
|
+
* import { object, string } from "./validate.js";
|
|
87
|
+
* const schema = object({ title: string });
|
|
88
|
+
* const arr = await readJsonFiles(pattern, { schema });
|
|
89
|
+
* ```
|
|
90
|
+
*/
|
|
91
|
+
export const readJsonFiles = async (pattern, opts = {}) => Promise.all((await findFiles(pattern)).map(async (path) => {
|
|
92
|
+
let data = JSON.parse(await readTextFile(path));
|
|
93
|
+
if (opts.schema) {
|
|
94
|
+
const res = await opts.schema["~standard"].validate(data);
|
|
95
|
+
if (res.issues) {
|
|
96
|
+
const issues = res.issues.map((i) => `${i.message} (${i.path})`);
|
|
97
|
+
throw Error(`JSON in ${path} did not validate:\n ${issues.join("\n ")}`);
|
|
98
|
+
}
|
|
99
|
+
data = res.value;
|
|
100
|
+
}
|
|
101
|
+
const slug = path.split("/").at(-1)?.split(".").at(0) || "";
|
|
102
|
+
return { data, path, slug };
|
|
103
|
+
}));
|
|
104
|
+
/**
|
|
105
|
+
* Best-effort input validation for unix paths
|
|
106
|
+
*/
|
|
107
|
+
const validatePattern = (p) => {
|
|
108
|
+
p = p.startsWith("/") ? p.slice(1) : p;
|
|
109
|
+
if (p.split("/").includes(".."))
|
|
110
|
+
throw Error("findFiles pattern must not include .. segments");
|
|
111
|
+
return p;
|
|
112
|
+
};
|
|
113
|
+
// normalize and convert a filesystem path to a URL path
|
|
114
|
+
const toUrlPath = (path) => normalizeSlashes(path).split("/").map(encodeURIComponent).join("/");
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Internal branded type of a decoded, project-relative filesystem path.
|
|
3
|
+
*/
|
|
4
|
+
export type FilePath = string & {
|
|
5
|
+
readonly __filePath: unique symbol;
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* Convert a URL path to a decoded, project-relative filesystem path with forward slashes
|
|
9
|
+
* on every platform. For example `urlPathToFilePath("/foo/bar%20baz.jpg") === "foo/bar baz.jpg"`
|
|
10
|
+
*/
|
|
11
|
+
export declare const urlPathToFilePath: (urlPath: string & {
|
|
12
|
+
readonly __filePath?: never;
|
|
13
|
+
}) => FilePath;
|
|
14
|
+
/** Replace backslashes with forward slashes on Windows */
|
|
15
|
+
export declare const normalizeSlashes: (path: string) => string;
|
|
16
|
+
/** Backslash on Windows, forward slash everywhere else */
|
|
17
|
+
export declare const sep: "/" | "\\";
|
|
18
|
+
//# sourceMappingURL=fsHelpers.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fsHelpers.d.ts","sourceRoot":"","sources":["../../src/core/fsHelpers.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG;IAAE,QAAQ,CAAC,UAAU,EAAE,OAAO,MAAM,CAAA;CAAE,CAAC;AAEvE;;;GAGG;AACH,eAAO,MAAM,iBAAiB,YAAa,MAAM,GAAG;IAAE,QAAQ,CAAC,UAAU,CAAC,EAAE,KAAK,CAAA;CAAE,KAAG,QAMrF,CAAC;AAEF,0DAA0D;AAC1D,eAAO,MAAM,gBAAgB,SAAU,MAAM,KAAG,MACE,CAAC;AAEnD,0DAA0D;AAC1D,eAAO,MAAM,GAAG,EAAE,GAAG,GAAG,IACqD,CAAC"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Convert a URL path to a decoded, project-relative filesystem path with forward slashes
|
|
3
|
+
* on every platform. For example `urlPathToFilePath("/foo/bar%20baz.jpg") === "foo/bar baz.jpg"`
|
|
4
|
+
*/
|
|
5
|
+
export const urlPathToFilePath = (urlPath) => {
|
|
6
|
+
const path = normalizeSlashes(decodeURIComponent(urlPath)).replace(/^\/+/, "");
|
|
7
|
+
if (path.split("/").includes(".."))
|
|
8
|
+
throw Error("FilePath must not include .. segments");
|
|
9
|
+
// on Windows, prevent paths starting with `C:`, `./C:`, etc:
|
|
10
|
+
if (sep === "\\" && /^(?:\.\/+)*[a-z]:/i.test(path))
|
|
11
|
+
throw Error("FilePath must be relative");
|
|
12
|
+
return (path || "."); // urlPathToFilePath("/") === "."
|
|
13
|
+
};
|
|
14
|
+
/** Replace backslashes with forward slashes on Windows */
|
|
15
|
+
export const normalizeSlashes = (path) => sep === "\\" ? path.replaceAll("\\", "/") : path;
|
|
16
|
+
/** Backslash on Windows, forward slash everywhere else */
|
|
17
|
+
export const sep = typeof process !== "undefined" && process.platform === "win32" ? "\\" : "/";
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@mastrojs/mastro/html` contains a selfcontained way to construct and properly escape
|
|
3
|
+
* HTML using JavaScript tagged template literals.
|
|
4
|
+
* All its exports are also exported by the default `@mastrojs/mastro` module,
|
|
5
|
+
* and usually you should just use those. However, it is also exported separately here
|
|
6
|
+
* for use in `@mastrojs/reactive` or other projects where you only want its functionality.
|
|
7
|
+
* @module
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* HTML primitive values like strings and numbers.
|
|
11
|
+
*
|
|
12
|
+
* Note that we use `String` objects to store already properly escaped HTML.
|
|
13
|
+
*/
|
|
14
|
+
export type HtmlPrimitive = String | string | number | undefined | null | false;
|
|
15
|
+
/**
|
|
16
|
+
* An `Html` node – i.e. what can be used with `html` tagged templates.
|
|
17
|
+
*/
|
|
18
|
+
export type Html = HtmlPrimitive | Html[] | AsyncIterable<Html> | Promise<Html>;
|
|
19
|
+
/**
|
|
20
|
+
* Tagged template literal to construct `Html` nodes.
|
|
21
|
+
* This makes sure things are properly escaped (unless `unsafeInnerHtml` is used).
|
|
22
|
+
*
|
|
23
|
+
* ```ts
|
|
24
|
+
* import { html, renderToString } from "@mastrojs/mastro";
|
|
25
|
+
*
|
|
26
|
+
* const myName = "World";
|
|
27
|
+
* const myClass = "hero";
|
|
28
|
+
*
|
|
29
|
+
* const str = await renderToString(
|
|
30
|
+
* html`<h1 class=${myClass}>Hello ${myName}</h1>`
|
|
31
|
+
* );
|
|
32
|
+
* ```
|
|
33
|
+
*/
|
|
34
|
+
export declare const html: (templateParts: TemplateStringsArray, ...params: Html[]) => Html[];
|
|
35
|
+
/**
|
|
36
|
+
* Mark a string as already properly escaped HTML. Do not use this on an untrusted/user-supplied string!
|
|
37
|
+
*
|
|
38
|
+
* This is similar to the DOM's [innerHTML](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#replacing_the_contents_of_an_element)
|
|
39
|
+
* or React's `dangerouslySetInnerHTML`.
|
|
40
|
+
*/
|
|
41
|
+
export declare const unsafeInnerHtml: (val: string) => HtmlPrimitive;
|
|
42
|
+
/**
|
|
43
|
+
* Returns true iff `val` is an async iterable
|
|
44
|
+
*/
|
|
45
|
+
export declare const isAsyncIterable: <T>(val: any) => val is AsyncIterable<T>;
|
|
46
|
+
/**
|
|
47
|
+
* Convert an `Html` node to a properly escaped `Promise<string>`.
|
|
48
|
+
*
|
|
49
|
+
* See `renderToStream` for a more efficient but less ergonomic alternative.
|
|
50
|
+
*/
|
|
51
|
+
export declare const renderToString: (node: Html) => Promise<string>;
|
|
52
|
+
/**
|
|
53
|
+
* Convert an `Html` node to a properly escaped `string` but
|
|
54
|
+
* throws if the input contains a Promise or AsyncIterable.
|
|
55
|
+
* You probably want to use `renderToString` or `renderToStream` instead.
|
|
56
|
+
*/
|
|
57
|
+
export declare const renderToStringSync: (node: Html) => string;
|
|
58
|
+
/**
|
|
59
|
+
* Convert an `Html` node to a properly escaped stream.
|
|
60
|
+
* Returns an `AsyncIterable<string>` if there are Promises or AsyncIterables in the input,
|
|
61
|
+
* otherwise returns a `string`.
|
|
62
|
+
*
|
|
63
|
+
* The string case is a lot more efficient – especially when then passed to
|
|
64
|
+
* Mastro's `htmlResponse`, to construct a `Response`.
|
|
65
|
+
*/
|
|
66
|
+
export declare const renderToStream: (node: Html) => string | AsyncIterable<string>;
|
|
67
|
+
//# sourceMappingURL=html.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"html.d.ts","sourceRoot":"","sources":["../../src/core/html.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH;;;;GAIG;AACH,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,SAAS,GAAG,IAAI,GAAG,KAAK,CAAC;AAEhF;;GAEG;AACH,MAAM,MAAM,IAAI,GACZ,aAAa,GACb,IAAI,EAAE,GACN,aAAa,CAAC,IAAI,CAAC,GACnB,OAAO,CAAC,IAAI,CAAC,CAAC;AAElB;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,IAAI,kBAAmB,oBAAoB,aAAa,IAAI,EAAE,KAAG,IAAI,EAmBjF,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,eAAe,QAAS,MAAM,KAAG,aAA+C,CAAC;AAE9F;;GAEG;AACH,eAAO,MAAM,eAAe,GAAI,CAAC,OAAO,GAAG,KAAG,GAAG,IAAI,aAAa,CAAC,CAAC,CACZ,CAAC;AAEzD;;;;GAIG;AACH,eAAO,MAAM,cAAc,SAAgB,IAAI,KAAG,OAAO,CAAC,MAAM,CAG/D,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,kBAAkB,SAAU,IAAI,KAAG,MAM/C,CAAA;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,cAAc,SAAU,IAAI,KAAG,MAAM,GAAG,aAAa,CAAC,MAAM,CA6ExE,CAAC"}
|