@mostra/plugin-mcp-app 0.0.0-placeholder → 0.17.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 +202 -0
- package/README.md +24 -1
- package/dist/index.d.ts +27 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +464 -0
- package/dist/index.js.map +1 -0
- package/package.json +83 -4
- package/src/bundle.ts +185 -0
- package/src/index.ts +198 -0
- package/src/page.ts +235 -0
package/src/bundle.ts
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Re-bundles a version's client build into one module (D175 item 2): the entry the build's
|
|
3
|
+
* `index.html` loads, its static and dynamic imports inlined, every file of the build it names by
|
|
4
|
+
* path (`"/assets/logo-H.png"`) as a `data:` URL, so the page needs nothing but itself.
|
|
5
|
+
*/
|
|
6
|
+
import type { FileTree } from "@mostra/contract-exporter";
|
|
7
|
+
import { rolldown } from "rolldown";
|
|
8
|
+
|
|
9
|
+
/** The media types of the files a page may name, by extension; anything else is octet-stream. */
|
|
10
|
+
const MEDIA_TYPES: Readonly<Record<string, string>> = {
|
|
11
|
+
".png": "image/png",
|
|
12
|
+
".jpg": "image/jpeg",
|
|
13
|
+
".jpeg": "image/jpeg",
|
|
14
|
+
".gif": "image/gif",
|
|
15
|
+
".webp": "image/webp",
|
|
16
|
+
".avif": "image/avif",
|
|
17
|
+
".svg": "image/svg+xml",
|
|
18
|
+
".ico": "image/x-icon",
|
|
19
|
+
".bmp": "image/bmp",
|
|
20
|
+
".mp3": "audio/mpeg",
|
|
21
|
+
".wav": "audio/wav",
|
|
22
|
+
".ogg": "audio/ogg",
|
|
23
|
+
".mp4": "video/mp4",
|
|
24
|
+
".webm": "video/webm",
|
|
25
|
+
".json": "application/json",
|
|
26
|
+
".txt": "text/plain",
|
|
27
|
+
".csv": "text/csv",
|
|
28
|
+
".css": "text/css",
|
|
29
|
+
".js": "text/javascript",
|
|
30
|
+
".wasm": "application/wasm",
|
|
31
|
+
".woff": "font/woff",
|
|
32
|
+
".woff2": "font/woff2",
|
|
33
|
+
".ttf": "font/ttf",
|
|
34
|
+
".otf": "font/otf",
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/** Font files, which a chat host's default policy never loads (no `font-src`, VERIFIED_FACTS). */
|
|
38
|
+
export const FONT_EXTENSIONS: readonly string[] = [".woff", ".woff2", ".ttf", ".otf", ".eot"];
|
|
39
|
+
|
|
40
|
+
/** The extension of a path, lower case, with its dot. */
|
|
41
|
+
export function extensionOf(path: string): string {
|
|
42
|
+
const name = path.slice(path.lastIndexOf("/") + 1);
|
|
43
|
+
const dot = name.lastIndexOf(".");
|
|
44
|
+
return dot <= 0 ? "" : name.slice(dot).toLowerCase();
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** A file as a `data:` URL. */
|
|
48
|
+
export function dataUrl(path: string, bytes: Uint8Array): string {
|
|
49
|
+
const type = MEDIA_TYPES[extensionOf(path)] ?? "application/octet-stream";
|
|
50
|
+
return `data:${type};base64,${Buffer.from(bytes).toString("base64")}`;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The client build's files the page may name by URL (`/assets/x.png`), by that URL. */
|
|
54
|
+
export interface ClientFiles {
|
|
55
|
+
/** Every file of `client/`, by its URL path (`/assets/index-H.js`). */
|
|
56
|
+
readonly paths: ReadonlySet<string>;
|
|
57
|
+
/** A file's bytes by its URL path. */
|
|
58
|
+
read(urlPath: string): Promise<Uint8Array>;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The client build of a version's file tree, by URL path. */
|
|
62
|
+
export async function clientFiles(files: FileTree): Promise<ClientFiles> {
|
|
63
|
+
const paths = new Set<string>();
|
|
64
|
+
for (const path of await files.list()) {
|
|
65
|
+
if (path.startsWith("client/")) paths.add(path.slice("client".length));
|
|
66
|
+
}
|
|
67
|
+
return { paths, read: (urlPath) => files.read(`client${urlPath}`) };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The characters a quoted URL path may hold, so a replacement never runs into code around it. */
|
|
71
|
+
const QUOTED_PATH = /(["'`])(\/[A-Za-z0-9._~\-/@%+]+)\1/g;
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Replaces each quoted URL path of a build file (`"/assets/logo-H.png"`) with its `data:` URL.
|
|
75
|
+
* Only exact quoted paths of files the build holds change, never text that merely contains one.
|
|
76
|
+
*/
|
|
77
|
+
export async function inlineQuotedPaths(
|
|
78
|
+
code: string,
|
|
79
|
+
client: ClientFiles,
|
|
80
|
+
skip: (urlPath: string) => boolean,
|
|
81
|
+
): Promise<{ readonly code: string; readonly inlined: readonly string[] }> {
|
|
82
|
+
const found = new Map<string, string>();
|
|
83
|
+
for (const match of code.matchAll(QUOTED_PATH)) {
|
|
84
|
+
const path = match[2] as string;
|
|
85
|
+
if (!client.paths.has(path) || skip(path) || found.has(path)) continue;
|
|
86
|
+
found.set(path, dataUrl(path, await client.read(path)));
|
|
87
|
+
}
|
|
88
|
+
if (found.size === 0) return { code, inlined: [] };
|
|
89
|
+
const replaced = code.replace(QUOTED_PATH, (whole, quote: string, path: string) => {
|
|
90
|
+
const url = found.get(path);
|
|
91
|
+
return url === undefined ? whole : `${quote}${url}${quote}`;
|
|
92
|
+
});
|
|
93
|
+
return { code: replaced, inlined: [...found.keys()] };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Resolves an import of a build module (`./chunk-H.js`, `/assets/x.js`) to its URL path. */
|
|
97
|
+
function resolveUrlPath(specifier: string, importer: string | undefined): string | undefined {
|
|
98
|
+
if (specifier.startsWith("/")) return new URL(specifier, "http://page.invalid").pathname;
|
|
99
|
+
if (specifier.startsWith("./") || specifier.startsWith("../")) {
|
|
100
|
+
const base = importer ?? "/";
|
|
101
|
+
return new URL(specifier, `http://page.invalid${base}`).pathname;
|
|
102
|
+
}
|
|
103
|
+
return undefined;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The prefix rolldown sees build modules under, so no path of this machine is ever read. */
|
|
107
|
+
const MODULE_PREFIX = "\0mostra-client:";
|
|
108
|
+
|
|
109
|
+
/** What {@link bundleEntry} produced. */
|
|
110
|
+
export interface Bundled {
|
|
111
|
+
/** The one module's code. */
|
|
112
|
+
readonly code: string;
|
|
113
|
+
/** The build's modules it holds, by URL path. */
|
|
114
|
+
readonly modules: readonly string[];
|
|
115
|
+
/** The files it names by URL that became `data:` URLs. */
|
|
116
|
+
readonly inlined: readonly string[];
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Bundles the build's module `entry` (a URL path) and everything it imports into one ES module.
|
|
121
|
+
* Every module comes from the version's file tree: an import outside it (a bare specifier, a URL)
|
|
122
|
+
* throws, since a built page imports only its own chunks.
|
|
123
|
+
*/
|
|
124
|
+
export async function bundleEntry(
|
|
125
|
+
entry: string,
|
|
126
|
+
client: ClientFiles,
|
|
127
|
+
skipInline: (urlPath: string) => boolean,
|
|
128
|
+
): Promise<Bundled> {
|
|
129
|
+
const modules: string[] = [];
|
|
130
|
+
const inlined = new Set<string>();
|
|
131
|
+
const build = await rolldown({
|
|
132
|
+
input: `${MODULE_PREFIX}${entry}`,
|
|
133
|
+
// The build is minified already; re-bundling only joins it.
|
|
134
|
+
treeshake: false,
|
|
135
|
+
logLevel: "silent",
|
|
136
|
+
plugins: [
|
|
137
|
+
{
|
|
138
|
+
name: "mostra-client",
|
|
139
|
+
resolveId(specifier, importer) {
|
|
140
|
+
const from = importer?.startsWith(MODULE_PREFIX)
|
|
141
|
+
? importer.slice(MODULE_PREFIX.length)
|
|
142
|
+
: undefined;
|
|
143
|
+
const target = specifier.startsWith(MODULE_PREFIX)
|
|
144
|
+
? specifier.slice(MODULE_PREFIX.length)
|
|
145
|
+
: resolveUrlPath(specifier, from);
|
|
146
|
+
if (target === undefined || !client.paths.has(target)) {
|
|
147
|
+
throw new Error(
|
|
148
|
+
`the build's module ${from ?? entry} imports ${JSON.stringify(specifier)}, which isn't a file of the build`,
|
|
149
|
+
);
|
|
150
|
+
}
|
|
151
|
+
return `${MODULE_PREFIX}${target}`;
|
|
152
|
+
},
|
|
153
|
+
async load(id) {
|
|
154
|
+
if (!id.startsWith(MODULE_PREFIX)) return null;
|
|
155
|
+
const path = id.slice(MODULE_PREFIX.length);
|
|
156
|
+
modules.push(path);
|
|
157
|
+
const text = new TextDecoder().decode(await client.read(path));
|
|
158
|
+
// The build's source map comment names a file the page won't have.
|
|
159
|
+
const code = text.replace(/\n\/\/# sourceMappingURL=[^\n]*\s*$/, "\n");
|
|
160
|
+
const done = await inlineQuotedPaths(code, client, (urlPath) => {
|
|
161
|
+
if (skipInline(urlPath)) return true;
|
|
162
|
+
// A module of the build is joined into the bundle, never inlined as a string.
|
|
163
|
+
return extensionOf(urlPath) === ".js" || extensionOf(urlPath) === ".map";
|
|
164
|
+
});
|
|
165
|
+
for (const path of done.inlined) inlined.add(path);
|
|
166
|
+
return { code: done.code, moduleType: "js" };
|
|
167
|
+
},
|
|
168
|
+
},
|
|
169
|
+
],
|
|
170
|
+
});
|
|
171
|
+
try {
|
|
172
|
+
const { output } = await build.generate({
|
|
173
|
+
format: "es",
|
|
174
|
+
// One module: dynamic imports are inlined, never split into chunks.
|
|
175
|
+
codeSplitting: false,
|
|
176
|
+
sourcemap: false,
|
|
177
|
+
comments: { legal: false },
|
|
178
|
+
});
|
|
179
|
+
const chunk = output.find((item) => item.type === "chunk");
|
|
180
|
+
if (chunk?.type !== "chunk") throw new Error("re-bundling produced no module");
|
|
181
|
+
return { code: chunk.code, modules, inlined: [...inlined] };
|
|
182
|
+
} finally {
|
|
183
|
+
await build.close();
|
|
184
|
+
}
|
|
185
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@mostra/plugin-mcp-app`: Mostra's MCP App exporter (D175 item 2, MC-02), the first first-party
|
|
3
|
+
* plugin, on `@mostra/contract-exporter`. It turns one published version into an MCP App: one
|
|
4
|
+
* self-contained HTML5 page (`index.html`, `text/html;profile=mcp-app`) that a chat host shows
|
|
5
|
+
* inline as `ui://mostra/view/<versionId>`, and `mcp-app.json`, that resource's description with
|
|
6
|
+
* the origins it declares (`_meta.ui.csp`). Every home has it (scope `bundled`, D175 item 3), so
|
|
7
|
+
* `mostra export <artifact> --as mcp-app --out <dir>` and `artifact_open` work with nothing
|
|
8
|
+
* installed.
|
|
9
|
+
*
|
|
10
|
+
* @packageDocumentation
|
|
11
|
+
*/
|
|
12
|
+
import {
|
|
13
|
+
defineExporter,
|
|
14
|
+
type Exporter,
|
|
15
|
+
type ExporterDefinition,
|
|
16
|
+
type ExportResult,
|
|
17
|
+
type Finding,
|
|
18
|
+
} from "@mostra/contract-exporter";
|
|
19
|
+
import {
|
|
20
|
+
APP_PAGE_MAX_CHARS,
|
|
21
|
+
MCP_APP_MIME_TYPE,
|
|
22
|
+
type McpAppResourceMeta,
|
|
23
|
+
mcpAppUri,
|
|
24
|
+
} from "@mostra/protocol";
|
|
25
|
+
import { bundleEntry, clientFiles, extensionOf, FONT_EXTENSIONS } from "./bundle.ts";
|
|
26
|
+
import { httpsOrigin, inlineStylesheet, ownOrigins, pageHtml, readBuiltPage } from "./page.ts";
|
|
27
|
+
|
|
28
|
+
/** The exporter's ID: what `mostra export --as` names. */
|
|
29
|
+
export const EXPORTER_ID = "mcp-app";
|
|
30
|
+
|
|
31
|
+
/** What `mcp-app.json` holds: the page's `ui://` resource as MCP lists it. */
|
|
32
|
+
export interface McpAppDescription {
|
|
33
|
+
/** The page's resource: `ui://mostra/view/<versionId>`. */
|
|
34
|
+
readonly uri: string;
|
|
35
|
+
/** A stable machine name: `mostra-<versionId>`. */
|
|
36
|
+
readonly name: string;
|
|
37
|
+
/** The artifact's title, for people. */
|
|
38
|
+
readonly title: string;
|
|
39
|
+
/** The artifact's description, when it has one. */
|
|
40
|
+
readonly description?: string;
|
|
41
|
+
/** `text/html;profile=mcp-app`. */
|
|
42
|
+
readonly mimeType: string;
|
|
43
|
+
/** What the page declares to its host: the origins it reaches, its border preference. */
|
|
44
|
+
readonly _meta: { readonly ui: McpAppResourceMeta };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The origins an option lists, each an `https:` origin, deduplicated. */
|
|
48
|
+
function originsOption(value: unknown, name: string): string[] {
|
|
49
|
+
if (value === undefined) return [];
|
|
50
|
+
const origins: string[] = [];
|
|
51
|
+
for (const entry of value as string[]) {
|
|
52
|
+
const origin = httpsOrigin(entry);
|
|
53
|
+
if (origin === undefined || origin !== entry.replace(/\/$/, "")) {
|
|
54
|
+
throw new Error(`${name} takes https: origins such as https://api.example.com, not ${entry}`);
|
|
55
|
+
}
|
|
56
|
+
if (!origins.includes(origin)) origins.push(origin);
|
|
57
|
+
}
|
|
58
|
+
return origins;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The exporter `mcp-app`: one version as an MCP App (the package's default export). */
|
|
62
|
+
const exporter: Exporter = defineExporter<ExporterDefinition>({
|
|
63
|
+
id: EXPORTER_ID,
|
|
64
|
+
title: "MCP App",
|
|
65
|
+
description:
|
|
66
|
+
"One self-contained page that chat hosts show inline (MCP Apps), with its ui:// resource's description.",
|
|
67
|
+
output: { mediaType: MCP_APP_MIME_TYPE, layout: "directory" },
|
|
68
|
+
options: {
|
|
69
|
+
type: "object",
|
|
70
|
+
additionalProperties: false,
|
|
71
|
+
properties: {
|
|
72
|
+
connectDomains: {
|
|
73
|
+
type: "array",
|
|
74
|
+
items: { type: "string" },
|
|
75
|
+
description: "More https: origins the page fetches from, beyond those its code names.",
|
|
76
|
+
},
|
|
77
|
+
resourceDomains: {
|
|
78
|
+
type: "array",
|
|
79
|
+
items: { type: "string" },
|
|
80
|
+
description: "More https: origins the page loads images, styles or media from.",
|
|
81
|
+
},
|
|
82
|
+
prefersBorder: {
|
|
83
|
+
type: "boolean",
|
|
84
|
+
description:
|
|
85
|
+
"Whether the host draws a border and background around the page; true unless set.",
|
|
86
|
+
},
|
|
87
|
+
},
|
|
88
|
+
},
|
|
89
|
+
async export({ version, files, options }, { signal }): Promise<ExportResult> {
|
|
90
|
+
const findings: Finding[] = [];
|
|
91
|
+
const client = await clientFiles(files);
|
|
92
|
+
const built = readBuiltPage(await files.readText("client/index.html"));
|
|
93
|
+
// Every stylesheet of the build: the page's own first, then those a dynamic import loads.
|
|
94
|
+
const stylesheets = [
|
|
95
|
+
...built.stylesheets,
|
|
96
|
+
...[...client.paths]
|
|
97
|
+
.filter((path) => extensionOf(path) === ".css" && !built.stylesheets.includes(path))
|
|
98
|
+
.sort(),
|
|
99
|
+
];
|
|
100
|
+
const cssParts: string[] = [];
|
|
101
|
+
const cssOrigins = new Set<string>();
|
|
102
|
+
let fonts = 0;
|
|
103
|
+
for (const sheet of stylesheets) {
|
|
104
|
+
if (!client.paths.has(sheet)) continue;
|
|
105
|
+
const inlined = await inlineStylesheet(
|
|
106
|
+
new TextDecoder().decode(await client.read(sheet)),
|
|
107
|
+
client,
|
|
108
|
+
);
|
|
109
|
+
cssParts.push(inlined.css);
|
|
110
|
+
for (const origin of inlined.origins) cssOrigins.add(origin);
|
|
111
|
+
fonts += inlined.fonts;
|
|
112
|
+
}
|
|
113
|
+
if (signal.aborted) throw new Error("cancelled");
|
|
114
|
+
const bundled = await bundleEntry(built.entry, client, (path) =>
|
|
115
|
+
FONT_EXTENSIONS.includes(extensionOf(path)),
|
|
116
|
+
);
|
|
117
|
+
const codeOrigins = await ownOrigins(files, bundled.modules);
|
|
118
|
+
const connectDomains = [
|
|
119
|
+
...new Set([...codeOrigins, ...originsOption(options["connectDomains"], "connectDomains")]),
|
|
120
|
+
].sort();
|
|
121
|
+
const resourceDomains = [
|
|
122
|
+
...new Set([
|
|
123
|
+
...codeOrigins,
|
|
124
|
+
...cssOrigins,
|
|
125
|
+
...originsOption(options["resourceDomains"], "resourceDomains"),
|
|
126
|
+
]),
|
|
127
|
+
].sort();
|
|
128
|
+
const meta: McpAppResourceMeta = {
|
|
129
|
+
...(connectDomains.length > 0 || resourceDomains.length > 0
|
|
130
|
+
? {
|
|
131
|
+
csp: {
|
|
132
|
+
...(connectDomains.length > 0 ? { connectDomains } : {}),
|
|
133
|
+
...(resourceDomains.length > 0 ? { resourceDomains } : {}),
|
|
134
|
+
},
|
|
135
|
+
}
|
|
136
|
+
: {}),
|
|
137
|
+
// Said every time, since hosts' own defaults differ (MCP Apps recommends an explicit value):
|
|
138
|
+
// a border and background, so the page and its bar read as one card, unless asked otherwise.
|
|
139
|
+
prefersBorder:
|
|
140
|
+
typeof options["prefersBorder"] === "boolean" ? options["prefersBorder"] : true,
|
|
141
|
+
};
|
|
142
|
+
const html = pageHtml({
|
|
143
|
+
title: version.title,
|
|
144
|
+
lang: built.lang,
|
|
145
|
+
versionId: version.versionId,
|
|
146
|
+
css: cssParts.join("\n"),
|
|
147
|
+
code: bundled.code,
|
|
148
|
+
});
|
|
149
|
+
if (html.length > APP_PAGE_MAX_CHARS) {
|
|
150
|
+
findings.push({
|
|
151
|
+
code: "PAGE_TOO_LARGE",
|
|
152
|
+
severity: "error",
|
|
153
|
+
message: `The page is ${Math.ceil(html.length / 1024 / 1024)} MiB, past the 16 MiB an MCP App may be.`,
|
|
154
|
+
hint: "Load large media from an https: origin instead of bundling it.",
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
if (version.server) {
|
|
158
|
+
findings.push({
|
|
159
|
+
code: "SERVER_CODE",
|
|
160
|
+
severity: "hint",
|
|
161
|
+
message:
|
|
162
|
+
"The page's actions and live data reach Mostra through its MCP server's app tools; a host that serves this page without them shows them as unavailable.",
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
if (fonts > 0) {
|
|
166
|
+
findings.push({
|
|
167
|
+
code: "FONTS_FROM_HOST",
|
|
168
|
+
severity: "hint",
|
|
169
|
+
message: `The page's own faces (${fonts}) are left out: a chat host loads no font files, and its own faces take their place.`,
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
if (resourceDomains.length > 0 || connectDomains.length > 0) {
|
|
173
|
+
findings.push({
|
|
174
|
+
code: "ORIGINS_DECLARED",
|
|
175
|
+
severity: "hint",
|
|
176
|
+
message: `The page declares ${[...new Set([...connectDomains, ...resourceDomains])].join(", ")} for a host that shows this resource itself; shown inline through artifact_open, whose loader declares no origin, it loads none of them, and says so for each (D175 item 2).`,
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
const description: McpAppDescription = {
|
|
180
|
+
uri: mcpAppUri(version.versionId),
|
|
181
|
+
name: `mostra-${version.versionId}`,
|
|
182
|
+
title: version.title,
|
|
183
|
+
...(version.description !== undefined ? { description: version.description } : {}),
|
|
184
|
+
mimeType: MCP_APP_MIME_TYPE,
|
|
185
|
+
_meta: { ui: meta },
|
|
186
|
+
};
|
|
187
|
+
return {
|
|
188
|
+
files: [
|
|
189
|
+
{ path: "index.html", content: html },
|
|
190
|
+
{ path: "mcp-app.json", content: `${JSON.stringify(description, null, 2)}\n` },
|
|
191
|
+
],
|
|
192
|
+
entry: "index.html",
|
|
193
|
+
findings,
|
|
194
|
+
};
|
|
195
|
+
},
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
export default exporter;
|
package/src/page.ts
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The MCP App's document (D175 item 2): one HTML5 page holding the version's whole client build,
|
|
3
|
+
* marked for the `mcp-app` target, with the token table the runtime applies to the host's context
|
|
4
|
+
* and the origins its own code names, declared for the host's policy.
|
|
5
|
+
*/
|
|
6
|
+
import type { FileTree } from "@mostra/contract-exporter";
|
|
7
|
+
import { HOST_TOKENS } from "@mostra/themes";
|
|
8
|
+
import { type ClientFiles, dataUrl, extensionOf, FONT_EXTENSIONS } from "./bundle.ts";
|
|
9
|
+
|
|
10
|
+
/** Escapes text for HTML content and attribute values. */
|
|
11
|
+
export function escapeHtml(text: string): string {
|
|
12
|
+
return text
|
|
13
|
+
.replaceAll("&", "&")
|
|
14
|
+
.replaceAll("<", "<")
|
|
15
|
+
.replaceAll(">", ">")
|
|
16
|
+
.replaceAll('"', """)
|
|
17
|
+
.replaceAll("'", "'");
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* A stylesheet's text inside `<style>`, where `</style` would end it: written `<\/style`, which
|
|
22
|
+
* CSS reads as the same text (`\/` is `/`), in a string, a comment or anywhere else.
|
|
23
|
+
*/
|
|
24
|
+
export function styleText(css: string): string {
|
|
25
|
+
return css.replace(/<\/(style)/gi, "<\\/$1");
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The page's own code, run without its text ever going through the HTML parser (review findings
|
|
30
|
+
* Opus 11, Fable 12): rewriting `</script`, `<script` or `<!--` is right in a string and wrong in
|
|
31
|
+
* code (`i<scriptCount`), and only a JavaScript tokenizer could tell them apart. So the module
|
|
32
|
+
* travels as base64, which has no `<`, in an inert element, and {@link MODULE_BOOTSTRAP}, Mostra's
|
|
33
|
+
* own few lines, decodes it and gives it to a module script as its `textContent`: the code runs
|
|
34
|
+
* byte for byte as built. MCP Apps' default policy allows inline scripts (`'unsafe-inline'`).
|
|
35
|
+
*/
|
|
36
|
+
export const MODULE_BOOTSTRAP: string = [
|
|
37
|
+
"(function () {",
|
|
38
|
+
// A file the build fetches (`new URL("./data.csv", import.meta.url)`, a wasm module) is a
|
|
39
|
+
// data: URL here, which a host's `connect-src 'none'` would block: it is answered from memory,
|
|
40
|
+
// with its own type (review finding Fable 13). Every other request goes as it would.
|
|
41
|
+
" var native = window.fetch;",
|
|
42
|
+
' if (typeof native === "function") {',
|
|
43
|
+
" window.fetch = function (input, init) {",
|
|
44
|
+
' var url = typeof input === "string" ? input : input && (input.href || input.url);',
|
|
45
|
+
' var comma = typeof url === "string" && url.slice(0, 5) === "data:" ? url.indexOf(",") : -1;',
|
|
46
|
+
" if (comma === -1) return native.apply(this, arguments);",
|
|
47
|
+
" var head = url.slice(5, comma);",
|
|
48
|
+
" var payload = url.slice(comma + 1);",
|
|
49
|
+
" var encoded = /;base64$/i.test(head);",
|
|
50
|
+
' var type = head.replace(/;base64$/i, "") || "text/plain;charset=US-ASCII";',
|
|
51
|
+
" var data;",
|
|
52
|
+
" if (encoded) {",
|
|
53
|
+
" var raw = atob(payload);",
|
|
54
|
+
" data = new Uint8Array(raw.length);",
|
|
55
|
+
" for (var j = 0; j !== raw.length; j++) data[j] = raw.charCodeAt(j);",
|
|
56
|
+
" } else data = new TextEncoder().encode(decodeURIComponent(payload));",
|
|
57
|
+
' return Promise.resolve(new Response(data, { headers: { "content-type": type } }));',
|
|
58
|
+
" };",
|
|
59
|
+
" }",
|
|
60
|
+
' var carrier = document.getElementById("mostra-module");',
|
|
61
|
+
" if (carrier === null) return;",
|
|
62
|
+
' var binary = atob((carrier.textContent || "").trim());',
|
|
63
|
+
" var bytes = new Uint8Array(binary.length);",
|
|
64
|
+
" for (var i = 0; i !== binary.length; i++) bytes[i] = binary.charCodeAt(i);",
|
|
65
|
+
' var module = document.createElement("script");',
|
|
66
|
+
' module.type = "module";',
|
|
67
|
+
" module.textContent = new TextDecoder().decode(bytes);",
|
|
68
|
+
" document.body.append(module);",
|
|
69
|
+
"})();",
|
|
70
|
+
].join("\n");
|
|
71
|
+
|
|
72
|
+
/** The two elements that carry and run the page's module (see {@link MODULE_BOOTSTRAP}). */
|
|
73
|
+
export function moduleElements(code: string): string {
|
|
74
|
+
const encoded = Buffer.from(code, "utf8").toString("base64");
|
|
75
|
+
return [
|
|
76
|
+
` <script type="application/octet-stream" id="mostra-module">${encoded}</script>`,
|
|
77
|
+
` <script>${MODULE_BOOTSTRAP}</script>`,
|
|
78
|
+
].join("\n");
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** What the build's `index.html` names: its module entry and stylesheets, its language. */
|
|
82
|
+
export interface BuiltPage {
|
|
83
|
+
readonly entry: string;
|
|
84
|
+
readonly stylesheets: readonly string[];
|
|
85
|
+
readonly lang: string;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Reads the build's `index.html` (the builder's own, INTERFACES §11). */
|
|
89
|
+
export function readBuiltPage(html: string): BuiltPage {
|
|
90
|
+
const entry = /<script\b[^>]*\btype="module"[^>]*\bsrc="([^"]+)"/i.exec(html)?.[1];
|
|
91
|
+
if (entry === undefined) throw new Error("the build's index.html names no module script");
|
|
92
|
+
const stylesheets = [
|
|
93
|
+
...html.matchAll(/<link\b[^>]*\brel="stylesheet"[^>]*\bhref="([^"]+)"/gi),
|
|
94
|
+
].map((match) => match[1] as string);
|
|
95
|
+
const lang = /<html\b[^>]*\blang="([^"]*)"/i.exec(html)?.[1] ?? "en";
|
|
96
|
+
return { entry, stylesheets, lang };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The URLs a stylesheet names: `url(x)`, `url("x")`, `url('x')`. */
|
|
100
|
+
const CSS_URL = /url\(\s*(["']?)([^"')]+)\1\s*\)/g;
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* A stylesheet for the page: each file of the build it names as a `data:` URL, its `@font-face`
|
|
104
|
+
* rules for the build's own faces left out (a chat host's policy loads no font, VERIFIED_FACTS,
|
|
105
|
+
* WP-17; the host's faces take their place, D141 item 4), and the absolute `https:` origins it
|
|
106
|
+
* names.
|
|
107
|
+
*/
|
|
108
|
+
export async function inlineStylesheet(
|
|
109
|
+
css: string,
|
|
110
|
+
client: ClientFiles,
|
|
111
|
+
): Promise<{ readonly css: string; readonly origins: readonly string[]; readonly fonts: number }> {
|
|
112
|
+
let fonts = 0;
|
|
113
|
+
const withoutFaces = css.replace(/@font-face\s*\{[^}]*\}/g, (rule) => {
|
|
114
|
+
const named = [...rule.matchAll(CSS_URL)].map((match) => match[2] as string);
|
|
115
|
+
const ours =
|
|
116
|
+
named.length > 0 && named.every((url) => client.paths.has(url.split(/[?#]/)[0] ?? url));
|
|
117
|
+
if (!ours) return rule;
|
|
118
|
+
fonts += 1;
|
|
119
|
+
return "";
|
|
120
|
+
});
|
|
121
|
+
const origins = new Set<string>();
|
|
122
|
+
const urls = new Map<string, string>();
|
|
123
|
+
for (const match of withoutFaces.matchAll(CSS_URL)) {
|
|
124
|
+
const url = match[2] as string;
|
|
125
|
+
const path = url.split(/[?#]/)[0] ?? url;
|
|
126
|
+
if (client.paths.has(path) && !FONT_EXTENSIONS.includes(extensionOf(path))) {
|
|
127
|
+
if (!urls.has(path)) urls.set(path, dataUrl(path, await client.read(path)));
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
const origin = httpsOrigin(url);
|
|
131
|
+
if (origin !== undefined) origins.add(origin);
|
|
132
|
+
}
|
|
133
|
+
const inlined = withoutFaces.replace(CSS_URL, (whole, _quote: string, url: string) => {
|
|
134
|
+
const path = url.split(/[?#]/)[0] ?? url;
|
|
135
|
+
const data = urls.get(path);
|
|
136
|
+
return data === undefined ? whole : `url("${data}")`;
|
|
137
|
+
});
|
|
138
|
+
return { css: inlined, origins: [...origins], fonts };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** The origin of an absolute `https:` URL, or `undefined`. */
|
|
142
|
+
export function httpsOrigin(url: string): string | undefined {
|
|
143
|
+
if (!/^https:\/\//i.test(url)) return undefined;
|
|
144
|
+
try {
|
|
145
|
+
const parsed = new URL(url);
|
|
146
|
+
return parsed.hostname === "" ? undefined : parsed.origin;
|
|
147
|
+
} catch {
|
|
148
|
+
return undefined;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Absolute `https:` URLs in code. */
|
|
153
|
+
const HTTPS_URL = /https:\/\/[A-Za-z0-9.-]+(?::\d{1,5})?/g;
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* The `https:` origins the artifact's own code names, from the build's source maps: only the
|
|
157
|
+
* sources the artifact wrote (under its `source/` directory, never a package's), since packages'
|
|
158
|
+
* documentation links (react.dev, json-schema.org) are never fetched. A build without source maps
|
|
159
|
+
* declares every origin its modules name.
|
|
160
|
+
*/
|
|
161
|
+
export async function ownOrigins(
|
|
162
|
+
files: FileTree,
|
|
163
|
+
modules: readonly string[],
|
|
164
|
+
): Promise<readonly string[]> {
|
|
165
|
+
const origins = new Set<string>();
|
|
166
|
+
const listed = new Set(await files.list());
|
|
167
|
+
for (const module of modules) {
|
|
168
|
+
const map = `client${module}.map`;
|
|
169
|
+
if (!listed.has(map)) {
|
|
170
|
+
for (const match of (await files.readText(`client${module}`)).matchAll(HTTPS_URL)) {
|
|
171
|
+
const origin = httpsOrigin(match[0]);
|
|
172
|
+
if (origin) origins.add(origin);
|
|
173
|
+
}
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
const parsed = JSON.parse(await files.readText(map)) as {
|
|
177
|
+
sources?: (string | null)[];
|
|
178
|
+
sourcesContent?: (string | null)[];
|
|
179
|
+
};
|
|
180
|
+
for (const [index, source] of (parsed.sources ?? []).entries()) {
|
|
181
|
+
if (source === null || !isOwnSource(source)) continue;
|
|
182
|
+
const content = parsed.sourcesContent?.[index];
|
|
183
|
+
if (typeof content !== "string") continue;
|
|
184
|
+
for (const match of content.matchAll(HTTPS_URL)) {
|
|
185
|
+
const origin = httpsOrigin(match[0]);
|
|
186
|
+
if (origin) origins.add(origin);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return [...origins].sort();
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Whether a source map's source is the artifact's own file, not a package's or Mostra's. */
|
|
194
|
+
export function isOwnSource(source: string): boolean {
|
|
195
|
+
const path = source.replaceAll("\\", "/");
|
|
196
|
+
return /(^|\/)source\//.test(path) && !path.includes("/node_modules/");
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** The page's parts. */
|
|
200
|
+
export interface PageParts {
|
|
201
|
+
readonly title: string;
|
|
202
|
+
readonly lang: string;
|
|
203
|
+
readonly versionId: string;
|
|
204
|
+
readonly css: string;
|
|
205
|
+
readonly code: string;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* The document. The module runs last, after the stylesheet; a dynamic import's preload of a
|
|
210
|
+
* stylesheet or chunk the page already holds is told not to fail (Vite's `vite:preloadError`).
|
|
211
|
+
*/
|
|
212
|
+
export function pageHtml(parts: PageParts): string {
|
|
213
|
+
// JSON's own escape for `<`, so no sequence in it can end the script element.
|
|
214
|
+
const tokens = JSON.stringify(HOST_TOKENS).replaceAll("<", "\\u003c");
|
|
215
|
+
return [
|
|
216
|
+
"<!doctype html>",
|
|
217
|
+
`<html lang="${escapeHtml(parts.lang)}">`,
|
|
218
|
+
" <head>",
|
|
219
|
+
' <meta charset="utf-8" />',
|
|
220
|
+
' <meta name="viewport" content="width=device-width, initial-scale=1" />',
|
|
221
|
+
` <meta name="mostra-version" content="${escapeHtml(parts.versionId)}" />`,
|
|
222
|
+
' <meta name="mostra-target" content="mcp-app" />',
|
|
223
|
+
` <title>${escapeHtml(parts.title)}</title>`,
|
|
224
|
+
` <script type="application/json" id="mostra-host-tokens">${tokens}</script>`,
|
|
225
|
+
' <script>addEventListener("vite:preloadError", function (event) { event.preventDefault(); });</script>',
|
|
226
|
+
` <style>${styleText(parts.css)}</style>`,
|
|
227
|
+
" </head>",
|
|
228
|
+
" <body>",
|
|
229
|
+
' <div id="root"></div>',
|
|
230
|
+
moduleElements(parts.code),
|
|
231
|
+
" </body>",
|
|
232
|
+
"</html>",
|
|
233
|
+
"",
|
|
234
|
+
].join("\n");
|
|
235
|
+
}
|