@mostra/runtime 0.0.0-stage → 0.2.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 (115) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +39 -2
  3. package/dist/bin.d.ts +1 -0
  4. package/dist/bin.js +236 -0
  5. package/dist/bin.js.map +1 -0
  6. package/dist/builder/child/main.d.ts +1 -0
  7. package/dist/builder/child/main.js +1408 -0
  8. package/dist/builder/child/main.js.map +1 -0
  9. package/dist/child-xrHmytks.js +49 -0
  10. package/dist/child-xrHmytks.js.map +1 -0
  11. package/dist/deps/child/install.d.ts +1 -0
  12. package/dist/deps/child/install.js +33 -0
  13. package/dist/deps/child/install.js.map +1 -0
  14. package/dist/index.d.ts +221 -0
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +3 -0
  17. package/dist/instance-CzBkUyHu.js +15920 -0
  18. package/dist/instance-CzBkUyHu.js.map +1 -0
  19. package/dist/types-NjNy7gXX.js +57 -0
  20. package/dist/types-NjNy7gXX.js.map +1 -0
  21. package/package.json +87 -3
  22. package/src/actions/index.ts +622 -0
  23. package/src/addressing/index.ts +281 -0
  24. package/src/bin.ts +240 -0
  25. package/src/builder/child/dev.ts +383 -0
  26. package/src/builder/child/fields.ts +363 -0
  27. package/src/builder/child/main.ts +47 -0
  28. package/src/builder/child/plugins.ts +195 -0
  29. package/src/builder/child/scan.ts +459 -0
  30. package/src/builder/child/spa.ts +348 -0
  31. package/src/builder/coverage.ts +72 -0
  32. package/src/builder/index.ts +406 -0
  33. package/src/builder/types.ts +180 -0
  34. package/src/deps/child/install.ts +30 -0
  35. package/src/deps/index.ts +918 -0
  36. package/src/deps/installer.ts +321 -0
  37. package/src/deps/lock.ts +82 -0
  38. package/src/deps/scan.ts +266 -0
  39. package/src/deps/specifier.ts +64 -0
  40. package/src/deps/warm.ts +57 -0
  41. package/src/dev/index.ts +518 -0
  42. package/src/faults.ts +65 -0
  43. package/src/gate.ts +55 -0
  44. package/src/gateway/actions.ts +268 -0
  45. package/src/gateway/browser.ts +650 -0
  46. package/src/gateway/capabilities.ts +760 -0
  47. package/src/gateway/controls.ts +91 -0
  48. package/src/gateway/dev.ts +119 -0
  49. package/src/gateway/http.ts +229 -0
  50. package/src/gateway/identity.ts +101 -0
  51. package/src/gateway/index.ts +1299 -0
  52. package/src/gateway/integrity.ts +117 -0
  53. package/src/gateway/listener.ts +217 -0
  54. package/src/gateway/routes.ts +197 -0
  55. package/src/gateway/serve.ts +138 -0
  56. package/src/gc/index.ts +451 -0
  57. package/src/home/acquire.ts +276 -0
  58. package/src/home/index.ts +16 -0
  59. package/src/home/paths.ts +192 -0
  60. package/src/home/platform.ts +34 -0
  61. package/src/home/record.ts +76 -0
  62. package/src/home/settings.ts +113 -0
  63. package/src/index.ts +30 -0
  64. package/src/instance/index.ts +979 -0
  65. package/src/interaction/ephemeral.ts +300 -0
  66. package/src/interaction/events.ts +355 -0
  67. package/src/interaction/fields.ts +392 -0
  68. package/src/interaction/index.ts +1013 -0
  69. package/src/interaction/outbox.ts +493 -0
  70. package/src/interaction/policy.ts +26 -0
  71. package/src/interaction/results.ts +341 -0
  72. package/src/interaction/runs.ts +313 -0
  73. package/src/interaction/signals.ts +120 -0
  74. package/src/interaction/submissions.ts +585 -0
  75. package/src/interaction/subscriptions.ts +258 -0
  76. package/src/interaction/viewers.ts +187 -0
  77. package/src/interaction/wait.ts +201 -0
  78. package/src/ledger/index.ts +442 -0
  79. package/src/ledger/migrations.ts +596 -0
  80. package/src/ledger/requests.ts +105 -0
  81. package/src/ledger/types.ts +28 -0
  82. package/src/live/index.ts +573 -0
  83. package/src/log.ts +316 -0
  84. package/src/processes/child.ts +67 -0
  85. package/src/processes/environment.ts +64 -0
  86. package/src/processes/identity.ts +191 -0
  87. package/src/processes/index.ts +19 -0
  88. package/src/processes/manager.ts +543 -0
  89. package/src/protocol-server/client.ts +94 -0
  90. package/src/protocol-server/index.ts +91 -0
  91. package/src/protocol-server/server.ts +518 -0
  92. package/src/protocol-server/streams.ts +81 -0
  93. package/src/publish/checks.ts +92 -0
  94. package/src/publish/digest.ts +87 -0
  95. package/src/publish/index.ts +23 -0
  96. package/src/publish/manifest.ts +409 -0
  97. package/src/publish/methods.ts +96 -0
  98. package/src/publish/publisher.ts +913 -0
  99. package/src/publish/source.ts +272 -0
  100. package/src/publish/tar.ts +110 -0
  101. package/src/registry/index.ts +481 -0
  102. package/src/registry/store.ts +136 -0
  103. package/src/secrets/index.ts +223 -0
  104. package/src/service/idle.ts +64 -0
  105. package/src/service/index.ts +3 -0
  106. package/src/service/unit.ts +250 -0
  107. package/src/verify/fields.ts +125 -0
  108. package/src/verify/index.ts +913 -0
  109. package/src/verify/regression.ts +157 -0
  110. package/src/verify/runner.ts +230 -0
  111. package/src/verify/sandbox.ts +407 -0
  112. package/src/verify/typecheck.ts +371 -0
  113. package/src/workers/index.ts +17 -0
  114. package/src/workers/launcher.ts +260 -0
  115. package/src/workers/pool.ts +708 -0
