@botiverse/porthole 0.5.1 → 0.6.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 (73) hide show
  1. package/README.md +25 -0
  2. package/dist/bridge/bridge.js +8 -5
  3. package/dist/bridge/navigation.d.ts +1 -6
  4. package/dist/bridge/navigation.js +11 -0
  5. package/dist/check/check.d.ts +12 -3
  6. package/dist/check/check.js +54 -8
  7. package/dist/check/files.d.ts +26 -0
  8. package/dist/check/files.js +307 -0
  9. package/dist/check/lint.js +27 -10
  10. package/dist/check/page-source.js +1 -1
  11. package/dist/check/tools.d.ts +23 -0
  12. package/dist/check/tools.js +25 -0
  13. package/dist/compile/policy.d.ts +15 -0
  14. package/dist/compile/policy.js +32 -0
  15. package/dist/config/schema.d.ts +8 -0
  16. package/dist/config/validate.js +8 -1
  17. package/dist/conformance/harness-source.js +1 -1
  18. package/dist/files/paths.d.ts +99 -0
  19. package/dist/files/paths.js +263 -0
  20. package/dist/files/types.d.ts +24 -0
  21. package/dist/files/types.js +83 -0
  22. package/dist/guide/guide.js +11 -1
  23. package/dist/host/create-host.js +21 -0
  24. package/dist/index.d.ts +6 -3
  25. package/dist/index.js +8 -3
  26. package/dist/protocol/adapter.d.ts +4 -0
  27. package/dist/protocol/mcp-apps.d.ts +6 -0
  28. package/dist/protocol/mcp-apps.js +6 -0
  29. package/dist/protocol/shell-adapter.js +5 -1
  30. package/dist/server/files.d.ts +44 -0
  31. package/dist/server/files.js +244 -0
  32. package/dist/server/host.d.ts +38 -1
  33. package/dist/server/host.js +37 -2
  34. package/dist/server/index.d.ts +4 -2
  35. package/dist/server/index.js +4 -1
  36. package/dist/server/keys.d.ts +8 -0
  37. package/dist/server/keys.js +34 -0
  38. package/dist/server/server.js +287 -22
  39. package/dist/server/types.d.ts +49 -5
  40. package/dist/shell/document.d.ts +19 -0
  41. package/dist/shell/document.js +30 -0
  42. package/dist/shell/runtime.d.ts +2 -1
  43. package/dist/shell/runtime.js +85 -4
  44. package/docs/ADOPTING.md +56 -4
  45. package/docs/ARCHITECTURE.md +13 -3
  46. package/docs/DECISIONS.md +304 -4
  47. package/docs/DESIGN.md +31 -3
  48. package/package.json +1 -1
  49. package/src/bridge/bridge.ts +8 -5
  50. package/src/bridge/navigation.ts +12 -0
  51. package/src/check/check.ts +92 -14
  52. package/src/check/files.ts +384 -0
  53. package/src/check/lint.ts +29 -10
  54. package/src/check/tools.ts +50 -0
  55. package/src/compile/policy.ts +38 -0
  56. package/src/config/schema.ts +8 -0
  57. package/src/config/validate.ts +8 -1
  58. package/src/files/paths.ts +323 -0
  59. package/src/files/types.ts +101 -0
  60. package/src/guide/guide.ts +20 -0
  61. package/src/host/create-host.ts +21 -0
  62. package/src/index.ts +32 -0
  63. package/src/protocol/adapter.ts +3 -1
  64. package/src/protocol/mcp-apps.ts +7 -0
  65. package/src/protocol/shell-adapter.ts +5 -0
  66. package/src/server/files.ts +312 -0
  67. package/src/server/host.ts +72 -3
  68. package/src/server/index.ts +19 -0
  69. package/src/server/keys.ts +53 -0
  70. package/src/server/server.ts +353 -24
  71. package/src/server/types.ts +56 -4
  72. package/src/shell/document.ts +53 -0
  73. package/src/shell/runtime.ts +85 -4
@@ -0,0 +1,323 @@
1
+ import type { Limits, PortholeConfig } from "../config/schema.ts";
2
+
3
+ /**
4
+ * A version made of files (P081): the rules a published path follows, the limits a version is
5
+ * held to, and how a request's path finds its file. Pure: any runtime. A host checks a version
6
+ * with `checkFileSet` when it is published; `/server` looks paths up in the version's manifest
7
+ * only, never on a filesystem.
8
+ */
9
+
10
+ /** The most files a version holds, by default. */
11
+ export const DEFAULT_MAX_FILES = 1_000;
12
+ /** The largest file of a version, bytes, by default (25 MiB). */
13
+ export const DEFAULT_MAX_FILE_BYTES = 25 * 1024 * 1024;
14
+ /** A version's files together, bytes, by default (100 MiB): a host sets its own. */
15
+ export const DEFAULT_MAX_VERSION_BYTES = 100 * 1024 * 1024;
16
+ /** The longest path, characters, and the longest segment of one. */
17
+ export const MAX_FILE_PATH_CHARS = 512;
18
+ export const MAX_SEGMENT_CHARS = 255;
19
+ /** The page a version opens at by default. */
20
+ export const DEFAULT_ENTRY = "index.html";
21
+
22
+ /**
23
+ * Whether a config's pages may come with files of their own (P081): an artifact served on an
24
+ * origin of its own. Opaque frames have no origin to serve them from.
25
+ */
26
+ export const servesFiles = (config: PortholeConfig): boolean =>
27
+ config.mode === "artifact" && config.isolation === "domain";
28
+
29
+ export interface FileLimits {
30
+ readonly maxFiles: number;
31
+ readonly maxFileBytes: number;
32
+ readonly maxVersionBytes: number;
33
+ }
34
+
35
+ /** A config's file limits (`limits.maxFiles`, …), with the defaults where it names none. */
36
+ export function fileLimits(limits?: Partial<Limits> | null): FileLimits {
37
+ return {
38
+ maxFiles: limits?.maxFiles ?? DEFAULT_MAX_FILES,
39
+ maxFileBytes: limits?.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES,
40
+ maxVersionBytes: limits?.maxVersionBytes ?? DEFAULT_MAX_VERSION_BYTES,
41
+ };
42
+ }
43
+
44
+ /**
45
+ * What a request's path can never hold once decoded, and a published path never holds: control
46
+ * and format characters (`Cc`, `Cf`: a right-to-left override, a zero-width space, a BOM would make
47
+ * a path read as another), and `\ % ? #`.
48
+ */
49
+ // oxlint-disable-next-line no-control-regex -- control characters are what it refuses
50
+ const FORBIDDEN = /[\p{Cc}\p{Cf}\\%?#]/u;
51
+
52
+ /**
53
+ * What is wrong with a published path, or null: relative (no leading `/`), `/`-separated, no
54
+ * empty, `.` or `..` segment, none of `\ % ? #` or a control character, in Unicode NFC, no segment
55
+ * starting or ending with a space, at most 512 characters and 255 a segment, not under
56
+ * `__porthole/` (Porthole's own paths at an origin's root). Case-sensitive.
57
+ */
58
+ export function filePathProblem(path: unknown): string | null {
59
+ if (typeof path !== "string" || path.length === 0) {
60
+ return "a path is a non-empty string";
61
+ }
62
+ if (path.length > MAX_FILE_PATH_CHARS) {
63
+ return `a path is at most ${MAX_FILE_PATH_CHARS} characters`;
64
+ }
65
+ if (path.startsWith("/")) {
66
+ return "a path is relative: no leading /";
67
+ }
68
+ if (path.endsWith("/")) {
69
+ return "a path names a file: no trailing /";
70
+ }
71
+ const forbidden = FORBIDDEN.exec(path);
72
+ if (forbidden !== null) {
73
+ const char = forbidden[0];
74
+ return `a path holds no ${char === "\\" || char === "%" || char === "?" || char === "#" ? char : "control or format character"}`;
75
+ }
76
+ if (path.normalize("NFC") !== path) {
77
+ return "a path is in Unicode NFC";
78
+ }
79
+ const segments = path.split("/");
80
+ for (const segment of segments) {
81
+ if (segment === "") {
82
+ return "a path has no empty segment (//)";
83
+ }
84
+ if (segment === "." || segment === "..") {
85
+ return `a path has no ${segment} segment`;
86
+ }
87
+ if (segment.length > MAX_SEGMENT_CHARS) {
88
+ return `a path's segment is at most ${MAX_SEGMENT_CHARS} characters`;
89
+ }
90
+ if (segment.startsWith(" ") || segment.endsWith(" ")) {
91
+ return "a path's segment doesn't start or end with a space";
92
+ }
93
+ }
94
+ if (segments[0] === "__porthole") {
95
+ return "__porthole/ is Porthole's own";
96
+ }
97
+ return null;
98
+ }
99
+
100
+ /** A published path's metadata, as far as the checks read it. */
101
+ export interface FileSetEntryLike {
102
+ readonly size: number;
103
+ }
104
+
105
+ export interface FileSetProblem {
106
+ /** The path it is about, where it is about one. */
107
+ readonly path?: string;
108
+ readonly code: "path" | "collision" | "count" | "size" | "total" | "entry";
109
+ /** What to change, for the agent or the person publishing. */
110
+ readonly message: string;
111
+ }
112
+
113
+ const sizeOf = (bytes: number): string =>
114
+ bytes >= 1024 * 1024
115
+ ? `${Math.round((bytes / (1024 * 1024)) * 10) / 10} MiB`
116
+ : bytes >= 1024
117
+ ? `${Math.round(bytes / 1024)} KiB`
118
+ : `${bytes} bytes`;
119
+
120
+ /**
121
+ * Checks a version's files before it is published (P081): every path by `filePathProblem`; no
122
+ * two paths that differ only in case, and no path that is both a file and a directory; the
123
+ * entry is one of them; the count, each size and the total within the limits (a config's, see
124
+ * `fileLimits`). Empty when it may be published.
125
+ */
126
+ export function checkFileSet(
127
+ files: Readonly<Record<string, FileSetEntryLike>>,
128
+ options: { readonly entry?: string; readonly limits?: FileLimits } = {},
129
+ ): FileSetProblem[] {
130
+ const limits = options.limits ?? fileLimits();
131
+ const problems: FileSetProblem[] = [];
132
+ const paths = Object.keys(files);
133
+ if (paths.length > limits.maxFiles) {
134
+ problems.push({
135
+ code: "count",
136
+ message: `${paths.length} files: a version holds at most ${limits.maxFiles}`,
137
+ });
138
+ }
139
+ const folded = new Map<string, string>();
140
+ const directories = new Set<string>();
141
+ let total = 0;
142
+ for (const path of paths) {
143
+ const problem = filePathProblem(path);
144
+ if (problem !== null) {
145
+ problems.push({ path, code: "path", message: `${JSON.stringify(path)}: ${problem}` });
146
+ continue;
147
+ }
148
+ const lower = path.toLowerCase();
149
+ const other = folded.get(lower);
150
+ if (other !== undefined) {
151
+ problems.push({
152
+ path,
153
+ code: "collision",
154
+ message: `${JSON.stringify(path)} and ${JSON.stringify(other)} differ only in case: rename one`,
155
+ });
156
+ } else {
157
+ folded.set(lower, path);
158
+ }
159
+ const segments = path.split("/");
160
+ for (let index = 1; index < segments.length; index += 1) {
161
+ directories.add(segments.slice(0, index).join("/"));
162
+ }
163
+ const size = files[path]?.size;
164
+ if (typeof size !== "number" || !Number.isInteger(size) || size < 0) {
165
+ problems.push({ path, code: "size", message: `${JSON.stringify(path)}: no size` });
166
+ continue;
167
+ }
168
+ if (size > limits.maxFileBytes) {
169
+ problems.push({
170
+ path,
171
+ code: "size",
172
+ message: `${JSON.stringify(path)} is ${sizeOf(size)}: a file is at most ${sizeOf(limits.maxFileBytes)}`,
173
+ });
174
+ }
175
+ total += size;
176
+ }
177
+ for (const path of paths) {
178
+ if (directories.has(path)) {
179
+ problems.push({
180
+ path,
181
+ code: "collision",
182
+ message: `${JSON.stringify(path)} is a file and a directory: rename one`,
183
+ });
184
+ }
185
+ }
186
+ if (total > limits.maxVersionBytes) {
187
+ problems.push({
188
+ code: "total",
189
+ message: `The files are ${sizeOf(total)} together: a version holds at most ${sizeOf(limits.maxVersionBytes)}`,
190
+ });
191
+ }
192
+ const entry = options.entry ?? DEFAULT_ENTRY;
193
+ if (!Object.hasOwn(files, entry)) {
194
+ problems.push({
195
+ path: entry,
196
+ code: "entry",
197
+ message: `No ${JSON.stringify(entry)}: the page the version opens at is one of its files`,
198
+ });
199
+ }
200
+ return problems;
201
+ }
202
+
203
+ /**
204
+ * A request's path below a version's base, decoded once, as the key it looks up: null where it
205
+ * can name no file (a segment that doesn't decode, or decodes to one holding `/ \ % ? #` or a
206
+ * control character, or is `.` or `..`). The URL parser has already removed the dot segments it
207
+ * sees (`.`, `..`, `%2e`); anything left of that kind is refused rather than resolved. A trailing
208
+ * `/` stays (a directory).
209
+ */
210
+ export function requestFilePath(raw: string): string | null {
211
+ if (raw.length > MAX_FILE_PATH_CHARS * 3 + 1) {
212
+ return null;
213
+ }
214
+ const segments = raw.split("/");
215
+ const decoded: string[] = [];
216
+ for (const [index, segment] of segments.entries()) {
217
+ if (segment === "") {
218
+ // Only the last segment may be empty: a directory's trailing slash (or the base itself).
219
+ if (index !== segments.length - 1) {
220
+ return null;
221
+ }
222
+ decoded.push("");
223
+ continue;
224
+ }
225
+ let value: string;
226
+ try {
227
+ value = decodeURIComponent(segment);
228
+ } catch {
229
+ return null;
230
+ }
231
+ if (value === "." || value === ".." || value.includes("/") || FORBIDDEN.test(value)) {
232
+ return null;
233
+ }
234
+ decoded.push(value);
235
+ }
236
+ return decoded.join("/");
237
+ }
238
+
239
+ /** What a request's path finds in a version's manifest. */
240
+ export type FileLookup =
241
+ /** The file to answer with, and its status (404 for a `404.html`). */
242
+ | { readonly kind: "file"; readonly path: string; readonly status: 200 | 404 }
243
+ /** The canonical address: `dir` → `dir/` (or `page/` → `page`), relative to the base. */
244
+ | { readonly kind: "redirect"; readonly to: string }
245
+ /** Nothing: a plain 404. */
246
+ | { readonly kind: "none" };
247
+
248
+ export interface LookupOptions {
249
+ /** The page the version opens at (default `index.html`). */
250
+ readonly entry?: string;
251
+ /** A single-page app's routes: a navigation that finds nothing answers the entry. */
252
+ readonly spa?: boolean;
253
+ /** Whether the request is a navigation (a page loading), not a subresource. */
254
+ readonly navigation: boolean;
255
+ }
256
+
257
+ /**
258
+ * Finds a request's file in a version's manifest (P081), as static hosts do (Cloudflare's
259
+ * `auto-trailing-slash`): `""` is the entry; `dir/` is `dir/index.html`; `name` is `name`, else
260
+ * `name.html`, else `dir/` when `name/index.html` exists; `name/` with no index but a
261
+ * `name.html` goes to `name`. What finds nothing: for a navigation, the entry when the version is
262
+ * a single-page app, else the nearest `404.html` (status 404); otherwise none.
263
+ */
264
+ export function lookupFile(
265
+ has: (path: string) => boolean,
266
+ path: string,
267
+ options: LookupOptions,
268
+ ): FileLookup {
269
+ const entry = options.entry ?? DEFAULT_ENTRY;
270
+ if (path === "") {
271
+ if (!has(entry)) {
272
+ return notFound(has, "", options);
273
+ }
274
+ // An entry in a directory opens there, so its relative addresses are its directory's.
275
+ return entry.includes("/")
276
+ ? { kind: "redirect", to: entry }
277
+ : { kind: "file", path: entry, status: 200 };
278
+ }
279
+ if (path.endsWith("/")) {
280
+ const index = `${path}index.html`;
281
+ if (has(index)) {
282
+ return { kind: "file", path: index, status: 200 };
283
+ }
284
+ const page = `${path.slice(0, -1)}.html`;
285
+ if (has(page)) {
286
+ return { kind: "redirect", to: path.slice(0, -1) };
287
+ }
288
+ return notFound(has, path, options);
289
+ }
290
+ if (has(path)) {
291
+ return { kind: "file", path, status: 200 };
292
+ }
293
+ if (has(`${path}.html`)) {
294
+ return { kind: "file", path: `${path}.html`, status: 200 };
295
+ }
296
+ if (has(`${path}/index.html`)) {
297
+ return { kind: "redirect", to: `${path}/` };
298
+ }
299
+ return notFound(has, path, options);
300
+ }
301
+
302
+ function notFound(
303
+ has: (path: string) => boolean,
304
+ path: string,
305
+ options: LookupOptions,
306
+ ): FileLookup {
307
+ if (!options.navigation) {
308
+ return { kind: "none" };
309
+ }
310
+ const entry = options.entry ?? DEFAULT_ENTRY;
311
+ if (options.spa === true && has(entry)) {
312
+ return { kind: "file", path: entry, status: 200 };
313
+ }
314
+ // The nearest 404.html: in the request's directory, then each one above it.
315
+ const segments = path.split("/").slice(0, -1);
316
+ for (let depth = segments.length; depth >= 0; depth -= 1) {
317
+ const candidate = [...segments.slice(0, depth), "404.html"].join("/");
318
+ if (has(candidate)) {
319
+ return { kind: "file", path: candidate, status: 404 };
320
+ }
321
+ }
322
+ return { kind: "none" };
323
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * The media type a file of a set is served with (P081): Porthole's own table, by the path's
3
+ * extension, never the uploader's word and never sniffed. A file whose extension isn't here is
4
+ * `application/octet-stream`, served as a download. Pure: any runtime.
5
+ */
6
+
7
+ /** How a type is served: a page (in the shell), a script (it may run as a worker), or a file. */
8
+ export type FileRole = "page" | "script" | "file";
9
+
10
+ export interface FileType {
11
+ /** The `content-type` header. */
12
+ readonly type: string;
13
+ readonly role: FileRole;
14
+ }
15
+
16
+ const UTF8 = "; charset=utf-8";
17
+
18
+ /** Extension (lowercase, no dot) to media type. Standard web types only. */
19
+ const TABLE: Readonly<Record<string, string>> = {
20
+ html: `text/html${UTF8}`,
21
+ htm: `text/html${UTF8}`,
22
+ css: `text/css${UTF8}`,
23
+ js: `text/javascript${UTF8}`,
24
+ mjs: `text/javascript${UTF8}`,
25
+ cjs: `text/javascript${UTF8}`,
26
+ json: `application/json${UTF8}`,
27
+ map: `application/json${UTF8}`,
28
+ webmanifest: `application/manifest+json${UTF8}`,
29
+ txt: `text/plain${UTF8}`,
30
+ md: `text/markdown${UTF8}`,
31
+ markdown: `text/markdown${UTF8}`,
32
+ csv: `text/csv${UTF8}`,
33
+ tsv: `text/tab-separated-values${UTF8}`,
34
+ xml: `application/xml${UTF8}`,
35
+ vtt: `text/vtt${UTF8}`,
36
+ svg: "image/svg+xml",
37
+ png: "image/png",
38
+ jpg: "image/jpeg",
39
+ jpeg: "image/jpeg",
40
+ gif: "image/gif",
41
+ webp: "image/webp",
42
+ avif: "image/avif",
43
+ ico: "image/x-icon",
44
+ bmp: "image/bmp",
45
+ woff: "font/woff",
46
+ woff2: "font/woff2",
47
+ ttf: "font/ttf",
48
+ otf: "font/otf",
49
+ mp3: "audio/mpeg",
50
+ wav: "audio/wav",
51
+ ogg: "audio/ogg",
52
+ oga: "audio/ogg",
53
+ opus: "audio/ogg",
54
+ m4a: "audio/mp4",
55
+ flac: "audio/flac",
56
+ aac: "audio/aac",
57
+ mp4: "video/mp4",
58
+ m4v: "video/mp4",
59
+ webm: "video/webm",
60
+ ogv: "video/ogg",
61
+ wasm: "application/wasm",
62
+ pdf: "application/pdf",
63
+ glb: "model/gltf-binary",
64
+ gltf: `model/gltf+json${UTF8}`,
65
+ zip: "application/zip",
66
+ };
67
+
68
+ /** What a file whose extension isn't in the table is served as: a download. */
69
+ export const UNKNOWN_TYPE = "application/octet-stream";
70
+
71
+ /** The extension of a path's last segment, lowercase, without the dot ("" for none). */
72
+ export function extensionOf(path: string): string {
73
+ const last = path.slice(path.lastIndexOf("/") + 1);
74
+ const dot = last.lastIndexOf(".");
75
+ return dot <= 0 ? "" : last.slice(dot + 1).toLowerCase();
76
+ }
77
+
78
+ /** The type a path is served with, and how. */
79
+ export function fileTypeOf(path: string): FileType {
80
+ const extension = extensionOf(path);
81
+ const type = Object.hasOwn(TABLE, extension) ? TABLE[extension] : undefined;
82
+ if (type === undefined) {
83
+ return { type: UNKNOWN_TYPE, role: "file" };
84
+ }
85
+ const role: FileRole =
86
+ extension === "html" || extension === "htm"
87
+ ? "page"
88
+ : type.startsWith("text/javascript")
89
+ ? "script"
90
+ : "file";
91
+ return { type, role };
92
+ }
93
+
94
+ /** Whether Porthole's table names the path's extension (else it is served as a download). */
95
+ export const knownType = (path: string): boolean => fileTypeOf(path).type !== UNKNOWN_TYPE;
96
+
97
+ /** Whether a path names a page: an `.html` file. */
98
+ export const isPagePath = (path: string): boolean => fileTypeOf(path).role === "page";
99
+
100
+ /** Every extension the table knows, for the manual and tests. */
101
+ export const KNOWN_EXTENSIONS: readonly string[] = Object.keys(TABLE);
@@ -14,6 +14,7 @@ import {
14
14
  librarySources,
15
15
  type EgressKind,
16
16
  } from "../compile/policy.ts";
17
+ import { fileLimits, servesFiles } from "../files/paths.ts";
17
18
  import { VENDORED_LIBRARIES, libraryPath } from "../libraries/libraries.ts";
18
19
  import { shellPlan } from "../shell/plan.ts";
19
20
  import { themeDefault } from "../theme/variables.ts";
@@ -108,6 +109,23 @@ const sourcesFor = (config: PortholeConfig, kind: EgressKind): string[] => [
108
109
  /** Whether Porthole's own libraries load in the frame (`egress.libraries`, served, P079). */
109
110
  const servesLibraries = (config: PortholeConfig): boolean => librarySources(config).length > 0;
110
111
 
112
+ /** The manual's lines on a page's own files (P081-P084), where it may have them. */
113
+ function files(config: PortholeConfig): string | null {
114
+ if (!servesFiles(config)) {
115
+ return null;
116
+ }
117
+ const limits = fileLimits(config.limits);
118
+ const downloads = config.capabilities.downloadFile !== undefined;
119
+ return lines(
120
+ "Files: a page may come with files of its own (stylesheets, scripts and modules, images, fonts, data, workers, other pages), published beside it, with index.html the page it opens at.",
121
+ '- Name them by relative path (./style.css, assets/app.js, data.json), never with a leading / or a full address: a page loads only its own version\'s files. fetch("./data.json") works; a module\'s imports and a worker\'s script resolve from the module (new Worker(new URL("./worker.js", import.meta.url))).',
122
+ `- A link to another of your pages (about.html, or about; docs/ for docs/index.html) opens it in place. A link to any other file doesn't open: show an image with <img>${downloads ? ", offer a file with downloadFile" : ""}. A missing path shows your 404.html, if you publish one.`,
123
+ "- Paths are case-sensitive, relative, with no .., //, \\, %, ? or #. Each file is served as its extension says (.html a page, .js and .mjs scripts, .css, .json, .txt, .svg, .png, .woff2, .mp4, …), never as what it holds; an extension the server doesn't know is a download.",
124
+ '- A build tool\'s output works when it writes relative paths (Vite: base: "./"). No service workers.',
125
+ `- At most ${limits.maxFiles.toLocaleString("en-US")} files, ${sizeWords(limits.maxFileBytes)} each (a page under ${sizeWords(config.limits.maxBytes)}) and ${sizeWords(limits.maxVersionBytes)} in all.`,
126
+ );
127
+ }
128
+
111
129
  /** What content may load, in prose, from the same origins the CSP lists. */
112
130
  function network(config: PortholeConfig): string {
113
131
  const kinds: EgressKind[] = ["script", "style", "font", "img", "media", "connect"];
@@ -242,6 +260,8 @@ function widget(c: Context): string {
242
260
  "The sandbox:",
243
261
  ...stated.filter((limit) => limit.topic === "sandbox").map((limit) => `- ${limit.text}`),
244
262
  `Keep it under ${sizeWords(limits.maxBytes)}.`,
263
+ servesFiles(config) ? "" : null,
264
+ files(config),
245
265
  loadsScripts(config)
246
266
  ? "\nLibraries: pin an exact version at least two weeks old (chart.js@4.4.1 in its URL), never @latest or a range, so the code can't be swapped under you and draws the same every time."
247
267
  : null,
@@ -8,6 +8,7 @@ import { annotateMode, checkMarks, parseReport } from "../annotate/validate.ts";
8
8
  import { createBridge, onceConsent, type BridgeEvent } from "../bridge/bridge.ts";
9
9
  import type { HostFunctionBridge } from "../bridge/types.ts";
10
10
  import { compile } from "../compile/compile.ts";
11
+ import { servesFiles } from "../files/paths.ts";
11
12
  import { declaredCapabilities, effectiveGates } from "../compile/policy.ts";
12
13
  import { isRefused } from "../bridge/refusal.ts";
13
14
  import { capabilitySpec } from "../config/capabilities.ts";
@@ -38,6 +39,8 @@ import type {
38
39
  /** How long a display may take to load before its outcome is a timeout, by default. */
39
40
  const DEFAULT_LOAD_TIMEOUT_MS = 15_000;
40
41
 
42
+ /** How long a set's page said its next load is another of its pages (P084), ms. */
43
+ const PAGE_OF_SET_MS = 10_000;
41
44
  /** How many times a display is started again after its content navigated its frame away. */
42
45
  const MAX_RESTARTS = 3;
43
46
 
@@ -121,6 +124,8 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
121
124
  let connection: C | null = null;
122
125
  let destroyed = false;
123
126
  let restarts = 0;
127
+ // Until when the frame's next load is another page of its own set, as its content said (P084).
128
+ let pageOfSetUntil = 0;
124
129
  let generation = 0;
125
130
  // The viewer's answer for this display (P079): asked once, kept across its frames; or the
126
131
  // host's refusal of them all (P080).
@@ -320,6 +325,7 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
320
325
 
321
326
  const stop = () => {
322
327
  handshaken = false;
328
+ pageOfSetUntil = 0;
323
329
  abort?.abort();
324
330
  abort = null;
325
331
  outcomeWatch?.stop();
@@ -390,6 +396,14 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
390
396
  hostInfo,
391
397
  hostContext,
392
398
  emit: (event) => {
399
+ if (event.type === "navigating") {
400
+ // Only a display whose pages may come with files (P084), for the next load only, and
401
+ // only soon: content can't bank it to skip a restart later (P031).
402
+ if (servesFiles(config)) {
403
+ pageOfSetUntil = Date.now() + PAGE_OF_SET_MS;
404
+ }
405
+ return;
406
+ }
393
407
  if (event.type === "initialized") {
394
408
  watch.initialized();
395
409
  if (!handshaken) {
@@ -406,6 +420,13 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
406
420
  (opened as unknown as Record<string, (...each: unknown[]) => unknown>)[name]?.(...args);
407
421
  }
408
422
  created.onNavigated(() => {
423
+ // Another page of the content's own set (P084): the same content, still connected (the
424
+ // new page's shell says hello again on the same transport). Not a restart.
425
+ const ofSet = pageOfSetUntil > Date.now();
426
+ pageOfSetUntil = 0;
427
+ if (ofSet) {
428
+ return;
429
+ }
409
430
  emit("navigated", undefined);
410
431
  if (restarts < MAX_RESTARTS) {
411
432
  restarts += 1;
package/src/index.ts CHANGED
@@ -67,6 +67,30 @@ export {
67
67
  type VendoredLibrary,
68
68
  } from "./libraries/libraries.ts";
69
69
 
70
+ // A version made of files (P081): the rules its paths follow, its limits and its types.
71
+ export {
72
+ checkFileSet,
73
+ DEFAULT_ENTRY,
74
+ DEFAULT_MAX_FILE_BYTES,
75
+ DEFAULT_MAX_FILES,
76
+ DEFAULT_MAX_VERSION_BYTES,
77
+ fileLimits,
78
+ filePathProblem,
79
+ lookupFile,
80
+ requestFilePath,
81
+ servesFiles,
82
+ type FileLimits,
83
+ type FileLookup,
84
+ type FileSetProblem,
85
+ } from "./files/paths.ts";
86
+ export {
87
+ fileTypeOf,
88
+ KNOWN_EXTENSIONS,
89
+ UNKNOWN_TYPE,
90
+ type FileRole,
91
+ type FileType,
92
+ } from "./files/types.ts";
93
+
70
94
  // The compiler.
71
95
  export { compile, type CompiledConfig } from "./compile/compile.ts";
72
96
  export {
@@ -77,6 +101,9 @@ export {
77
101
  egressOrigins,
78
102
  embedderCsp,
79
103
  embedderFrameSourcesOf,
104
+ FILE_SET_DIRECTIVES,
105
+ fileSetCspDirectives,
106
+ INERT_FILE_CSP,
80
107
  type CspDirective,
81
108
  type EgressKind,
82
109
  } from "./compile/policy.ts";
@@ -122,6 +149,7 @@ export {
122
149
  MCP_APPS_METHODS,
123
150
  MCP_APPS_PROTOCOL_VERSION,
124
151
  MCP_APPS_STYLE_VARIABLES,
152
+ NAVIGATING_METHOD,
125
153
  NAVIGATION_BLOCKED_METHOD,
126
154
  PORTHOLE_STYLES,
127
155
  STALE_META,
@@ -166,8 +194,12 @@ export {
166
194
  export { defineDisplays, type DisplayKind, type Displays } from "./displays/displays.ts";
167
195
  // The agent's side: what content can be told without running it, and its tools (P073).
168
196
  export { fragmentOf, lintContent, type Finding, type LintRule } from "./check/lint.ts";
197
+ // A page that comes with files (P081): its lint, without running it.
198
+ export { lintFiles, type FileContents, type FileFinding } from "./check/files.ts";
169
199
  export {
170
200
  admitContent,
201
+ admitFiles,
202
+ type AdmitFilesResult,
171
203
  answerGuide,
172
204
  checkTool,
173
205
  guideChanges,
@@ -40,7 +40,9 @@ export type AdapterEvent =
40
40
  /** The view finished its handshake; content may be sent. */
41
41
  | { readonly type: "initialized" }
42
42
  /** The view asked to be closed. */
43
- | { readonly type: "teardown-requested" };
43
+ | { readonly type: "teardown-requested" }
44
+ /** A page that came with files is opening another page of its set in the frame (P084). */
45
+ | { readonly type: "navigating" };
44
46
 
45
47
  /** What the framework drives on every adapter. Adapters add their protocol's own operations. */
46
48
  export interface AdapterConnection {
@@ -140,6 +140,13 @@ export const STALE_META = "porthole/stale";
140
140
  */
141
141
  export const NAVIGATION_BLOCKED_METHOD = "porthole/navigation-blocked";
142
142
 
143
+ /**
144
+ * Porthole's own notification from the shell (P084): a page that came with files is opening
145
+ * another page of its set, `{ url }`, in the frame. The host takes the frame's next load for that
146
+ * page rather than for content that left (P031). The content's word: it only spares a restart.
147
+ */
148
+ export const NAVIGATING_METHOD = "porthole/navigating";
149
+
143
150
  /** The logger name the shell's error reports (`notifications/message`, level `error`) carry. */
144
151
  export const SHELL_LOGGER = "porthole";
145
152
 
@@ -11,6 +11,7 @@ import {
11
11
  import { reasonFor, type RefusalReason } from "../bridge/refusal.ts";
12
12
  import {
13
13
  COPY_TEXT_METHOD,
14
+ NAVIGATING_METHOD,
14
15
  NAVIGATION_BLOCKED_METHOD,
15
16
  MCP_APPS_METHODS as M,
16
17
  MCP_APPS_PROTOCOL_VERSION,
@@ -249,6 +250,10 @@ export const shellAdapter: ProtocolAdapter<ShellConnection> = {
249
250
  // The shell stopped a navigation (P080): an error report, with its address.
250
251
  void bridge.call("reportError", { navigationBlocked: params.url });
251
252
  return;
253
+ case NAVIGATING_METHOD:
254
+ // Another page of the set opens in the frame (P084): its next load is that page.
255
+ session.emit({ type: "navigating" });
256
+ return;
252
257
  case M.requestTeardown:
253
258
  session.emit({ type: "teardown-requested" });
254
259
  return;