@@ -0,0 +1,363 @@
1
+ /**
2
+ * The field scan (D109): every field ID the artifact's own code can use, read statically from its
3
+ * scripts and MDX pages, for `registry.json`. Literal IDs of `useField` and `useChoice`, the form
4
+ * adapter's `useForm({ id })` and `window.storage` become entries; anything the scan can't follow
5
+ * (a computed ID, a hook passed around or re-exported) makes the coverage open, so a version never
6
+ * orphans a field by a guess. Parsing only; nothing runs.
7
+ */
8
+ import { readFile } from "node:fs/promises";
9
+ import { extname, join } from "node:path";
10
+ import { compile } from "@mdx-js/mdx";
11
+ import { parseSync } from "oxc-parser";
12
+ import remarkFrontmatter from "remark-frontmatter";
13
+ import remarkGfm from "remark-gfm";
14
+ import type { FieldCoverage, FieldEntry, FieldHook, FieldLocation } from "../coverage.ts";
15
+
16
+ interface Node {
17
+ readonly type: string;
18
+ readonly start: number;
19
+ readonly end: number;
20
+ readonly [key: string]: unknown;
21
+ }
22
+
23
+ /** The packages whose hooks name fields, and the hooks they export. */
24
+ const HOOKS: Readonly<Record<string, ReadonlySet<string>>> = {
25
+ "@mostra/react": new Set(["useField", "useChoice"]),
26
+ "@mostra/react/form": new Set(["useForm"]),
27
+ };
28
+
29
+ /** The global objects `storage` hangs off (D53). */
30
+ const GLOBALS = new Set(["window", "globalThis", "self"]);
31
+
32
+ /** `window.storage`'s methods. */
33
+ const STORAGE_METHODS = new Set(["get", "set", "delete", "list"]);
34
+
35
+ const SCRIPT_LANG: Readonly<Record<string, "ts" | "tsx" | "js" | "jsx">> = {
36
+ ".ts": "ts",
37
+ ".mts": "ts",
38
+ ".cts": "ts",
39
+ ".tsx": "tsx",
40
+ ".js": "js",
41
+ ".mjs": "js",
42
+ ".cjs": "js",
43
+ ".jsx": "jsx",
44
+ };
45
+
46
+ function lineColumn(text: string, offset: number): { line: number; column: number } {
47
+ const before = text.slice(0, offset);
48
+ return { line: before.split("\n").length, column: offset - before.lastIndexOf("\n") };
49
+ }
50
+
51
+ function each(node: Node, visit: (child: Node, key: string) => void): void {
52
+ for (const [key, value] of Object.entries(node)) {
53
+ if (Array.isArray(value)) {
54
+ for (const item of value)
55
+ if (item && typeof item === "object" && "type" in item) visit(item as Node, key);
56
+ } else if (value && typeof value === "object" && "type" in value) visit(value as Node, key);
57
+ }
58
+ }
59
+
60
+ /** TypeScript wrappers that compile away. */
61
+ const ERASED = new Set([
62
+ "TSAsExpression",
63
+ "TSSatisfiesExpression",
64
+ "TSNonNullExpression",
65
+ "TSTypeAssertion",
66
+ "ParenthesizedExpression",
67
+ ]);
68
+
69
+ function unwrap(node: Node | undefined): Node | undefined {
70
+ let current = node;
71
+ while (current !== undefined && ERASED.has(current.type))
72
+ current = current["expression"] as Node | undefined;
73
+ return current;
74
+ }
75
+
76
+ /** A string literal or template's parts: one part for a literal, holes between parts otherwise. */
77
+ function idParts(node: Node | undefined): string[] | undefined {
78
+ const target = unwrap(node);
79
+ if (target?.type === "Literal" && typeof target["value"] === "string") return [target["value"]];
80
+ if (target?.type === "TemplateLiteral") {
81
+ const parts = (target["quasis"] as Node[]).map(
82
+ (quasi) => (quasi["value"] as { cooked: string | null }).cooked,
83
+ );
84
+ if (parts.some((part) => part === null)) return undefined;
85
+ return parts as string[];
86
+ }
87
+ return undefined;
88
+ }
89
+
90
+ /**
91
+ * A literal object's literal string or boolean properties, as they stand after every property
92
+ * in order: a spread or a computed key may override anything before it, so what came before is
93
+ * forgotten (GPT review finding 12); a property the scan can't read is left out.
94
+ */
95
+ function literalOptions(node: Node | undefined): Record<string, string | boolean> | undefined {
96
+ const target = unwrap(node);
97
+ if (target?.type !== "ObjectExpression") return undefined;
98
+ let out: Record<string, string | boolean> = {};
99
+ for (const property of target["properties"] as Node[]) {
100
+ if (property.type !== "Property" || property["computed"]) {
101
+ out = {};
102
+ continue;
103
+ }
104
+ const key = property["key"] as Node;
105
+ const name = key.type === "Identifier" ? key["name"] : key["value"];
106
+ const value = unwrap(property["value"] as Node);
107
+ if (
108
+ typeof name === "string" &&
109
+ value?.type === "Literal" &&
110
+ (typeof value["value"] === "string" || typeof value["value"] === "boolean")
111
+ ) {
112
+ out[name] = value["value"];
113
+ }
114
+ }
115
+ return out;
116
+ }
117
+
118
+ /** The scan of one artifact. */
119
+ class FieldScan {
120
+ readonly entries: FieldEntry[] = [];
121
+ readonly openReasons: { reason: string; location?: FieldLocation }[] = [];
122
+
123
+ open(reason: string, location?: FieldLocation): void {
124
+ this.openReasons.push({ reason, ...(location ? { location } : {}) });
125
+ }
126
+
127
+ /** Scans one parsed module; `text` is what offsets refer to. */
128
+ module(file: string, text: string, program: Node): void {
129
+ const at = (node: Node): FieldLocation => ({ file, ...lineColumn(text, node.start) });
130
+ // Local names of the hooks, and namespaces of their packages.
131
+ const hooks = new Map<string, FieldHook>();
132
+ const namespaces = new Map<string, ReadonlySet<string>>();
133
+ for (const statement of program["body"] as Node[]) {
134
+ const source =
135
+ statement.type === "ImportDeclaration" ||
136
+ statement.type === "ExportNamedDeclaration" ||
137
+ statement.type === "ExportAllDeclaration"
138
+ ? ((statement["source"] as Node | null)?.["value"] as string | undefined)
139
+ : undefined;
140
+ const exported = source === undefined ? undefined : HOOKS[source];
141
+ if (!exported) continue;
142
+ if (statement.type !== "ImportDeclaration") {
143
+ // Re-exporting a hook hands it to code the scan can't follow.
144
+ this.open(`${file} re-exports from ${source}`, at(statement));
145
+ continue;
146
+ }
147
+ if (statement["importKind"] === "type") continue;
148
+ for (const specifier of statement["specifiers"] as Node[]) {
149
+ const local = (specifier["local"] as Node)["name"] as string;
150
+ if (specifier.type === "ImportNamespaceSpecifier") namespaces.set(local, exported);
151
+ else if (specifier.type === "ImportSpecifier" && specifier["importKind"] !== "type") {
152
+ const imported = specifier["imported"] as Node;
153
+ const name = (imported["name"] ?? imported["value"]) as string;
154
+ if (exported.has(name)) hooks.set(local, name as FieldHook);
155
+ }
156
+ }
157
+ }
158
+
159
+ const hookOf = (callee: Node | undefined): FieldHook | undefined => {
160
+ const target = unwrap(callee);
161
+ if (target?.type === "Identifier") return hooks.get(target["name"] as string);
162
+ if (target?.type === "MemberExpression" && !target["computed"]) {
163
+ const object = target["object"] as Node;
164
+ const property = (target["property"] as Node)["name"] as string;
165
+ const names =
166
+ object.type === "Identifier" ? namespaces.get(object["name"] as string) : undefined;
167
+ if (names?.has(property)) return property as FieldHook;
168
+ }
169
+ return undefined;
170
+ };
171
+
172
+ const callees = new Set<Node>();
173
+ const visit = (node: Node): void => {
174
+ if (node.type === "CallExpression") {
175
+ const callee = node["callee"] as Node;
176
+ const hook = hookOf(callee);
177
+ if (hook) {
178
+ callees.add(unwrap(callee) as Node);
179
+ this.call(hook, node["arguments"] as Node[], at(node));
180
+ }
181
+ // `window.storage.get(…)` and the bare `storage.get(…)` of Claude's artifacts (D53).
182
+ const target = unwrap(callee);
183
+ if (target?.type === "MemberExpression" && !target["computed"]) {
184
+ const object = unwrap(target["object"] as Node);
185
+ const method = (target["property"] as Node)["name"] as string;
186
+ const isStorage =
187
+ (object?.type === "MemberExpression" &&
188
+ !object["computed"] &&
189
+ (object["object"] as Node).type === "Identifier" &&
190
+ GLOBALS.has((object["object"] as Node)["name"] as string) &&
191
+ (object["property"] as Node)["name"] === "storage") ||
192
+ (object?.type === "Identifier" && object["name"] === "storage");
193
+ if (isStorage && STORAGE_METHODS.has(method)) this.storage(at(node));
194
+ }
195
+ }
196
+ // `const s = window.storage` hands storage on: every key is possible.
197
+ if (
198
+ node.type === "MemberExpression" &&
199
+ !node["computed"] &&
200
+ (node["object"] as Node).type === "Identifier" &&
201
+ GLOBALS.has((node["object"] as Node)["name"] as string) &&
202
+ (node["property"] as Node)["name"] === "storage"
203
+ ) {
204
+ this.storage(at(node));
205
+ }
206
+ each(node, (child) => visit(child));
207
+ };
208
+ visit(program);
209
+
210
+ // A hook referenced anywhere but as a callee is passed around: its IDs are unknowable.
211
+ const references = (node: Node, parentKey: string, parent: Node | undefined): void => {
212
+ if (
213
+ node.type === "Identifier" &&
214
+ parentKey !== "property" &&
215
+ parentKey !== "key" &&
216
+ parent?.type !== "ImportSpecifier" &&
217
+ parent?.type !== "ImportNamespaceSpecifier"
218
+ ) {
219
+ const name = node["name"] as string;
220
+ if (hooks.has(name) && !callees.has(node)) {
221
+ this.open(`${file} uses ${name} other than by calling it`, at(node));
222
+ }
223
+ const exported = namespaces.get(name);
224
+ if (exported) {
225
+ const member =
226
+ parent?.type === "MemberExpression" && parentKey === "object" && !parent["computed"]
227
+ ? ((parent["property"] as Node)["name"] as string)
228
+ : undefined;
229
+ const passedOn =
230
+ member === undefined || (exported.has(member) && !callees.has(parent as Node));
231
+ if (passedOn) this.open(`${file} uses ${name} other than by calling its hooks`, at(node));
232
+ }
233
+ }
234
+ each(node, (child, key) => references(child, key, node));
235
+ };
236
+ references(program, "", undefined);
237
+ }
238
+
239
+ storage(location: FieldLocation): void {
240
+ if (this.entries.some((entry) => entry.hook === "storage")) return;
241
+ // Personal keys are the viewer's fields under `storage.`; shared ones are artifact state.
242
+ this.entries.push(
243
+ { template: ["storage.", ""], hook: "storage", scope: "viewer", location },
244
+ { template: ["storage.", ""], hook: "storage", scope: "artifact", location },
245
+ );
246
+ }
247
+
248
+ call(hook: FieldHook, args: Node[], location: FieldLocation): void {
249
+ const first = args[0];
250
+ if (hook === "useForm") {
251
+ const options = unwrap(first);
252
+ // The id that stands: the last one, unless a spread or computed key after it may replace it.
253
+ let idProperty: Node | undefined;
254
+ if (options?.type === "ObjectExpression") {
255
+ for (const property of options["properties"] as Node[]) {
256
+ if (property.type !== "Property" || property["computed"]) idProperty = undefined;
257
+ else if (
258
+ ((property["key"] as Node)["name"] ?? (property["key"] as Node)["value"]) === "id"
259
+ ) {
260
+ idProperty = property;
261
+ }
262
+ }
263
+ }
264
+ const parts = idParts(idProperty?.["value"] as Node | undefined);
265
+ if (!parts) {
266
+ this.open("a useForm call without a literal id", location);
267
+ return;
268
+ }
269
+ // Every registered field is `<id>.<name>` (the form adapter).
270
+ const template = [...parts.slice(0, -1), `${parts.at(-1) as string}.`, ""];
271
+ this.entries.push({ template, hook, location });
272
+ return;
273
+ }
274
+ const parts = idParts(first);
275
+ if (!parts) {
276
+ this.open(`a ${hook} call whose ID isn't a string literal or template`, location);
277
+ return;
278
+ }
279
+ // A choice is the field `review.<set>.choice` (D65).
280
+ const wrap = (inner: string[]): string[] => {
281
+ if (hook !== "useChoice") return inner;
282
+ const out = [...inner];
283
+ out[0] = `review.${out[0] as string}`;
284
+ out[out.length - 1] = `${out.at(-1) as string}.choice`;
285
+ return out;
286
+ };
287
+ const wrapped = wrap(parts);
288
+ const singleLiteral = parts.length === 1;
289
+ const options = hook === "useField" ? literalOptions(args[2]) : undefined;
290
+ // Only `"artifact"` takes a field out of drafts; a scope the scan can't read may be the
291
+ // viewer's, which keeps the field covered.
292
+ const scopeOption = options?.["scope"];
293
+ const scope = scopeOption === "artifact" || scopeOption === "viewer" ? scopeOption : undefined;
294
+ this.entries.push({
295
+ ...(singleLiteral ? { id: wrapped.join("") } : { template: wrapped }),
296
+ hook,
297
+ ...(scope !== undefined ? { scope } : {}),
298
+ ...(typeof options?.["label"] === "string" ? { label: options["label"] } : {}),
299
+ ...(typeof options?.["required"] === "boolean" ? { required: options["required"] } : {}),
300
+ ...(typeof options?.["sensitive"] === "boolean" ? { sensitive: options["sensitive"] } : {}),
301
+ location,
302
+ });
303
+ }
304
+
305
+ result(): FieldCoverage {
306
+ // A version that declares no field through the hooks may still take answers through the
307
+ // browser protocol itself; the scan can't see those, so nothing is orphaned by a guess.
308
+ if (this.entries.length === 0 && this.openReasons.length === 0) {
309
+ this.open("the artifact declares no fields through @mostra/react");
310
+ }
311
+ return {
312
+ open: this.openReasons.length > 0,
313
+ openReasons: this.openReasons,
314
+ entries: this.entries,
315
+ };
316
+ }
317
+ }
318
+
319
+ /** Mentions that make a file worth parsing for fields. */
320
+ const MENTIONS = /@mostra\/react|storage/;
321
+
322
+ /** A file that speaks the browser protocol itself writes fields the scan can't follow. */
323
+ const RAW_PROTOCOL = /_mostra\/v\//;
324
+
325
+ /** Scans the artifact's scripts and MDX pages (`files` are paths inside `sourceDir`). */
326
+ export async function scanFields(
327
+ sourceDir: string,
328
+ files: readonly string[],
329
+ ): Promise<FieldCoverage> {
330
+ const scan = new FieldScan();
331
+ for (const file of [...files].sort()) {
332
+ const ext = extname(file);
333
+ const lang = SCRIPT_LANG[ext];
334
+ if (lang === undefined && ext !== ".mdx") continue;
335
+ const source = await readFile(join(sourceDir, file), "utf8");
336
+ if (RAW_PROTOCOL.test(source)) scan.open(`${file} calls the browser protocol directly`);
337
+ if (!MENTIONS.test(source)) continue;
338
+ let text = source;
339
+ let parseLang: "ts" | "tsx" | "js" | "jsx" = lang ?? "jsx";
340
+ if (ext === ".mdx") {
341
+ try {
342
+ const compiled = await compile(
343
+ { value: source, path: file },
344
+ { jsxImportSource: "react", remarkPlugins: [remarkFrontmatter, remarkGfm] },
345
+ );
346
+ text = String(compiled.value);
347
+ parseLang = "js";
348
+ } catch {
349
+ // The bundler reports the MDX error; nothing here can be known about its fields.
350
+ scan.open(`${file} doesn't compile`);
351
+ continue;
352
+ }
353
+ }
354
+ const parsed = parseSync(file, text, { lang: parseLang });
355
+ if (parsed.errors.length > 0) {
356
+ scan.open(`${file} doesn't parse`);
357
+ continue;
358
+ }
359
+ // MDX offsets refer to the compiled text, so its locations name only the file.
360
+ scan.module(file, text, parsed.program as unknown as Node);
361
+ }
362
+ return scan.result();
363
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * The builder child's entry (`mostra-runtime`'s `dist/builder/child/main.js`, ARCHITECTURE §1): the
3
+ * only process that loads Vite. The supervisor starts one per build through the process manager,
4
+ * sends `builder/build` over IPC, and stops it after the answer; for `mostra dev` it starts one per
5
+ * session and sends `builder/dev`, and the child serves until it is stopped (D140 item 12). It
6
+ * exits with its supervisor (`connectToSupervisor`) and never runs artifact code: bundling reads
7
+ * modules, it doesn't run them.
8
+ */
9
+ import { connectToSupervisor } from "../../processes/index.ts";
10
+ import {
11
+ BUILD_METHOD,
12
+ type BuildRequest,
13
+ DEV_CHANGED_METHOD,
14
+ DEV_METHOD,
15
+ DEV_RELOAD_METHOD,
16
+ type DevChange,
17
+ type DevRequest,
18
+ } from "../types.ts";
19
+ import { type DevServer, startDev } from "./dev.ts";
20
+ import { buildSpa } from "./spa.ts";
21
+
22
+ let dev: DevServer | undefined;
23
+
24
+ const supervisor = connectToSupervisor({
25
+ onRequest: async (method, params) => {
26
+ if (method === BUILD_METHOD) {
27
+ const request = params as BuildRequest;
28
+ // A test's hung builder (issue #18): it never answers.
29
+ if (request.hang === true) return new Promise<never>(() => {});
30
+ return buildSpa(request);
31
+ }
32
+ if (method === DEV_METHOD) {
33
+ if (dev) throw new Error("This builder child already serves a dev session.");
34
+ dev = await startDev(params as DevRequest, supervisor);
35
+ return dev.ready;
36
+ }
37
+ if (method === DEV_CHANGED_METHOD) {
38
+ await dev?.changed((params as { changes: DevChange[] }).changes);
39
+ return {};
40
+ }
41
+ if (method === DEV_RELOAD_METHOD) {
42
+ dev?.reload();
43
+ return {};
44
+ }
45
+ throw new Error(`The builder doesn't serve ${method}.`);
46
+ },
47
+ });
@@ -0,0 +1,195 @@
1
+ /**
2
+ * The Vite plugins of the SPA build (D19 seams 1 and 2): MDX compilation, and the `"use server"`
3
+ * client-stub transform, which replaces each server module in the client build with
4
+ * `createServerReference` stubs so no server code reaches the browser (D54).
5
+ */
6
+
7
+ import { existsSync, realpathSync } from "node:fs";
8
+ import { extname, isAbsolute, relative } from "node:path";
9
+ import { compile } from "@mdx-js/mdx";
10
+ import remarkFrontmatter from "remark-frontmatter";
11
+ import remarkGfm from "remark-gfm";
12
+ import type { Plugin } from "vite";
13
+ import type { ServerFunctionEntry } from "../types.ts";
14
+ import { SCRIPT, startsWithUseServer } from "./scan.ts";
15
+
16
+ /** Compiles `.mdx` files to JavaScript with React's JSX runtime, frontmatter removed (MDX 3). */
17
+ export function mdxPlugin(): Plugin {
18
+ return {
19
+ name: "mostra:mdx",
20
+ enforce: "pre",
21
+ async transform(code, id) {
22
+ const file = id.split("?")[0] ?? id;
23
+ if (!file.endsWith(".mdx")) return null;
24
+ const compiled = await compile(
25
+ { value: code, path: file },
26
+ {
27
+ jsxImportSource: "react",
28
+ remarkPlugins: [remarkFrontmatter, remarkGfm],
29
+ development: false,
30
+ },
31
+ );
32
+ return { code: String(compiled.value), map: null, moduleType: "js" };
33
+ },
34
+ };
35
+ }
36
+
37
+ /** Where packages outside the artifact use the client runtime's field hooks (D109). */
38
+ export interface FieldHookUse {
39
+ /** The importing module's path, relative to the build's `node_modules` when it is a package. */
40
+ readonly importer: string;
41
+ }
42
+
43
+ /**
44
+ * Records every module outside the artifact that imports `@mostra/react` or `@mostra/react/form`
45
+ * (D109): such a package may name fields the artifact's scan can't see, so the version's coverage
46
+ * is open. `@mostra/react` itself and Mostra's generated files don't count. It resolves nothing.
47
+ */
48
+ export function fieldHookUsePlugin(
49
+ roots: {
50
+ readonly sourceDir: string;
51
+ readonly generatedDir: string;
52
+ readonly runtimeDir?: string;
53
+ },
54
+ uses: FieldHookUse[],
55
+ ): Plugin {
56
+ const inside = (file: string, dir: string | undefined): boolean =>
57
+ dir !== undefined && (file === dir || file.startsWith(`${dir}/`));
58
+ return {
59
+ name: "mostra:field-hook-use",
60
+ enforce: "pre",
61
+ resolveId(source, importer) {
62
+ if (source !== "@mostra/react" && source !== "@mostra/react/form") return null;
63
+ if (importer === undefined || importer.startsWith("\0")) return null;
64
+ const file = existsSync(importer) ? realpathSync(importer) : importer;
65
+ if (
66
+ inside(file, roots.sourceDir) ||
67
+ inside(file, roots.generatedDir) ||
68
+ inside(file, roots.runtimeDir)
69
+ )
70
+ return null;
71
+ if (!uses.some((use) => use.importer === file)) uses.push({ importer: file });
72
+ return null;
73
+ },
74
+ };
75
+ }
76
+
77
+ /** The client stub of one `"use server"` module. */
78
+ export function serverStub(entries: readonly ServerFunctionEntry[]): string {
79
+ const lines = ['import { createServerReference } from "@mostra/react";'];
80
+ // `export { local as "name" }` covers default and string export names alike (ES2022).
81
+ entries.forEach((entry, index) => {
82
+ lines.push(
83
+ `const reference${index} = createServerReference(${JSON.stringify(entry.id)});`,
84
+ `export { reference${index} as ${JSON.stringify(entry.export)} };`,
85
+ );
86
+ });
87
+ return `${lines.join("\n")}\n`;
88
+ }
89
+
90
+ /** The ID prefix of the virtual stub modules that stand in for server modules in the client. */
91
+ const STUB_PREFIX = "\0mostra-server-reference:";
92
+
93
+ /**
94
+ * Replaces `"use server"` modules with their client stubs. `modules` maps each module's absolute
95
+ * path to its exports, from the scan.
96
+ */
97
+ export function serverClientStubPlugin(
98
+ modules: ReadonlyMap<string, readonly ServerFunctionEntry[]>,
99
+ sourceDir: string,
100
+ ): Plugin {
101
+ return {
102
+ name: "mostra:use-server-client",
103
+ enforce: "pre",
104
+ // Server modules resolve to a virtual stub module whose ID ends in `.mjs`: the bundler reads a
105
+ // `.cts` or `.cjs` file name as CommonJS, and the stub is an ES module.
106
+ async resolveId(source, importer, options) {
107
+ if (source.startsWith(STUB_PREFIX)) return source;
108
+ const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });
109
+ const file = resolved?.id.split("?")[0];
110
+ return file !== undefined && modules.has(file) ? `${STUB_PREFIX}${file}.mjs` : null;
111
+ },
112
+ load(id) {
113
+ if (!id.startsWith(STUB_PREFIX)) return null;
114
+ const entries = modules.get(id.slice(STUB_PREFIX.length, -".mjs".length));
115
+ return entries === undefined ? null : { code: serverStub(entries), moduleType: "js" };
116
+ },
117
+ // Fails closed (D54): a module of the artifact that reaches the client build with the
118
+ // directive, but without a stub, would ship its server code to every viewer.
119
+ transform(code, id) {
120
+ const file = id.split("?")[0] ?? id;
121
+ if (!file.startsWith(`${sourceDir}/`) || modules.has(file)) return null;
122
+ if (!SCRIPT.has(extname(file))) return null;
123
+ if (startsWithUseServer(file, code) !== true) return null;
124
+ return this.error(
125
+ `${relative(sourceDir, file)} starts with "use server" but has no client stub, so its server code would reach the browser; give it one of the extensions ${[...SCRIPT].join(", ")}.`,
126
+ );
127
+ },
128
+ };
129
+ }
130
+
131
+ /** Where an artifact's build may read from (VR-01: every input is covered by a digest). */
132
+ export interface BuildInputs {
133
+ /** The artifact's snapshot (`sourceDigest`). */
134
+ readonly sourceDir: string;
135
+ /** Mostra's generated build files (`buildConfigDigest`), whose imports are checked like the artifact's. */
136
+ readonly generatedDir: string;
137
+ /** Real directories holding the build's packages and their dependencies (`lockDigest`). */
138
+ readonly packageRoots: readonly string[];
139
+ }
140
+
141
+ /**
142
+ * Keeps a build's inputs inside what the version's digests cover (VR-01, DATA_MODEL §2). A relative
143
+ * or absolute import from an artifact file must resolve inside the artifact, and a package import
144
+ * from an artifact file or a generated file must resolve into the build's packages (the warm set
145
+ * and the artifact's lockfile). An import from inside a package must stay among those packages
146
+ * too: a package that imports a dependency it doesn't declare would otherwise find it in any
147
+ * `node_modules` above the home. Anything else (a file beside the artifact, a stray
148
+ * `node_modules` above the home) would bring bytes into the build that no digest covers, so a
149
+ * later change to them would go unnoticed.
150
+ */
151
+ export function confinePlugin(inputs: BuildInputs): Plugin {
152
+ const under = (file: string, dir: string): boolean => file.startsWith(`${dir}/`);
153
+ const ours = (file: string): boolean =>
154
+ under(file, inputs.sourceDir) || under(file, inputs.generatedDir);
155
+ const packaged = (file: string): boolean => inputs.packageRoots.some((root) => under(file, root));
156
+ const real = (file: string): string => {
157
+ try {
158
+ return realpathSync.native(file);
159
+ } catch {
160
+ return file;
161
+ }
162
+ };
163
+ return {
164
+ name: "mostra:confine",
165
+ enforce: "pre",
166
+ async resolveId(source, importer, options) {
167
+ const from = importer?.split("?")[0];
168
+ if (from === undefined || source.startsWith("\0")) return null;
169
+ const fromPackage = !ours(from);
170
+ if (fromPackage && !packaged(from)) return null;
171
+ const bare = !source.startsWith(".") && !source.startsWith("/");
172
+ const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });
173
+ if (!resolved || resolved.external) return resolved;
174
+ const id = resolved.id.split("?")[0] ?? resolved.id;
175
+ // Virtual modules, browser stubs for Node built-ins and public URLs (`/logo.svg` from
176
+ // `public/`) aren't files, so there is nothing outside to read.
177
+ if (id.startsWith("\0") || !isAbsolute(id) || !existsSync(id)) return resolved;
178
+ const file = real(id);
179
+ if (fromPackage) {
180
+ if (packaged(file)) return resolved;
181
+ return this.error(
182
+ `Could not resolve "${source}" from the package file ${from}: it isn't among the build's packages (the warm set and the artifact's lockfile), and a package can't take a dependency it doesn't declare from elsewhere.`,
183
+ );
184
+ }
185
+ if (ours(file)) return resolved;
186
+ if (bare && packaged(file)) return resolved;
187
+ const where = relative(inputs.sourceDir, from);
188
+ return this.error(
189
+ bare
190
+ ? `Could not resolve "${source}" from ${where}: it isn't in the warm set or the artifact's lockfile, and a version is built only from the artifact's own files and those packages; add it with \`mostra add\`.`
191
+ : `Could not resolve "${source}" from ${where}: it is outside the artifact, and a version is built only from the artifact's own files.`,
192
+ );
193
+ },
194
+ };
195
+ }