@mostra/runtime 0.0.0-stage → 0.1.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 +39 -2
- package/dist/bin.d.ts +1 -0
- package/dist/bin.js +236 -0
- package/dist/bin.js.map +1 -0
- package/dist/builder/child/main.d.ts +1 -0
- package/dist/builder/child/main.js +1408 -0
- package/dist/builder/child/main.js.map +1 -0
- package/dist/child-xrHmytks.js +49 -0
- package/dist/child-xrHmytks.js.map +1 -0
- package/dist/deps/child/install.d.ts +1 -0
- package/dist/deps/child/install.js +33 -0
- package/dist/deps/child/install.js.map +1 -0
- package/dist/index.d.ts +221 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/instance-D7_UVdoN.js +15752 -0
- package/dist/instance-D7_UVdoN.js.map +1 -0
- package/dist/types-NjNy7gXX.js +57 -0
- package/dist/types-NjNy7gXX.js.map +1 -0
- package/package.json +87 -3
- package/src/actions/index.ts +622 -0
- package/src/addressing/index.ts +281 -0
- package/src/bin.ts +240 -0
- package/src/builder/child/dev.ts +383 -0
- package/src/builder/child/fields.ts +363 -0
- package/src/builder/child/main.ts +47 -0
- package/src/builder/child/plugins.ts +195 -0
- package/src/builder/child/scan.ts +459 -0
- package/src/builder/child/spa.ts +348 -0
- package/src/builder/coverage.ts +72 -0
- package/src/builder/index.ts +406 -0
- package/src/builder/types.ts +180 -0
- package/src/deps/child/install.ts +30 -0
- package/src/deps/index.ts +918 -0
- package/src/deps/installer.ts +321 -0
- package/src/deps/lock.ts +82 -0
- package/src/deps/scan.ts +266 -0
- package/src/deps/specifier.ts +64 -0
- package/src/deps/warm.ts +57 -0
- package/src/dev/index.ts +518 -0
- package/src/faults.ts +65 -0
- package/src/gate.ts +55 -0
- package/src/gateway/actions.ts +268 -0
- package/src/gateway/browser.ts +650 -0
- package/src/gateway/capabilities.ts +739 -0
- package/src/gateway/controls.ts +91 -0
- package/src/gateway/dev.ts +119 -0
- package/src/gateway/http.ts +229 -0
- package/src/gateway/index.ts +1209 -0
- package/src/gateway/integrity.ts +117 -0
- package/src/gateway/listener.ts +217 -0
- package/src/gateway/routes.ts +197 -0
- package/src/gateway/serve.ts +138 -0
- package/src/gc/index.ts +451 -0
- package/src/home/acquire.ts +276 -0
- package/src/home/index.ts +16 -0
- package/src/home/paths.ts +192 -0
- package/src/home/platform.ts +34 -0
- package/src/home/record.ts +76 -0
- package/src/home/settings.ts +113 -0
- package/src/index.ts +30 -0
- package/src/instance/index.ts +942 -0
- package/src/interaction/ephemeral.ts +300 -0
- package/src/interaction/events.ts +355 -0
- package/src/interaction/fields.ts +392 -0
- package/src/interaction/index.ts +1009 -0
- package/src/interaction/outbox.ts +493 -0
- package/src/interaction/policy.ts +26 -0
- package/src/interaction/results.ts +341 -0
- package/src/interaction/runs.ts +313 -0
- package/src/interaction/signals.ts +120 -0
- package/src/interaction/submissions.ts +585 -0
- package/src/interaction/subscriptions.ts +258 -0
- package/src/interaction/viewers.ts +173 -0
- package/src/interaction/wait.ts +201 -0
- package/src/ledger/index.ts +442 -0
- package/src/ledger/migrations.ts +583 -0
- package/src/ledger/requests.ts +105 -0
- package/src/ledger/types.ts +28 -0
- package/src/live/index.ts +573 -0
- package/src/log.ts +316 -0
- package/src/processes/child.ts +67 -0
- package/src/processes/environment.ts +64 -0
- package/src/processes/identity.ts +191 -0
- package/src/processes/index.ts +19 -0
- package/src/processes/manager.ts +543 -0
- package/src/protocol-server/client.ts +94 -0
- package/src/protocol-server/index.ts +91 -0
- package/src/protocol-server/server.ts +509 -0
- package/src/protocol-server/streams.ts +81 -0
- package/src/publish/checks.ts +92 -0
- package/src/publish/digest.ts +87 -0
- package/src/publish/index.ts +23 -0
- package/src/publish/manifest.ts +409 -0
- package/src/publish/methods.ts +96 -0
- package/src/publish/publisher.ts +913 -0
- package/src/publish/source.ts +272 -0
- package/src/publish/tar.ts +110 -0
- package/src/registry/index.ts +481 -0
- package/src/registry/store.ts +136 -0
- package/src/secrets/index.ts +223 -0
- package/src/service/idle.ts +64 -0
- package/src/service/index.ts +3 -0
- package/src/service/unit.ts +250 -0
- package/src/verify/fields.ts +125 -0
- package/src/verify/index.ts +913 -0
- package/src/verify/regression.ts +157 -0
- package/src/verify/runner.ts +230 -0
- package/src/verify/sandbox.ts +407 -0
- package/src/verify/typecheck.ts +371 -0
- package/src/workers/index.ts +17 -0
- package/src/workers/launcher.ts +260 -0
- package/src/workers/pool.ts +708 -0
|
@@ -0,0 +1,1408 @@
|
|
|
1
|
+
import { a as DEV_SECRET_HEADER, c as LIVE_DECLARATION, l as STAGING_FILES, o as DEV_SERVER_NOTIFICATION, s as DEV_UPDATE_NOTIFICATION } from "../../types-NjNy7gXX.js";
|
|
2
|
+
import { t as connectToSupervisor } from "../../child-xrHmytks.js";
|
|
3
|
+
import { existsSync, realpathSync } from "node:fs";
|
|
4
|
+
import { extname, isAbsolute, join, relative } from "node:path";
|
|
5
|
+
import { createDiagnostic } from "@mostra/protocol";
|
|
6
|
+
import { createHash, timingSafeEqual } from "node:crypto";
|
|
7
|
+
import { mkdir, readFile, readdir, realpath, rm, symlink, writeFile } from "node:fs/promises";
|
|
8
|
+
import { createServer } from "node:http";
|
|
9
|
+
import { stripVTControlCharacters } from "node:util";
|
|
10
|
+
import tailwind from "@tailwindcss/vite";
|
|
11
|
+
import react from "@vitejs/plugin-react";
|
|
12
|
+
import { parseSync } from "oxc-parser";
|
|
13
|
+
import { build, createServer as createServer$1 } from "vite";
|
|
14
|
+
import { compile } from "@mdx-js/mdx";
|
|
15
|
+
import remarkFrontmatter from "remark-frontmatter";
|
|
16
|
+
import remarkGfm from "remark-gfm";
|
|
17
|
+
//#region src/builder/child/fields.ts
|
|
18
|
+
/**
|
|
19
|
+
* The field scan (D109): every field ID the artifact's own code can use, read statically from its
|
|
20
|
+
* scripts and MDX pages, for `registry.json`. Literal IDs of `useField` and `useChoice`, the form
|
|
21
|
+
* adapter's `useForm({ id })` and `window.storage` become entries; anything the scan can't follow
|
|
22
|
+
* (a computed ID, a hook passed around or re-exported) makes the coverage open, so a version never
|
|
23
|
+
* orphans a field by a guess. Parsing only; nothing runs.
|
|
24
|
+
*/
|
|
25
|
+
/** The packages whose hooks name fields, and the hooks they export. */
|
|
26
|
+
const HOOKS = {
|
|
27
|
+
"@mostra/react": /* @__PURE__ */ new Set(["useField", "useChoice"]),
|
|
28
|
+
"@mostra/react/form": /* @__PURE__ */ new Set(["useForm"])
|
|
29
|
+
};
|
|
30
|
+
/** The global objects `storage` hangs off (D53). */
|
|
31
|
+
const GLOBALS = /* @__PURE__ */ new Set([
|
|
32
|
+
"window",
|
|
33
|
+
"globalThis",
|
|
34
|
+
"self"
|
|
35
|
+
]);
|
|
36
|
+
/** `window.storage`'s methods. */
|
|
37
|
+
const STORAGE_METHODS = /* @__PURE__ */ new Set([
|
|
38
|
+
"get",
|
|
39
|
+
"set",
|
|
40
|
+
"delete",
|
|
41
|
+
"list"
|
|
42
|
+
]);
|
|
43
|
+
const SCRIPT_LANG = {
|
|
44
|
+
".ts": "ts",
|
|
45
|
+
".mts": "ts",
|
|
46
|
+
".cts": "ts",
|
|
47
|
+
".tsx": "tsx",
|
|
48
|
+
".js": "js",
|
|
49
|
+
".mjs": "js",
|
|
50
|
+
".cjs": "js",
|
|
51
|
+
".jsx": "jsx"
|
|
52
|
+
};
|
|
53
|
+
function lineColumn$1(text, offset) {
|
|
54
|
+
const before = text.slice(0, offset);
|
|
55
|
+
return {
|
|
56
|
+
line: before.split("\n").length,
|
|
57
|
+
column: offset - before.lastIndexOf("\n")
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
function each(node, visit) {
|
|
61
|
+
for (const [key, value] of Object.entries(node)) if (Array.isArray(value)) {
|
|
62
|
+
for (const item of value) if (item && typeof item === "object" && "type" in item) visit(item, key);
|
|
63
|
+
} else if (value && typeof value === "object" && "type" in value) visit(value, key);
|
|
64
|
+
}
|
|
65
|
+
/** TypeScript wrappers that compile away. */
|
|
66
|
+
const ERASED = /* @__PURE__ */ new Set([
|
|
67
|
+
"TSAsExpression",
|
|
68
|
+
"TSSatisfiesExpression",
|
|
69
|
+
"TSNonNullExpression",
|
|
70
|
+
"TSTypeAssertion",
|
|
71
|
+
"ParenthesizedExpression"
|
|
72
|
+
]);
|
|
73
|
+
function unwrap$1(node) {
|
|
74
|
+
let current = node;
|
|
75
|
+
while (current !== void 0 && ERASED.has(current.type)) current = current["expression"];
|
|
76
|
+
return current;
|
|
77
|
+
}
|
|
78
|
+
/** A string literal or template's parts: one part for a literal, holes between parts otherwise. */
|
|
79
|
+
function idParts(node) {
|
|
80
|
+
const target = unwrap$1(node);
|
|
81
|
+
if (target?.type === "Literal" && typeof target["value"] === "string") return [target["value"]];
|
|
82
|
+
if (target?.type === "TemplateLiteral") {
|
|
83
|
+
const parts = target["quasis"].map((quasi) => quasi["value"].cooked);
|
|
84
|
+
if (parts.some((part) => part === null)) return void 0;
|
|
85
|
+
return parts;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* A literal object's literal string or boolean properties, as they stand after every property
|
|
90
|
+
* in order: a spread or a computed key may override anything before it, so what came before is
|
|
91
|
+
* forgotten (GPT review finding 12); a property the scan can't read is left out.
|
|
92
|
+
*/
|
|
93
|
+
function literalOptions(node) {
|
|
94
|
+
const target = unwrap$1(node);
|
|
95
|
+
if (target?.type !== "ObjectExpression") return void 0;
|
|
96
|
+
let out = {};
|
|
97
|
+
for (const property of target["properties"]) {
|
|
98
|
+
if (property.type !== "Property" || property["computed"]) {
|
|
99
|
+
out = {};
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
const key = property["key"];
|
|
103
|
+
const name = key.type === "Identifier" ? key["name"] : key["value"];
|
|
104
|
+
const value = unwrap$1(property["value"]);
|
|
105
|
+
if (typeof name === "string" && value?.type === "Literal" && (typeof value["value"] === "string" || typeof value["value"] === "boolean")) out[name] = value["value"];
|
|
106
|
+
}
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
/** The scan of one artifact. */
|
|
110
|
+
var FieldScan = class {
|
|
111
|
+
entries = [];
|
|
112
|
+
openReasons = [];
|
|
113
|
+
open(reason, location) {
|
|
114
|
+
this.openReasons.push({
|
|
115
|
+
reason,
|
|
116
|
+
...location ? { location } : {}
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
/** Scans one parsed module; `text` is what offsets refer to. */
|
|
120
|
+
module(file, text, program) {
|
|
121
|
+
const at = (node) => ({
|
|
122
|
+
file,
|
|
123
|
+
...lineColumn$1(text, node.start)
|
|
124
|
+
});
|
|
125
|
+
const hooks = /* @__PURE__ */ new Map();
|
|
126
|
+
const namespaces = /* @__PURE__ */ new Map();
|
|
127
|
+
for (const statement of program["body"]) {
|
|
128
|
+
const source = statement.type === "ImportDeclaration" || statement.type === "ExportNamedDeclaration" || statement.type === "ExportAllDeclaration" ? statement["source"]?.["value"] : void 0;
|
|
129
|
+
const exported = source === void 0 ? void 0 : HOOKS[source];
|
|
130
|
+
if (!exported) continue;
|
|
131
|
+
if (statement.type !== "ImportDeclaration") {
|
|
132
|
+
this.open(`${file} re-exports from ${source}`, at(statement));
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
if (statement["importKind"] === "type") continue;
|
|
136
|
+
for (const specifier of statement["specifiers"]) {
|
|
137
|
+
const local = specifier["local"]["name"];
|
|
138
|
+
if (specifier.type === "ImportNamespaceSpecifier") namespaces.set(local, exported);
|
|
139
|
+
else if (specifier.type === "ImportSpecifier" && specifier["importKind"] !== "type") {
|
|
140
|
+
const imported = specifier["imported"];
|
|
141
|
+
const name = imported["name"] ?? imported["value"];
|
|
142
|
+
if (exported.has(name)) hooks.set(local, name);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
const hookOf = (callee) => {
|
|
147
|
+
const target = unwrap$1(callee);
|
|
148
|
+
if (target?.type === "Identifier") return hooks.get(target["name"]);
|
|
149
|
+
if (target?.type === "MemberExpression" && !target["computed"]) {
|
|
150
|
+
const object = target["object"];
|
|
151
|
+
const property = target["property"]["name"];
|
|
152
|
+
if ((object.type === "Identifier" ? namespaces.get(object["name"]) : void 0)?.has(property)) return property;
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
const callees = /* @__PURE__ */ new Set();
|
|
156
|
+
const visit = (node) => {
|
|
157
|
+
if (node.type === "CallExpression") {
|
|
158
|
+
const callee = node["callee"];
|
|
159
|
+
const hook = hookOf(callee);
|
|
160
|
+
if (hook) {
|
|
161
|
+
callees.add(unwrap$1(callee));
|
|
162
|
+
this.call(hook, node["arguments"], at(node));
|
|
163
|
+
}
|
|
164
|
+
const target = unwrap$1(callee);
|
|
165
|
+
if (target?.type === "MemberExpression" && !target["computed"]) {
|
|
166
|
+
const object = unwrap$1(target["object"]);
|
|
167
|
+
const method = target["property"]["name"];
|
|
168
|
+
if ((object?.type === "MemberExpression" && !object["computed"] && object["object"].type === "Identifier" && GLOBALS.has(object["object"]["name"]) && object["property"]["name"] === "storage" || object?.type === "Identifier" && object["name"] === "storage") && STORAGE_METHODS.has(method)) this.storage(at(node));
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
if (node.type === "MemberExpression" && !node["computed"] && node["object"].type === "Identifier" && GLOBALS.has(node["object"]["name"]) && node["property"]["name"] === "storage") this.storage(at(node));
|
|
172
|
+
each(node, (child) => visit(child));
|
|
173
|
+
};
|
|
174
|
+
visit(program);
|
|
175
|
+
const references = (node, parentKey, parent) => {
|
|
176
|
+
if (node.type === "Identifier" && parentKey !== "property" && parentKey !== "key" && parent?.type !== "ImportSpecifier" && parent?.type !== "ImportNamespaceSpecifier") {
|
|
177
|
+
const name = node["name"];
|
|
178
|
+
if (hooks.has(name) && !callees.has(node)) this.open(`${file} uses ${name} other than by calling it`, at(node));
|
|
179
|
+
const exported = namespaces.get(name);
|
|
180
|
+
if (exported) {
|
|
181
|
+
const member = parent?.type === "MemberExpression" && parentKey === "object" && !parent["computed"] ? parent["property"]["name"] : void 0;
|
|
182
|
+
if (member === void 0 || exported.has(member) && !callees.has(parent)) this.open(`${file} uses ${name} other than by calling its hooks`, at(node));
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
each(node, (child, key) => references(child, key, node));
|
|
186
|
+
};
|
|
187
|
+
references(program, "", void 0);
|
|
188
|
+
}
|
|
189
|
+
storage(location) {
|
|
190
|
+
if (this.entries.some((entry) => entry.hook === "storage")) return;
|
|
191
|
+
this.entries.push({
|
|
192
|
+
template: ["storage.", ""],
|
|
193
|
+
hook: "storage",
|
|
194
|
+
scope: "viewer",
|
|
195
|
+
location
|
|
196
|
+
}, {
|
|
197
|
+
template: ["storage.", ""],
|
|
198
|
+
hook: "storage",
|
|
199
|
+
scope: "artifact",
|
|
200
|
+
location
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
call(hook, args, location) {
|
|
204
|
+
const first = args[0];
|
|
205
|
+
if (hook === "useForm") {
|
|
206
|
+
const options = unwrap$1(first);
|
|
207
|
+
let idProperty;
|
|
208
|
+
if (options?.type === "ObjectExpression") {
|
|
209
|
+
for (const property of options["properties"]) if (property.type !== "Property" || property["computed"]) idProperty = void 0;
|
|
210
|
+
else if ((property["key"]["name"] ?? property["key"]["value"]) === "id") idProperty = property;
|
|
211
|
+
}
|
|
212
|
+
const parts = idParts(idProperty?.["value"]);
|
|
213
|
+
if (!parts) {
|
|
214
|
+
this.open("a useForm call without a literal id", location);
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
const template = [
|
|
218
|
+
...parts.slice(0, -1),
|
|
219
|
+
`${parts.at(-1)}.`,
|
|
220
|
+
""
|
|
221
|
+
];
|
|
222
|
+
this.entries.push({
|
|
223
|
+
template,
|
|
224
|
+
hook,
|
|
225
|
+
location
|
|
226
|
+
});
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
const parts = idParts(first);
|
|
230
|
+
if (!parts) {
|
|
231
|
+
this.open(`a ${hook} call whose ID isn't a string literal or template`, location);
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
const wrap = (inner) => {
|
|
235
|
+
if (hook !== "useChoice") return inner;
|
|
236
|
+
const out = [...inner];
|
|
237
|
+
out[0] = `review.${out[0]}`;
|
|
238
|
+
out[out.length - 1] = `${out.at(-1)}.choice`;
|
|
239
|
+
return out;
|
|
240
|
+
};
|
|
241
|
+
const wrapped = wrap(parts);
|
|
242
|
+
const singleLiteral = parts.length === 1;
|
|
243
|
+
const options = hook === "useField" ? literalOptions(args[2]) : void 0;
|
|
244
|
+
const scopeOption = options?.["scope"];
|
|
245
|
+
const scope = scopeOption === "artifact" || scopeOption === "viewer" ? scopeOption : void 0;
|
|
246
|
+
this.entries.push({
|
|
247
|
+
...singleLiteral ? { id: wrapped.join("") } : { template: wrapped },
|
|
248
|
+
hook,
|
|
249
|
+
...scope !== void 0 ? { scope } : {},
|
|
250
|
+
...typeof options?.["label"] === "string" ? { label: options["label"] } : {},
|
|
251
|
+
...typeof options?.["required"] === "boolean" ? { required: options["required"] } : {},
|
|
252
|
+
...typeof options?.["sensitive"] === "boolean" ? { sensitive: options["sensitive"] } : {},
|
|
253
|
+
location
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
result() {
|
|
257
|
+
if (this.entries.length === 0 && this.openReasons.length === 0) this.open("the artifact declares no fields through @mostra/react");
|
|
258
|
+
return {
|
|
259
|
+
open: this.openReasons.length > 0,
|
|
260
|
+
openReasons: this.openReasons,
|
|
261
|
+
entries: this.entries
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
/** Mentions that make a file worth parsing for fields. */
|
|
266
|
+
const MENTIONS = /@mostra\/react|storage/;
|
|
267
|
+
/** A file that speaks the browser protocol itself writes fields the scan can't follow. */
|
|
268
|
+
const RAW_PROTOCOL = /_mostra\/v\//;
|
|
269
|
+
/** Scans the artifact's scripts and MDX pages (`files` are paths inside `sourceDir`). */
|
|
270
|
+
async function scanFields(sourceDir, files) {
|
|
271
|
+
const scan = new FieldScan();
|
|
272
|
+
for (const file of [...files].sort()) {
|
|
273
|
+
const ext = extname(file);
|
|
274
|
+
const lang = SCRIPT_LANG[ext];
|
|
275
|
+
if (lang === void 0 && ext !== ".mdx") continue;
|
|
276
|
+
const source = await readFile(join(sourceDir, file), "utf8");
|
|
277
|
+
if (RAW_PROTOCOL.test(source)) scan.open(`${file} calls the browser protocol directly`);
|
|
278
|
+
if (!MENTIONS.test(source)) continue;
|
|
279
|
+
let text = source;
|
|
280
|
+
let parseLang = lang ?? "jsx";
|
|
281
|
+
if (ext === ".mdx") try {
|
|
282
|
+
const compiled = await compile({
|
|
283
|
+
value: source,
|
|
284
|
+
path: file
|
|
285
|
+
}, {
|
|
286
|
+
jsxImportSource: "react",
|
|
287
|
+
remarkPlugins: [remarkFrontmatter, remarkGfm]
|
|
288
|
+
});
|
|
289
|
+
text = String(compiled.value);
|
|
290
|
+
parseLang = "js";
|
|
291
|
+
} catch {
|
|
292
|
+
scan.open(`${file} doesn't compile`);
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
295
|
+
const parsed = parseSync(file, text, { lang: parseLang });
|
|
296
|
+
if (parsed.errors.length > 0) {
|
|
297
|
+
scan.open(`${file} doesn't parse`);
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
scan.module(file, text, parsed.program);
|
|
301
|
+
}
|
|
302
|
+
return scan.result();
|
|
303
|
+
}
|
|
304
|
+
//#endregion
|
|
305
|
+
//#region src/builder/child/scan.ts
|
|
306
|
+
/**
|
|
307
|
+
* The builder child's static scan of an artifact (INTERFACES §11): its `"use server"` modules with
|
|
308
|
+
* their exports and `dryRun()` opt-ins (D54, D55), the live sources of `live.ts` (D56) and the
|
|
309
|
+
* routes of `pages/` (D57). Parsing only; nothing in the artifact runs.
|
|
310
|
+
*/
|
|
311
|
+
/** Every script extension the bundler loads; a "use server" module may have any of them. */
|
|
312
|
+
const SCRIPT = /* @__PURE__ */ new Set([
|
|
313
|
+
".ts",
|
|
314
|
+
".tsx",
|
|
315
|
+
".mts",
|
|
316
|
+
".cts",
|
|
317
|
+
".js",
|
|
318
|
+
".jsx",
|
|
319
|
+
".mjs",
|
|
320
|
+
".cjs"
|
|
321
|
+
]);
|
|
322
|
+
/** Oxc's language for a script file. */
|
|
323
|
+
function langOf(file) {
|
|
324
|
+
const ext = extname(file);
|
|
325
|
+
if (ext === ".tsx") return "tsx";
|
|
326
|
+
if (ext === ".jsx") return "jsx";
|
|
327
|
+
if (ext === ".ts" || ext === ".mts" || ext === ".cts") return "ts";
|
|
328
|
+
return "js";
|
|
329
|
+
}
|
|
330
|
+
/**
|
|
331
|
+
* Whether a script starts with the `"use server"` directive. `undefined` when it doesn't parse:
|
|
332
|
+
* the bundler, which parses the same way, then reports the syntax error.
|
|
333
|
+
*/
|
|
334
|
+
function startsWithUseServer(file, text) {
|
|
335
|
+
if (!text.includes("use server")) return false;
|
|
336
|
+
const parsed = parseSync(file, text, { lang: langOf(file) });
|
|
337
|
+
if (parsed.errors.length > 0) return void 0;
|
|
338
|
+
return isServerModule(parsed.program);
|
|
339
|
+
}
|
|
340
|
+
const PAGE = /* @__PURE__ */ new Set([
|
|
341
|
+
".tsx",
|
|
342
|
+
".jsx",
|
|
343
|
+
".mdx"
|
|
344
|
+
]);
|
|
345
|
+
const SERVER_PACKAGE = "@mostra/server";
|
|
346
|
+
async function walk(dir, prefix, out) {
|
|
347
|
+
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
348
|
+
const path = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
349
|
+
if (entry.isDirectory()) await walk(join(dir, entry.name), path, out);
|
|
350
|
+
else if (entry.isFile()) out.push(path);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
function lineColumn(text, offset) {
|
|
354
|
+
const before = text.slice(0, offset);
|
|
355
|
+
return {
|
|
356
|
+
line: before.split("\n").length,
|
|
357
|
+
column: offset - before.lastIndexOf("\n")
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
/** Calls each child node of `node`. */
|
|
361
|
+
function children(node, visit) {
|
|
362
|
+
for (const [key, value] of Object.entries(node)) if (Array.isArray(value)) {
|
|
363
|
+
for (const item of value) if (item && typeof item === "object" && "type" in item) visit(item, node, key);
|
|
364
|
+
} else if (value && typeof value === "object" && "type" in value) visit(value, node, key);
|
|
365
|
+
}
|
|
366
|
+
/** Whether the module starts with the `"use server"` directive. */
|
|
367
|
+
function isServerModule(program) {
|
|
368
|
+
for (const statement of program["body"]) {
|
|
369
|
+
if (statement.type !== "ExpressionStatement" || typeof statement["directive"] !== "string") return false;
|
|
370
|
+
if (statement["directive"] === "use server") return true;
|
|
371
|
+
}
|
|
372
|
+
return false;
|
|
373
|
+
}
|
|
374
|
+
/** TypeScript wrappers that compile away: `as`, `satisfies`, `!`, `<T>x` and parentheses. */
|
|
375
|
+
const ERASED_WRAPPERS = /* @__PURE__ */ new Set([
|
|
376
|
+
"TSAsExpression",
|
|
377
|
+
"TSSatisfiesExpression",
|
|
378
|
+
"TSNonNullExpression",
|
|
379
|
+
"TSTypeAssertion",
|
|
380
|
+
"TSInstantiationExpression",
|
|
381
|
+
"ParenthesizedExpression"
|
|
382
|
+
]);
|
|
383
|
+
/** The expression a wrapper chain wraps: `(async () => 1) satisfies F` is the arrow function. */
|
|
384
|
+
function unwrap(node) {
|
|
385
|
+
let current = node;
|
|
386
|
+
while (current !== void 0 && ERASED_WRAPPERS.has(current.type)) current = current["expression"];
|
|
387
|
+
return current;
|
|
388
|
+
}
|
|
389
|
+
const isAsyncFunction = (node) => {
|
|
390
|
+
const target = unwrap(node);
|
|
391
|
+
return target !== void 0 && (target.type === "FunctionDeclaration" || target.type === "FunctionExpression" || target.type === "ArrowFunctionExpression") && target["async"] === true;
|
|
392
|
+
};
|
|
393
|
+
/**
|
|
394
|
+
* Declarations that exist only for the type checker: types, interfaces, overload signatures and
|
|
395
|
+
* anything `declare`d. Enums and namespaces are values at run time, so they are not among them.
|
|
396
|
+
*/
|
|
397
|
+
const isErasedDeclaration = (node) => node["declare"] === true || node.type === "TSTypeAliasDeclaration" || node.type === "TSInterfaceDeclaration" || node.type === "TSDeclareFunction";
|
|
398
|
+
/**
|
|
399
|
+
* Reads one `"use server"` module: every export must be an async function (React's contract),
|
|
400
|
+
* and an export opts into `verify`'s smoke test when it, or a module-level function it calls,
|
|
401
|
+
* calls `dryRun()` from `@mostra/server` (D55).
|
|
402
|
+
*/
|
|
403
|
+
function serverExports(module, text, program, diagnostics) {
|
|
404
|
+
const dryRunNames = /* @__PURE__ */ new Set();
|
|
405
|
+
const namespaces = /* @__PURE__ */ new Set();
|
|
406
|
+
const functions = /* @__PURE__ */ new Map();
|
|
407
|
+
const exported = [];
|
|
408
|
+
const invalid = (at, message) => {
|
|
409
|
+
diagnostics.push(createDiagnostic("MOSTRA_ACTION_EXPORT_INVALID", {
|
|
410
|
+
message,
|
|
411
|
+
location: {
|
|
412
|
+
file: module,
|
|
413
|
+
...lineColumn(text, at)
|
|
414
|
+
}
|
|
415
|
+
}));
|
|
416
|
+
};
|
|
417
|
+
const remember = (declaration) => {
|
|
418
|
+
if (declaration.type === "FunctionDeclaration" && declaration["id"]) functions.set(declaration["id"]["name"], declaration);
|
|
419
|
+
if (declaration.type === "VariableDeclaration") for (const declarator of declaration["declarations"]) {
|
|
420
|
+
const id = declarator["id"];
|
|
421
|
+
if (id.type === "Identifier" && declarator["init"]) functions.set(id["name"], declarator["init"]);
|
|
422
|
+
}
|
|
423
|
+
};
|
|
424
|
+
for (const statement of program["body"]) if (statement.type === "ImportDeclaration" && statement["source"]["value"] === SERVER_PACKAGE) for (const specifier of statement["specifiers"]) {
|
|
425
|
+
const local = specifier["local"]["name"];
|
|
426
|
+
if (specifier.type === "ImportNamespaceSpecifier") namespaces.add(local);
|
|
427
|
+
const imported = specifier["imported"];
|
|
428
|
+
if (specifier.type === "ImportSpecifier" && (imported?.["name"] ?? imported?.["value"]) === "dryRun") dryRunNames.add(local);
|
|
429
|
+
}
|
|
430
|
+
else if (statement.type === "ExportNamedDeclaration") {
|
|
431
|
+
if (statement["exportKind"] === "type") continue;
|
|
432
|
+
if (statement["source"]) {
|
|
433
|
+
invalid(statement.start, `${module} re-exports from another module; a "use server" module exports only its own async functions.`);
|
|
434
|
+
continue;
|
|
435
|
+
}
|
|
436
|
+
const declaration = statement["declaration"];
|
|
437
|
+
if (declaration) {
|
|
438
|
+
if (isErasedDeclaration(declaration)) continue;
|
|
439
|
+
remember(declaration);
|
|
440
|
+
if (declaration.type === "FunctionDeclaration") {
|
|
441
|
+
const name = declaration["id"]["name"];
|
|
442
|
+
exported.push({
|
|
443
|
+
name,
|
|
444
|
+
local: declaration,
|
|
445
|
+
at: declaration.start
|
|
446
|
+
});
|
|
447
|
+
} else if (declaration.type === "VariableDeclaration") for (const declarator of declaration["declarations"]) {
|
|
448
|
+
const id = declarator["id"];
|
|
449
|
+
exported.push({
|
|
450
|
+
name: id.type === "Identifier" ? id["name"] : "(pattern)",
|
|
451
|
+
local: declarator["init"] ?? void 0,
|
|
452
|
+
at: declarator.start
|
|
453
|
+
});
|
|
454
|
+
}
|
|
455
|
+
else exported.push({
|
|
456
|
+
name: "(declaration)",
|
|
457
|
+
local: declaration,
|
|
458
|
+
at: declaration.start
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
for (const specifier of statement["specifiers"] ?? []) {
|
|
462
|
+
if (specifier["exportKind"] === "type") continue;
|
|
463
|
+
const name = specifier["exported"]["name"] ?? specifier["exported"]["value"];
|
|
464
|
+
const local = specifier["local"]["name"];
|
|
465
|
+
exported.push({
|
|
466
|
+
name,
|
|
467
|
+
local: {
|
|
468
|
+
type: "Ref",
|
|
469
|
+
start: specifier.start,
|
|
470
|
+
end: specifier.end,
|
|
471
|
+
name: local
|
|
472
|
+
},
|
|
473
|
+
at: specifier.start
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
} else if (statement.type === "ExportDefaultDeclaration") {
|
|
477
|
+
const declaration = statement["declaration"];
|
|
478
|
+
if (declaration.type === "FunctionDeclaration" && declaration["id"]) remember(declaration);
|
|
479
|
+
exported.push({
|
|
480
|
+
name: "default",
|
|
481
|
+
local: declaration.type === "Identifier" ? {
|
|
482
|
+
type: "Ref",
|
|
483
|
+
start: declaration.start,
|
|
484
|
+
end: declaration.end,
|
|
485
|
+
name: declaration["name"]
|
|
486
|
+
} : declaration,
|
|
487
|
+
at: statement.start
|
|
488
|
+
});
|
|
489
|
+
} else if (statement.type === "ExportAllDeclaration") invalid(statement.start, `${module} re-exports with \`export *\`; a "use server" module exports only its own async functions.`);
|
|
490
|
+
else if (!isErasedDeclaration(statement)) remember(statement);
|
|
491
|
+
const calls = /* @__PURE__ */ new Map();
|
|
492
|
+
const direct = /* @__PURE__ */ new Set();
|
|
493
|
+
const scan = (node, owner) => {
|
|
494
|
+
if (node.type === "CallExpression") {
|
|
495
|
+
const callee = node["callee"];
|
|
496
|
+
if (callee.type === "Identifier") {
|
|
497
|
+
const name = callee["name"];
|
|
498
|
+
if (dryRunNames.has(name)) direct.add(owner);
|
|
499
|
+
else calls.get(owner)?.add(name);
|
|
500
|
+
} else if (callee.type === "MemberExpression" && !callee["computed"] && callee["object"].type === "Identifier" && namespaces.has(callee["object"]["name"]) && callee["property"]["name"] === "dryRun") direct.add(owner);
|
|
501
|
+
}
|
|
502
|
+
children(node, (child) => scan(child, owner));
|
|
503
|
+
};
|
|
504
|
+
for (const [name, node] of functions) {
|
|
505
|
+
calls.set(name, /* @__PURE__ */ new Set());
|
|
506
|
+
scan(node, name);
|
|
507
|
+
}
|
|
508
|
+
const optsIn = (name, seen = /* @__PURE__ */ new Set()) => {
|
|
509
|
+
if (direct.has(name)) return true;
|
|
510
|
+
if (seen.has(name)) return false;
|
|
511
|
+
seen.add(name);
|
|
512
|
+
return [...calls.get(name) ?? []].some((callee) => optsIn(callee, seen));
|
|
513
|
+
};
|
|
514
|
+
const entries = [];
|
|
515
|
+
for (const { name, local, at } of exported) {
|
|
516
|
+
let target = unwrap(local?.type === "Ref" ? functions.get(local["name"]) : local);
|
|
517
|
+
const followed = /* @__PURE__ */ new Set();
|
|
518
|
+
while (target?.type === "Identifier" && !followed.has(target["name"])) {
|
|
519
|
+
followed.add(target["name"]);
|
|
520
|
+
target = unwrap(functions.get(target["name"]));
|
|
521
|
+
}
|
|
522
|
+
if (!isAsyncFunction(target)) {
|
|
523
|
+
invalid(at, `The export \`${name}\` of ${module} isn't an async function; a "use server" module exports only async functions.`);
|
|
524
|
+
continue;
|
|
525
|
+
}
|
|
526
|
+
let dryRun;
|
|
527
|
+
if (local?.type === "Ref") dryRun = optsIn(local["name"]);
|
|
528
|
+
else {
|
|
529
|
+
const owner = `export:${name}`;
|
|
530
|
+
calls.set(owner, /* @__PURE__ */ new Set());
|
|
531
|
+
scan(target, owner);
|
|
532
|
+
dryRun = optsIn(owner);
|
|
533
|
+
}
|
|
534
|
+
entries.push({
|
|
535
|
+
id: `${module}#${name}`,
|
|
536
|
+
module,
|
|
537
|
+
export: name,
|
|
538
|
+
dryRun
|
|
539
|
+
});
|
|
540
|
+
}
|
|
541
|
+
return entries;
|
|
542
|
+
}
|
|
543
|
+
/**
|
|
544
|
+
* Whether a `defineLive({ … })` argument says `always: true` (D63): `true` or `false` when the
|
|
545
|
+
* object literal tells, `undefined` when it can't be known without running it (a spread, a
|
|
546
|
+
* computed key, a value other than a literal, or no object literal at all).
|
|
547
|
+
*/
|
|
548
|
+
function literalAlways(argument) {
|
|
549
|
+
if (argument?.type !== "ObjectExpression") return void 0;
|
|
550
|
+
let always = false;
|
|
551
|
+
for (const property of argument["properties"]) {
|
|
552
|
+
if (property.type !== "Property" || property["computed"] === true) {
|
|
553
|
+
always = void 0;
|
|
554
|
+
continue;
|
|
555
|
+
}
|
|
556
|
+
const key = property["key"];
|
|
557
|
+
if ((key.type === "Identifier" ? key["name"] : key["value"]) !== "always") continue;
|
|
558
|
+
const value = property["value"];
|
|
559
|
+
always = value.type === "Literal" && typeof value["value"] === "boolean" ? value["value"] : void 0;
|
|
560
|
+
}
|
|
561
|
+
return always;
|
|
562
|
+
}
|
|
563
|
+
/** The exports of `live.ts` that are `defineLive(...)` calls (D56), with their literal `always`. */
|
|
564
|
+
function liveExports(program) {
|
|
565
|
+
const keys = [];
|
|
566
|
+
for (const statement of program["body"]) {
|
|
567
|
+
if (statement.type !== "ExportNamedDeclaration") continue;
|
|
568
|
+
const declaration = statement["declaration"];
|
|
569
|
+
if (declaration?.type !== "VariableDeclaration") continue;
|
|
570
|
+
for (const declarator of declaration["declarations"]) {
|
|
571
|
+
const id = declarator["id"];
|
|
572
|
+
const init = declarator["init"];
|
|
573
|
+
const callee = init?.type === "CallExpression" ? init["callee"] : void 0;
|
|
574
|
+
const calleeName = callee?.type === "Identifier" ? callee["name"] : callee?.type === "MemberExpression" ? callee["property"]["name"] : void 0;
|
|
575
|
+
if (id.type === "Identifier" && calleeName === "defineLive") {
|
|
576
|
+
const always = literalAlways((init?.["arguments"])?.[0]);
|
|
577
|
+
keys.push({
|
|
578
|
+
key: id["name"],
|
|
579
|
+
...always === void 0 ? {} : { always }
|
|
580
|
+
});
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
return keys;
|
|
585
|
+
}
|
|
586
|
+
/** `pages/reports/[id].tsx` → `/reports/:id`; `index` names its folder (D57). */
|
|
587
|
+
function routePath(file) {
|
|
588
|
+
return `/${file.slice(6, file.length - extname(file).length).split("/").filter((segment, index, all) => !(segment === "index" && index === all.length - 1)).map((segment) => {
|
|
589
|
+
if (/^\[\.\.\.(.+)\]$/.exec(segment)) return "*";
|
|
590
|
+
const param = /^\[(.+)\]$/.exec(segment);
|
|
591
|
+
return param ? `:${param[1]}` : segment;
|
|
592
|
+
}).join("/")}`;
|
|
593
|
+
}
|
|
594
|
+
/** Scans the snapshot in `sourceDir`. */
|
|
595
|
+
async function scanArtifact(sourceDir) {
|
|
596
|
+
const files = [];
|
|
597
|
+
await walk(sourceDir, "", files);
|
|
598
|
+
const diagnostics = [];
|
|
599
|
+
const serverModules = /* @__PURE__ */ new Map();
|
|
600
|
+
const unparsed = [];
|
|
601
|
+
let liveSources = [];
|
|
602
|
+
for (const file of files.sort()) {
|
|
603
|
+
if (!SCRIPT.has(extname(file))) continue;
|
|
604
|
+
const text = await readFile(join(sourceDir, file), "utf8");
|
|
605
|
+
if (!text.includes("use server") && file !== "live.ts") continue;
|
|
606
|
+
const parsed = parseSync(file, text, { lang: langOf(file) });
|
|
607
|
+
if (parsed.errors.length > 0) {
|
|
608
|
+
const first = parsed.errors[0];
|
|
609
|
+
const offset = first?.labels[0]?.start ?? 0;
|
|
610
|
+
const before = text.slice(0, offset).split("\n");
|
|
611
|
+
unparsed.push(createDiagnostic("MOSTRA_BUILD_FAILED", {
|
|
612
|
+
message: `${file}: ${first?.message ?? "a syntax error"}.`,
|
|
613
|
+
location: {
|
|
614
|
+
file,
|
|
615
|
+
line: before.length,
|
|
616
|
+
column: (before.at(-1)?.length ?? 0) + 1
|
|
617
|
+
}
|
|
618
|
+
}));
|
|
619
|
+
continue;
|
|
620
|
+
}
|
|
621
|
+
const program = parsed.program;
|
|
622
|
+
if (file === "live.ts") liveSources = liveExports(program);
|
|
623
|
+
if (isServerModule(program)) serverModules.set(file, serverExports(file, text, program, diagnostics));
|
|
624
|
+
}
|
|
625
|
+
const pages = files.filter((file) => file.startsWith("pages/") && PAGE.has(extname(file))).sort().map((file) => ({
|
|
626
|
+
path: routePath(file),
|
|
627
|
+
file
|
|
628
|
+
}));
|
|
629
|
+
const byPath = /* @__PURE__ */ new Map();
|
|
630
|
+
for (const page of pages) {
|
|
631
|
+
const other = byPath.get(page.path);
|
|
632
|
+
if (other) diagnostics.push(createDiagnostic("MOSTRA_BUILD_FAILED", {
|
|
633
|
+
message: `${other} and ${page.file} are both the page ${page.path}; keep one.`,
|
|
634
|
+
location: {
|
|
635
|
+
file: page.file,
|
|
636
|
+
line: 1,
|
|
637
|
+
column: 1
|
|
638
|
+
}
|
|
639
|
+
}));
|
|
640
|
+
byPath.set(page.path, page.file);
|
|
641
|
+
}
|
|
642
|
+
const fields = await scanFields(sourceDir, files);
|
|
643
|
+
return {
|
|
644
|
+
serverModules,
|
|
645
|
+
liveSources,
|
|
646
|
+
hasLive: files.includes("live.ts"),
|
|
647
|
+
pages,
|
|
648
|
+
fields,
|
|
649
|
+
diagnostics,
|
|
650
|
+
unparsed
|
|
651
|
+
};
|
|
652
|
+
}
|
|
653
|
+
//#endregion
|
|
654
|
+
//#region src/builder/child/plugins.ts
|
|
655
|
+
/**
|
|
656
|
+
* The Vite plugins of the SPA build (D19 seams 1 and 2): MDX compilation, and the `"use server"`
|
|
657
|
+
* client-stub transform, which replaces each server module in the client build with
|
|
658
|
+
* `createServerReference` stubs so no server code reaches the browser (D54).
|
|
659
|
+
*/
|
|
660
|
+
/** Compiles `.mdx` files to JavaScript with React's JSX runtime, frontmatter removed (MDX 3). */
|
|
661
|
+
function mdxPlugin() {
|
|
662
|
+
return {
|
|
663
|
+
name: "mostra:mdx",
|
|
664
|
+
enforce: "pre",
|
|
665
|
+
async transform(code, id) {
|
|
666
|
+
const file = id.split("?")[0] ?? id;
|
|
667
|
+
if (!file.endsWith(".mdx")) return null;
|
|
668
|
+
const compiled = await compile({
|
|
669
|
+
value: code,
|
|
670
|
+
path: file
|
|
671
|
+
}, {
|
|
672
|
+
jsxImportSource: "react",
|
|
673
|
+
remarkPlugins: [remarkFrontmatter, remarkGfm],
|
|
674
|
+
development: false
|
|
675
|
+
});
|
|
676
|
+
return {
|
|
677
|
+
code: String(compiled.value),
|
|
678
|
+
map: null,
|
|
679
|
+
moduleType: "js"
|
|
680
|
+
};
|
|
681
|
+
}
|
|
682
|
+
};
|
|
683
|
+
}
|
|
684
|
+
/**
|
|
685
|
+
* Records every module outside the artifact that imports `@mostra/react` or `@mostra/react/form`
|
|
686
|
+
* (D109): such a package may name fields the artifact's scan can't see, so the version's coverage
|
|
687
|
+
* is open. `@mostra/react` itself and Mostra's generated files don't count. It resolves nothing.
|
|
688
|
+
*/
|
|
689
|
+
function fieldHookUsePlugin(roots, uses) {
|
|
690
|
+
const inside = (file, dir) => dir !== void 0 && (file === dir || file.startsWith(`${dir}/`));
|
|
691
|
+
return {
|
|
692
|
+
name: "mostra:field-hook-use",
|
|
693
|
+
enforce: "pre",
|
|
694
|
+
resolveId(source, importer) {
|
|
695
|
+
if (source !== "@mostra/react" && source !== "@mostra/react/form") return null;
|
|
696
|
+
if (importer === void 0 || importer.startsWith("\0")) return null;
|
|
697
|
+
const file = existsSync(importer) ? realpathSync(importer) : importer;
|
|
698
|
+
if (inside(file, roots.sourceDir) || inside(file, roots.generatedDir) || inside(file, roots.runtimeDir)) return null;
|
|
699
|
+
if (!uses.some((use) => use.importer === file)) uses.push({ importer: file });
|
|
700
|
+
return null;
|
|
701
|
+
}
|
|
702
|
+
};
|
|
703
|
+
}
|
|
704
|
+
/** The client stub of one `"use server"` module. */
|
|
705
|
+
function serverStub(entries) {
|
|
706
|
+
const lines = ["import { createServerReference } from \"@mostra/react\";"];
|
|
707
|
+
entries.forEach((entry, index) => {
|
|
708
|
+
lines.push(`const reference${index} = createServerReference(${JSON.stringify(entry.id)});`, `export { reference${index} as ${JSON.stringify(entry.export)} };`);
|
|
709
|
+
});
|
|
710
|
+
return `${lines.join("\n")}\n`;
|
|
711
|
+
}
|
|
712
|
+
/** The ID prefix of the virtual stub modules that stand in for server modules in the client. */
|
|
713
|
+
const STUB_PREFIX = "\0mostra-server-reference:";
|
|
714
|
+
/**
|
|
715
|
+
* Replaces `"use server"` modules with their client stubs. `modules` maps each module's absolute
|
|
716
|
+
* path to its exports, from the scan.
|
|
717
|
+
*/
|
|
718
|
+
function serverClientStubPlugin(modules, sourceDir) {
|
|
719
|
+
return {
|
|
720
|
+
name: "mostra:use-server-client",
|
|
721
|
+
enforce: "pre",
|
|
722
|
+
async resolveId(source, importer, options) {
|
|
723
|
+
if (source.startsWith(STUB_PREFIX)) return source;
|
|
724
|
+
const file = (await this.resolve(source, importer, {
|
|
725
|
+
...options,
|
|
726
|
+
skipSelf: true
|
|
727
|
+
}))?.id.split("?")[0];
|
|
728
|
+
return file !== void 0 && modules.has(file) ? `${STUB_PREFIX}${file}.mjs` : null;
|
|
729
|
+
},
|
|
730
|
+
load(id) {
|
|
731
|
+
if (!id.startsWith(STUB_PREFIX)) return null;
|
|
732
|
+
const entries = modules.get(id.slice(25, -4));
|
|
733
|
+
return entries === void 0 ? null : {
|
|
734
|
+
code: serverStub(entries),
|
|
735
|
+
moduleType: "js"
|
|
736
|
+
};
|
|
737
|
+
},
|
|
738
|
+
transform(code, id) {
|
|
739
|
+
const file = id.split("?")[0] ?? id;
|
|
740
|
+
if (!file.startsWith(`${sourceDir}/`) || modules.has(file)) return null;
|
|
741
|
+
if (!SCRIPT.has(extname(file))) return null;
|
|
742
|
+
if (startsWithUseServer(file, code) !== true) return null;
|
|
743
|
+
return this.error(`${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(", ")}.`);
|
|
744
|
+
}
|
|
745
|
+
};
|
|
746
|
+
}
|
|
747
|
+
/**
|
|
748
|
+
* Keeps a build's inputs inside what the version's digests cover (VR-01, DATA_MODEL §2). A relative
|
|
749
|
+
* or absolute import from an artifact file must resolve inside the artifact, and a package import
|
|
750
|
+
* from an artifact file or a generated file must resolve into the build's packages (the warm set
|
|
751
|
+
* and the artifact's lockfile). An import from inside a package must stay among those packages
|
|
752
|
+
* too: a package that imports a dependency it doesn't declare would otherwise find it in any
|
|
753
|
+
* `node_modules` above the home. Anything else (a file beside the artifact, a stray
|
|
754
|
+
* `node_modules` above the home) would bring bytes into the build that no digest covers, so a
|
|
755
|
+
* later change to them would go unnoticed.
|
|
756
|
+
*/
|
|
757
|
+
function confinePlugin(inputs) {
|
|
758
|
+
const under = (file, dir) => file.startsWith(`${dir}/`);
|
|
759
|
+
const ours = (file) => under(file, inputs.sourceDir) || under(file, inputs.generatedDir);
|
|
760
|
+
const packaged = (file) => inputs.packageRoots.some((root) => under(file, root));
|
|
761
|
+
const real = (file) => {
|
|
762
|
+
try {
|
|
763
|
+
return realpathSync.native(file);
|
|
764
|
+
} catch {
|
|
765
|
+
return file;
|
|
766
|
+
}
|
|
767
|
+
};
|
|
768
|
+
return {
|
|
769
|
+
name: "mostra:confine",
|
|
770
|
+
enforce: "pre",
|
|
771
|
+
async resolveId(source, importer, options) {
|
|
772
|
+
const from = importer?.split("?")[0];
|
|
773
|
+
if (from === void 0 || source.startsWith("\0")) return null;
|
|
774
|
+
const fromPackage = !ours(from);
|
|
775
|
+
if (fromPackage && !packaged(from)) return null;
|
|
776
|
+
const bare = !source.startsWith(".") && !source.startsWith("/");
|
|
777
|
+
const resolved = await this.resolve(source, importer, {
|
|
778
|
+
...options,
|
|
779
|
+
skipSelf: true
|
|
780
|
+
});
|
|
781
|
+
if (!resolved || resolved.external) return resolved;
|
|
782
|
+
const id = resolved.id.split("?")[0] ?? resolved.id;
|
|
783
|
+
if (id.startsWith("\0") || !isAbsolute(id) || !existsSync(id)) return resolved;
|
|
784
|
+
const file = real(id);
|
|
785
|
+
if (fromPackage) {
|
|
786
|
+
if (packaged(file)) return resolved;
|
|
787
|
+
return this.error(`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.`);
|
|
788
|
+
}
|
|
789
|
+
if (ours(file)) return resolved;
|
|
790
|
+
if (bare && packaged(file)) return resolved;
|
|
791
|
+
const where = relative(inputs.sourceDir, from);
|
|
792
|
+
return this.error(bare ? `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\`.` : `Could not resolve "${source}" from ${where}: it is outside the artifact, and a version is built only from the artifact's own files.`);
|
|
793
|
+
}
|
|
794
|
+
};
|
|
795
|
+
}
|
|
796
|
+
//#endregion
|
|
797
|
+
//#region src/builder/child/spa.ts
|
|
798
|
+
/** Where generated build files live inside the staging directory (never in the snapshot). */
|
|
799
|
+
const GENERATED = ".mostra-build";
|
|
800
|
+
const html = (title, versionId) => `<!doctype html>
|
|
801
|
+
<html lang="en">
|
|
802
|
+
<head>
|
|
803
|
+
<meta charset="utf-8" />
|
|
804
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
805
|
+
<meta name="mostra-version" content="${versionId}" />
|
|
806
|
+
<title>${title.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">")}</title>
|
|
807
|
+
</head>
|
|
808
|
+
<body>
|
|
809
|
+
<div id="root"></div>
|
|
810
|
+
<script type="module" src="/${GENERATED}/entry.js"><\/script>
|
|
811
|
+
</body>
|
|
812
|
+
</html>
|
|
813
|
+
`;
|
|
814
|
+
/**
|
|
815
|
+
* The client entry: hands the page, or the `pages/` routes inside the entry's layout (D57), to the
|
|
816
|
+
* client runtime, which picks the history mode for its delivery target (D111), connects to the
|
|
817
|
+
* shell over the bridge, reports the current page and `mostra/ready` (SH-04), and installs
|
|
818
|
+
* `window.storage` (D53). A single page never loads React Router.
|
|
819
|
+
*/
|
|
820
|
+
function clientEntry(request, scan) {
|
|
821
|
+
const source = (file) => JSON.stringify(`../source/${file}`);
|
|
822
|
+
const lines = [`import "./styles.css";`];
|
|
823
|
+
if (scan.pages.length === 0) {
|
|
824
|
+
lines.push(`import { mountArtifact } from "@mostra/react";`, `import Page from ${source(request.entry)};`, `mountArtifact({ page: Page });`);
|
|
825
|
+
return `${lines.join("\n")}\n`;
|
|
826
|
+
}
|
|
827
|
+
lines.push(`import { mountRoutes } from "@mostra/react/router";`, request.entryHasDefault ? `import Layout from ${source(request.entry)};` : `import ${source(request.entry)};`);
|
|
828
|
+
for (const [index, page] of scan.pages.entries()) lines.push(`import Page${index} from ${source(page.file)};`);
|
|
829
|
+
const routes = scan.pages.map((page, index) => `{ path: ${JSON.stringify(page.path)}, page: Page${index} }`).join(", ");
|
|
830
|
+
const layout = request.entryHasDefault ? ", layout: Layout" : "";
|
|
831
|
+
lines.push(`mountRoutes({ routes: [${routes}]${layout} });`);
|
|
832
|
+
return `${lines.join("\n")}\n`;
|
|
833
|
+
}
|
|
834
|
+
/** The field coverage, opened by every package outside the artifact that uses the field hooks. */
|
|
835
|
+
function withPackageUses(fields, uses) {
|
|
836
|
+
const packageOf = (file) => {
|
|
837
|
+
return [...file.matchAll(/node_modules\/((?:@[^/]+\/)?[^/]+)/g)].at(-1)?.[1] ?? file;
|
|
838
|
+
};
|
|
839
|
+
const openReasons = [...fields.openReasons, ...[...new Set(uses.map((use) => packageOf(use.importer)))].map((name) => ({ reason: `the package ${name} uses @mostra/react's field hooks` }))];
|
|
840
|
+
return {
|
|
841
|
+
...fields,
|
|
842
|
+
open: openReasons.length > 0,
|
|
843
|
+
openReasons
|
|
844
|
+
};
|
|
845
|
+
}
|
|
846
|
+
/** The server entry: every server function by ID, and the live sources (loaded by WP-08's worker). */
|
|
847
|
+
function serverEntry(scan) {
|
|
848
|
+
const lines = [];
|
|
849
|
+
const functions = [];
|
|
850
|
+
[...scan.serverModules.entries()].forEach(([module, entries], index) => {
|
|
851
|
+
lines.push(`import * as module${index} from ${JSON.stringify(`../source/${module}`)};`);
|
|
852
|
+
for (const entry of entries) functions.push(` ${JSON.stringify(entry.id)}: module${index}[${JSON.stringify(entry.export)}],`);
|
|
853
|
+
});
|
|
854
|
+
lines.push(`export const functions = {\n${functions.join("\n")}\n};`);
|
|
855
|
+
if (scan.hasLive) lines.push(`export * as live from "../source/live.ts";`);
|
|
856
|
+
else lines.push("export const live = {};");
|
|
857
|
+
return `${lines.join("\n")}\n`;
|
|
858
|
+
}
|
|
859
|
+
/** Turns a bundler error into a diagnostic with the file relative to the artifact. */
|
|
860
|
+
function diagnose(error, sourceDir) {
|
|
861
|
+
const failure = error;
|
|
862
|
+
const first = failure.errors?.[0] ?? failure;
|
|
863
|
+
const rawMessage = stripVTControlCharacters(first.message ?? String(error)).replaceAll(`${sourceDir}/`, "");
|
|
864
|
+
const file = first.loc?.file ?? first.id;
|
|
865
|
+
const inSource = file?.startsWith(sourceDir) ? relative(sourceDir, file) : void 0;
|
|
866
|
+
const location = inSource !== void 0 ? {
|
|
867
|
+
file: inSource,
|
|
868
|
+
line: first.loc?.line ?? 1,
|
|
869
|
+
column: (first.loc?.column ?? 0) + 1
|
|
870
|
+
} : void 0;
|
|
871
|
+
const unresolved = first.code === "UNRESOLVED_IMPORT" || /\b(?:could not|failed to) resolve\b/i.test(rawMessage);
|
|
872
|
+
return createDiagnostic(unresolved ? "MOSTRA_BUILD_UNRESOLVED" : "MOSTRA_BUILD_FAILED", {
|
|
873
|
+
message: rawMessage.split("\n").slice(0, 6).join("\n"),
|
|
874
|
+
...location ? { location } : {}
|
|
875
|
+
});
|
|
876
|
+
}
|
|
877
|
+
function baseConfig(request, sourceDir, plugins) {
|
|
878
|
+
return {
|
|
879
|
+
root: request.stagingDir,
|
|
880
|
+
configFile: false,
|
|
881
|
+
envDir: false,
|
|
882
|
+
envPrefix: "MOSTRA_ARTIFACT_PUBLIC_",
|
|
883
|
+
logLevel: "warn",
|
|
884
|
+
clearScreen: false,
|
|
885
|
+
base: "/",
|
|
886
|
+
mode: "production",
|
|
887
|
+
resolve: {
|
|
888
|
+
alias: [{
|
|
889
|
+
find: /^@\//,
|
|
890
|
+
replacement: `${sourceDir}/`
|
|
891
|
+
}],
|
|
892
|
+
dedupe: ["react", "react-dom"]
|
|
893
|
+
},
|
|
894
|
+
css: { postcss: {} },
|
|
895
|
+
plugins
|
|
896
|
+
};
|
|
897
|
+
}
|
|
898
|
+
/**
|
|
899
|
+
* The real directories the build's packages and their dependencies live in: for a package in a
|
|
900
|
+
* pnpm store, the store (`.pnpm`) that holds it and its dependencies; otherwise the package's own
|
|
901
|
+
* directory (a workspace link such as `@mostra/react`), followed by the packages it depends on in
|
|
902
|
+
* turn (`@mostra/protocol`, say).
|
|
903
|
+
*/
|
|
904
|
+
async function packageRoots(nodeModules) {
|
|
905
|
+
const roots = /* @__PURE__ */ new Set();
|
|
906
|
+
const visit = async (modules) => {
|
|
907
|
+
let entries;
|
|
908
|
+
try {
|
|
909
|
+
entries = await readdir(modules, { withFileTypes: true });
|
|
910
|
+
} catch {
|
|
911
|
+
return;
|
|
912
|
+
}
|
|
913
|
+
roots.add(await realpath(modules));
|
|
914
|
+
const packages = [];
|
|
915
|
+
for (const entry of entries) {
|
|
916
|
+
if (entry.name.startsWith(".")) continue;
|
|
917
|
+
if (entry.name.startsWith("@")) for (const scoped of await readdir(join(modules, entry.name))) packages.push(join(modules, entry.name, scoped));
|
|
918
|
+
else packages.push(join(modules, entry.name));
|
|
919
|
+
}
|
|
920
|
+
for (const link of packages) {
|
|
921
|
+
let dir;
|
|
922
|
+
try {
|
|
923
|
+
dir = await realpath(link);
|
|
924
|
+
} catch {
|
|
925
|
+
continue;
|
|
926
|
+
}
|
|
927
|
+
const store = dir.lastIndexOf("/.pnpm/");
|
|
928
|
+
const root = store === -1 ? dir : dir.slice(0, store + 6);
|
|
929
|
+
if (roots.has(root)) continue;
|
|
930
|
+
roots.add(root);
|
|
931
|
+
if (store === -1) await visit(join(dir, "node_modules"));
|
|
932
|
+
}
|
|
933
|
+
};
|
|
934
|
+
await visit(nodeModules);
|
|
935
|
+
return [...roots];
|
|
936
|
+
}
|
|
937
|
+
/** Runs the SPA build of `request`. */
|
|
938
|
+
async function buildSpa(input) {
|
|
939
|
+
const request = {
|
|
940
|
+
...input,
|
|
941
|
+
stagingDir: await realpath(input.stagingDir)
|
|
942
|
+
};
|
|
943
|
+
const sourceDir = join(request.stagingDir, "source");
|
|
944
|
+
const scan = await scanArtifact(sourceDir);
|
|
945
|
+
if (scan.diagnostics.length > 0) return {
|
|
946
|
+
ok: false,
|
|
947
|
+
diagnostics: scan.diagnostics
|
|
948
|
+
};
|
|
949
|
+
if (!request.entryHasDefault && scan.pages.length === 0) return {
|
|
950
|
+
ok: false,
|
|
951
|
+
diagnostics: [createDiagnostic("MOSTRA_ARTIFACT_NO_PAGE", {
|
|
952
|
+
message: `${request.entry} has no default export and the artifact has no pages/ folder.`,
|
|
953
|
+
location: {
|
|
954
|
+
file: request.entry,
|
|
955
|
+
line: 1,
|
|
956
|
+
column: 1
|
|
957
|
+
}
|
|
958
|
+
})]
|
|
959
|
+
};
|
|
960
|
+
const generated = join(request.stagingDir, GENERATED);
|
|
961
|
+
await mkdir(generated, { recursive: true });
|
|
962
|
+
for (const [name, text] of Object.entries(STAGING_FILES)) await writeFile(join(request.stagingDir, name), text);
|
|
963
|
+
const inputs = {
|
|
964
|
+
sourceDir,
|
|
965
|
+
generatedDir: generated,
|
|
966
|
+
packageRoots: await packageRoots(request.nodeModules)
|
|
967
|
+
};
|
|
968
|
+
await rm(join(request.stagingDir, "node_modules"), {
|
|
969
|
+
force: true,
|
|
970
|
+
recursive: true
|
|
971
|
+
});
|
|
972
|
+
await symlink(request.nodeModules, join(request.stagingDir, "node_modules"), "dir");
|
|
973
|
+
await writeFile(join(request.stagingDir, "index.html"), html(request.manifest.title, request.versionId));
|
|
974
|
+
await writeFile(join(generated, "entry.js"), clientEntry(request, scan));
|
|
975
|
+
await writeFile(join(generated, "styles.css"), `@import "tailwindcss" source("../source");\n`);
|
|
976
|
+
if (scan.hasLive) await writeFile(join(generated, "mostra-env.d.ts"), LIVE_DECLARATION);
|
|
977
|
+
const serverModules = new Map([...scan.serverModules].map(([module, entries]) => [join(sourceDir, module), entries]));
|
|
978
|
+
const hookUses = [];
|
|
979
|
+
let runtimeDir;
|
|
980
|
+
try {
|
|
981
|
+
runtimeDir = await realpath(join(request.nodeModules, "@mostra", "react"));
|
|
982
|
+
} catch {
|
|
983
|
+
runtimeDir = void 0;
|
|
984
|
+
}
|
|
985
|
+
try {
|
|
986
|
+
await build({
|
|
987
|
+
...baseConfig(request, sourceDir, [
|
|
988
|
+
fieldHookUsePlugin({
|
|
989
|
+
sourceDir,
|
|
990
|
+
generatedDir: generated,
|
|
991
|
+
...runtimeDir ? { runtimeDir } : {}
|
|
992
|
+
}, hookUses),
|
|
993
|
+
confinePlugin(inputs),
|
|
994
|
+
mdxPlugin(),
|
|
995
|
+
serverClientStubPlugin(serverModules, sourceDir),
|
|
996
|
+
react(),
|
|
997
|
+
tailwind()
|
|
998
|
+
]),
|
|
999
|
+
publicDir: join(sourceDir, "public"),
|
|
1000
|
+
build: {
|
|
1001
|
+
outDir: join(request.outDir, "client"),
|
|
1002
|
+
emptyOutDir: true,
|
|
1003
|
+
sourcemap: true,
|
|
1004
|
+
reportCompressedSize: false
|
|
1005
|
+
}
|
|
1006
|
+
});
|
|
1007
|
+
} catch (error) {
|
|
1008
|
+
return {
|
|
1009
|
+
ok: false,
|
|
1010
|
+
diagnostics: [diagnose(error, sourceDir)]
|
|
1011
|
+
};
|
|
1012
|
+
}
|
|
1013
|
+
const server = scan.serverModules.size > 0 || scan.hasLive;
|
|
1014
|
+
if (server) {
|
|
1015
|
+
await writeFile(join(generated, "server-entry.js"), serverEntry(scan));
|
|
1016
|
+
try {
|
|
1017
|
+
await build({
|
|
1018
|
+
...baseConfig(request, sourceDir, [
|
|
1019
|
+
confinePlugin(inputs),
|
|
1020
|
+
mdxPlugin(),
|
|
1021
|
+
react()
|
|
1022
|
+
]),
|
|
1023
|
+
publicDir: false,
|
|
1024
|
+
ssr: {
|
|
1025
|
+
external: ["@mostra/server"],
|
|
1026
|
+
target: "node"
|
|
1027
|
+
},
|
|
1028
|
+
build: {
|
|
1029
|
+
ssr: join(generated, "server-entry.js"),
|
|
1030
|
+
outDir: join(request.outDir, "server"),
|
|
1031
|
+
emptyOutDir: true,
|
|
1032
|
+
sourcemap: true,
|
|
1033
|
+
rolldownOptions: {
|
|
1034
|
+
external: ["@mostra/server"],
|
|
1035
|
+
output: {
|
|
1036
|
+
entryFileNames: "entry.mjs",
|
|
1037
|
+
format: "es"
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
});
|
|
1042
|
+
} catch (error) {
|
|
1043
|
+
return {
|
|
1044
|
+
ok: false,
|
|
1045
|
+
diagnostics: [diagnose(error, sourceDir)]
|
|
1046
|
+
};
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
return {
|
|
1050
|
+
ok: true,
|
|
1051
|
+
registry: {
|
|
1052
|
+
schemaVersion: 1,
|
|
1053
|
+
entry: request.entry,
|
|
1054
|
+
actions: [...scan.serverModules.values()].flat(),
|
|
1055
|
+
liveSources: scan.liveSources,
|
|
1056
|
+
pages: scan.pages,
|
|
1057
|
+
terminals: Object.keys(request.manifest.terminals ?? {}).sort(),
|
|
1058
|
+
demos: Object.keys(request.manifest.demos ?? {}).sort(),
|
|
1059
|
+
fields: withPackageUses(scan.fields, hookUses)
|
|
1060
|
+
},
|
|
1061
|
+
server
|
|
1062
|
+
};
|
|
1063
|
+
}
|
|
1064
|
+
//#endregion
|
|
1065
|
+
//#region src/builder/child/dev.ts
|
|
1066
|
+
/**
|
|
1067
|
+
* `mostra dev`'s server (D140 item 12, VR-08): Vite in middleware mode over the dev root, whose
|
|
1068
|
+
* `source/` the supervisor keeps a mirror of the artifact's source, with the SPA build's own
|
|
1069
|
+
* plugins, so a page in dev is built as its published version would be. It listens on a loopback
|
|
1070
|
+
* port the operating system picks and answers only requests that carry the session's secret,
|
|
1071
|
+
* which only the dev sandbox's gateway sends: a browser reaches it only through the gateway's
|
|
1072
|
+
* route table (Host, Origin, session), never directly, and never through a capability URL of the
|
|
1073
|
+
* home. Its HMR WebSocket is served through the same check, on Vite's own token and allowed hosts.
|
|
1074
|
+
*
|
|
1075
|
+
* When the source changes, Vite updates client modules in place (HMR). When the artifact has
|
|
1076
|
+
* server code, the server bundle and `registry.json` are built again and the supervisor told
|
|
1077
|
+
* (`builder/dev.server`); once it runs the new bundle, it asks the child to reload every page.
|
|
1078
|
+
* When `pages/`, `"use server"` modules or `live.ts` change, the generated entry is written again.
|
|
1079
|
+
*/
|
|
1080
|
+
/** The custom HMR event a dev page sends with the time it was served. */
|
|
1081
|
+
const LOADED_EVENT = "mostra:dev.loaded";
|
|
1082
|
+
/** Whether a request carries the session's secret (compared in constant time). */
|
|
1083
|
+
function hasSecret(headers, secret) {
|
|
1084
|
+
const given = headers[DEV_SECRET_HEADER];
|
|
1085
|
+
if (typeof given !== "string") return false;
|
|
1086
|
+
const a = Buffer.from(given);
|
|
1087
|
+
const b = Buffer.from(secret);
|
|
1088
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
1089
|
+
}
|
|
1090
|
+
/** What the server entry depends on: which server modules, functions and live sources exist. */
|
|
1091
|
+
function serverShape(scan) {
|
|
1092
|
+
return JSON.stringify({
|
|
1093
|
+
modules: [...scan.serverModules].map(([module, entries]) => [module, entries.map((e) => e.id)]),
|
|
1094
|
+
live: scan.hasLive
|
|
1095
|
+
});
|
|
1096
|
+
}
|
|
1097
|
+
/** What the client entry depends on: the pages. */
|
|
1098
|
+
const pageShape = (scan) => JSON.stringify(scan.pages);
|
|
1099
|
+
/** Starts the dev server for `request`. */
|
|
1100
|
+
async function startDev(request, supervisor) {
|
|
1101
|
+
const root = request.root;
|
|
1102
|
+
const sourceDir = join(root, "source");
|
|
1103
|
+
const generated = join(root, GENERATED);
|
|
1104
|
+
await mkdir(generated, { recursive: true });
|
|
1105
|
+
for (const [name, text] of Object.entries(STAGING_FILES)) await writeFile(join(root, name), text);
|
|
1106
|
+
await rm(join(root, "node_modules"), {
|
|
1107
|
+
force: true,
|
|
1108
|
+
recursive: true
|
|
1109
|
+
});
|
|
1110
|
+
await symlink(request.nodeModules, join(root, "node_modules"), "dir");
|
|
1111
|
+
await writeFile(join(generated, "styles.css"), `@import "tailwindcss" source("../source");\n`);
|
|
1112
|
+
await mkdir(request.outDir, { recursive: true });
|
|
1113
|
+
const viteCache = join(root, ".vite");
|
|
1114
|
+
const inputs = {
|
|
1115
|
+
sourceDir,
|
|
1116
|
+
generatedDir: generated,
|
|
1117
|
+
packageRoots: [...await packageRoots(request.nodeModules), viteCache]
|
|
1118
|
+
};
|
|
1119
|
+
let scan = await scanArtifact(sourceDir);
|
|
1120
|
+
const serverModules = /* @__PURE__ */ new Map();
|
|
1121
|
+
const refreshServerModules = () => {
|
|
1122
|
+
serverModules.clear();
|
|
1123
|
+
for (const [module, entries] of scan.serverModules) serverModules.set(join(sourceDir, module), entries);
|
|
1124
|
+
};
|
|
1125
|
+
refreshServerModules();
|
|
1126
|
+
const writeEntry = async () => {
|
|
1127
|
+
await writeFile(join(generated, "entry.js"), clientEntry(request, scan));
|
|
1128
|
+
if (scan.hasLive) await writeFile(join(generated, "mostra-env.d.ts"), LIVE_DECLARATION);
|
|
1129
|
+
};
|
|
1130
|
+
await writeEntry();
|
|
1131
|
+
await writeFile(join(generated, "dev-loaded.js"), `const served = Number(document.querySelector('meta[name="mostra-dev-served"]')?.content);\nimport.meta.hot?.send(${JSON.stringify(LOADED_EVENT)}, served);\n`);
|
|
1132
|
+
const indexHtml = html(request.manifest.title, request.versionId);
|
|
1133
|
+
/** Builds the server bundle and `registry.json` into the dev version's directory. */
|
|
1134
|
+
let lastBundle = "";
|
|
1135
|
+
const buildServer = async () => {
|
|
1136
|
+
if (scan.diagnostics.length > 0 || scan.unparsed.length > 0) return {
|
|
1137
|
+
ok: false,
|
|
1138
|
+
diagnostics: [...scan.diagnostics, ...scan.unparsed]
|
|
1139
|
+
};
|
|
1140
|
+
const server = scan.serverModules.size > 0 || scan.hasLive;
|
|
1141
|
+
if (server) {
|
|
1142
|
+
await writeFile(join(generated, "server-entry.js"), serverEntry(scan));
|
|
1143
|
+
try {
|
|
1144
|
+
await build({
|
|
1145
|
+
...baseConfig({ stagingDir: root }, sourceDir, [
|
|
1146
|
+
confinePlugin(inputs),
|
|
1147
|
+
mdxPlugin(),
|
|
1148
|
+
react()
|
|
1149
|
+
]),
|
|
1150
|
+
mode: "development",
|
|
1151
|
+
publicDir: false,
|
|
1152
|
+
ssr: {
|
|
1153
|
+
external: ["@mostra/server"],
|
|
1154
|
+
target: "node"
|
|
1155
|
+
},
|
|
1156
|
+
build: {
|
|
1157
|
+
ssr: join(generated, "server-entry.js"),
|
|
1158
|
+
outDir: join(request.outDir, "server"),
|
|
1159
|
+
emptyOutDir: true,
|
|
1160
|
+
sourcemap: true,
|
|
1161
|
+
rolldownOptions: {
|
|
1162
|
+
external: ["@mostra/server"],
|
|
1163
|
+
output: {
|
|
1164
|
+
entryFileNames: "entry.mjs",
|
|
1165
|
+
format: "es"
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
});
|
|
1170
|
+
} catch (error) {
|
|
1171
|
+
return {
|
|
1172
|
+
ok: false,
|
|
1173
|
+
diagnostics: [diagnose(error, sourceDir)]
|
|
1174
|
+
};
|
|
1175
|
+
}
|
|
1176
|
+
} else await rm(join(request.outDir, "server"), {
|
|
1177
|
+
recursive: true,
|
|
1178
|
+
force: true
|
|
1179
|
+
});
|
|
1180
|
+
lastBundle = await bundleDigest(join(request.outDir, "server"));
|
|
1181
|
+
const registry = {
|
|
1182
|
+
schemaVersion: 1,
|
|
1183
|
+
entry: request.entry,
|
|
1184
|
+
actions: [...scan.serverModules.values()].flat(),
|
|
1185
|
+
liveSources: scan.liveSources,
|
|
1186
|
+
pages: scan.pages,
|
|
1187
|
+
terminals: Object.keys(request.manifest.terminals ?? {}).sort(),
|
|
1188
|
+
demos: Object.keys(request.manifest.demos ?? {}).sort(),
|
|
1189
|
+
fields: {
|
|
1190
|
+
...scan.fields,
|
|
1191
|
+
open: true,
|
|
1192
|
+
openReasons: [{ reason: "a development preview" }]
|
|
1193
|
+
}
|
|
1194
|
+
};
|
|
1195
|
+
await writeFile(join(request.outDir, "registry.json"), `${JSON.stringify(registry, null, 2)}\n`);
|
|
1196
|
+
return {
|
|
1197
|
+
ok: true,
|
|
1198
|
+
registry,
|
|
1199
|
+
server
|
|
1200
|
+
};
|
|
1201
|
+
};
|
|
1202
|
+
const firstBuild = await buildServer();
|
|
1203
|
+
const hmrServer = createServer();
|
|
1204
|
+
const vite = await createServer$1({
|
|
1205
|
+
...baseConfig({ stagingDir: root }, sourceDir, [
|
|
1206
|
+
confinePlugin(inputs),
|
|
1207
|
+
mdxPlugin(),
|
|
1208
|
+
serverClientStubPlugin(serverModules, sourceDir),
|
|
1209
|
+
manifestExportPlugin(join(sourceDir, request.entry)),
|
|
1210
|
+
react(),
|
|
1211
|
+
tailwind()
|
|
1212
|
+
]),
|
|
1213
|
+
mode: "development",
|
|
1214
|
+
appType: "custom",
|
|
1215
|
+
cacheDir: viteCache,
|
|
1216
|
+
publicDir: join(sourceDir, "public"),
|
|
1217
|
+
server: {
|
|
1218
|
+
middlewareMode: true,
|
|
1219
|
+
ws: { server: hmrServer },
|
|
1220
|
+
watch: null,
|
|
1221
|
+
allowedHosts: ["127.0.0.1", "localhost"],
|
|
1222
|
+
cors: false,
|
|
1223
|
+
fs: {
|
|
1224
|
+
strict: true,
|
|
1225
|
+
allow: [root, ...inputs.packageRoots]
|
|
1226
|
+
}
|
|
1227
|
+
},
|
|
1228
|
+
optimizeDeps: { entries: [`${GENERATED}/entry.js`] }
|
|
1229
|
+
});
|
|
1230
|
+
let changedAt = 0;
|
|
1231
|
+
vite.ws.on(LOADED_EVENT, (served, client) => {
|
|
1232
|
+
if (typeof served === "number" && served <= changedAt) client.send({ type: "full-reload" });
|
|
1233
|
+
});
|
|
1234
|
+
const serveHtml = async (req, res) => {
|
|
1235
|
+
const served = `<meta name="mostra-dev-served" content="${Date.now()}" />`;
|
|
1236
|
+
const report = `<script type="module" src="/${GENERATED}/dev-loaded.js"><\/script>`;
|
|
1237
|
+
const page = await vite.transformIndexHtml(req.url ?? "/", indexHtml.replace("</head>", ` ${served}\n </head>`).replace("</body>", ` ${report}\n </body>`));
|
|
1238
|
+
res.writeHead(200, {
|
|
1239
|
+
"content-type": "text/html; charset=utf-8",
|
|
1240
|
+
"cache-control": "no-cache"
|
|
1241
|
+
});
|
|
1242
|
+
res.end(page);
|
|
1243
|
+
};
|
|
1244
|
+
const http = createServer((req, res) => {
|
|
1245
|
+
if (!hasSecret(req.headers, request.secret)) {
|
|
1246
|
+
res.writeHead(403).end();
|
|
1247
|
+
return;
|
|
1248
|
+
}
|
|
1249
|
+
const path = (req.url ?? "/").split("?")[0] ?? "/";
|
|
1250
|
+
const navigation = req.headers["sec-fetch-dest"] === "document" || req.headers["sec-fetch-dest"] === "iframe" || path === "/" || path === "/index.html";
|
|
1251
|
+
if ((req.method === "GET" || req.method === "HEAD") && navigation) {
|
|
1252
|
+
serveHtml(req, res).catch((error) => {
|
|
1253
|
+
res.writeHead(500, { "content-type": "text/plain" }).end(String(error));
|
|
1254
|
+
});
|
|
1255
|
+
return;
|
|
1256
|
+
}
|
|
1257
|
+
vite.middlewares(req, res, () => {
|
|
1258
|
+
if (req.headers.accept?.includes("text/html")) {
|
|
1259
|
+
serveHtml(req, res).catch(() => res.writeHead(500).end());
|
|
1260
|
+
return;
|
|
1261
|
+
}
|
|
1262
|
+
res.writeHead(404).end();
|
|
1263
|
+
});
|
|
1264
|
+
});
|
|
1265
|
+
http.on("upgrade", (req, socket, head) => {
|
|
1266
|
+
if (!hasSecret(req.headers, request.secret)) {
|
|
1267
|
+
socket.destroy();
|
|
1268
|
+
return;
|
|
1269
|
+
}
|
|
1270
|
+
hmrServer.emit("upgrade", req, socket, head);
|
|
1271
|
+
});
|
|
1272
|
+
await new Promise((done) => http.listen(0, "127.0.0.1", done));
|
|
1273
|
+
const port = http.address().port;
|
|
1274
|
+
let running = Promise.resolve();
|
|
1275
|
+
const settle = async (changes) => {
|
|
1276
|
+
const files = changes.map((change) => change.file);
|
|
1277
|
+
changedAt = Date.now();
|
|
1278
|
+
for (const change of changes) vite.watcher.emit(change.kind, join(sourceDir, ...change.file.split("/")));
|
|
1279
|
+
const before = {
|
|
1280
|
+
pages: pageShape(scan),
|
|
1281
|
+
server: serverShape(scan)
|
|
1282
|
+
};
|
|
1283
|
+
scan = await scanArtifact(sourceDir);
|
|
1284
|
+
const serverChanged = before.server !== serverShape(scan);
|
|
1285
|
+
const pagesChanged = before.pages !== pageShape(scan);
|
|
1286
|
+
if (pagesChanged || serverChanged) {
|
|
1287
|
+
refreshServerModules();
|
|
1288
|
+
await writeEntry();
|
|
1289
|
+
vite.watcher.emit("change", join(generated, "entry.js"));
|
|
1290
|
+
if (serverChanged) vite.moduleGraph.invalidateAll();
|
|
1291
|
+
}
|
|
1292
|
+
if (pagesChanged && !serverChanged) vite.ws.send({ type: "full-reload" });
|
|
1293
|
+
if (scan.serverModules.size > 0 || scan.hasLive || scan.unparsed.length > 0 || serverChanged) {
|
|
1294
|
+
const before = lastBundle;
|
|
1295
|
+
const built = await buildServer();
|
|
1296
|
+
if (!built.ok || serverChanged || lastBundle !== before) {
|
|
1297
|
+
supervisor.notify(DEV_SERVER_NOTIFICATION, {
|
|
1298
|
+
build: built,
|
|
1299
|
+
files
|
|
1300
|
+
});
|
|
1301
|
+
return;
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
supervisor.notify(DEV_UPDATE_NOTIFICATION, { files });
|
|
1305
|
+
};
|
|
1306
|
+
return {
|
|
1307
|
+
ready: {
|
|
1308
|
+
port,
|
|
1309
|
+
build: firstBuild
|
|
1310
|
+
},
|
|
1311
|
+
changed: (changes) => {
|
|
1312
|
+
running = running.then(() => settle(changes)).catch(() => {});
|
|
1313
|
+
return running;
|
|
1314
|
+
},
|
|
1315
|
+
reload: () => vite.ws.send({ type: "full-reload" }),
|
|
1316
|
+
close: async () => {
|
|
1317
|
+
await running;
|
|
1318
|
+
http.closeAllConnections();
|
|
1319
|
+
await new Promise((done) => http.close(() => done()));
|
|
1320
|
+
await vite.close();
|
|
1321
|
+
}
|
|
1322
|
+
};
|
|
1323
|
+
}
|
|
1324
|
+
/**
|
|
1325
|
+
* Keeps React Fast Refresh working on the entry (D140 item 12): the entry exports its manifest
|
|
1326
|
+
* (`export const artifact = defineArtifact(…)`, D51), and a module that exports anything but
|
|
1327
|
+
* components can't be refreshed in place, so every edit of a single-file artifact would load the
|
|
1328
|
+
* page again. In dev only, the `export` keyword of that one declaration becomes spaces (positions
|
|
1329
|
+
* and source maps stay exact); nothing imports the manifest at run time, since Mostra reads it
|
|
1330
|
+
* statically.
|
|
1331
|
+
*/
|
|
1332
|
+
function manifestExportPlugin(entryFile) {
|
|
1333
|
+
return {
|
|
1334
|
+
name: "mostra:dev-manifest-export",
|
|
1335
|
+
enforce: "pre",
|
|
1336
|
+
transform(code, id) {
|
|
1337
|
+
if (id.split("?")[0] !== entryFile || !/\.[jt]sx$/.test(entryFile)) return null;
|
|
1338
|
+
const parsed = parseSync(entryFile, code, { lang: entryFile.endsWith(".tsx") ? "tsx" : "jsx" });
|
|
1339
|
+
if (parsed.errors.length > 0) return null;
|
|
1340
|
+
for (const statement of parsed.program.body) {
|
|
1341
|
+
if (statement.type !== "ExportNamedDeclaration") continue;
|
|
1342
|
+
const declaration = statement.declaration;
|
|
1343
|
+
if (declaration?.type !== "VariableDeclaration" || declaration.declarations.length !== 1) continue;
|
|
1344
|
+
const id = declaration.declarations[0]?.id;
|
|
1345
|
+
if (id?.type !== "Identifier" || id.name !== "artifact") continue;
|
|
1346
|
+
const blank = " ".repeat(declaration.start - statement.start);
|
|
1347
|
+
return {
|
|
1348
|
+
code: code.slice(0, statement.start) + blank + code.slice(declaration.start),
|
|
1349
|
+
map: null
|
|
1350
|
+
};
|
|
1351
|
+
}
|
|
1352
|
+
return null;
|
|
1353
|
+
}
|
|
1354
|
+
};
|
|
1355
|
+
}
|
|
1356
|
+
/** A digest of the server bundle's files, to tell a rebuild that changed nothing. */
|
|
1357
|
+
async function bundleDigest(dir) {
|
|
1358
|
+
const hash = createHash("sha256");
|
|
1359
|
+
let names;
|
|
1360
|
+
try {
|
|
1361
|
+
names = (await readdir(dir, { recursive: true })).sort();
|
|
1362
|
+
} catch {
|
|
1363
|
+
return "";
|
|
1364
|
+
}
|
|
1365
|
+
for (const name of names) {
|
|
1366
|
+
if (name.endsWith(".map")) continue;
|
|
1367
|
+
const text = await readFile(join(dir, name)).catch(() => void 0);
|
|
1368
|
+
if (text === void 0) continue;
|
|
1369
|
+
hash.update(name).update("\0").update(text).update("\0");
|
|
1370
|
+
}
|
|
1371
|
+
return hash.digest("hex");
|
|
1372
|
+
}
|
|
1373
|
+
//#endregion
|
|
1374
|
+
//#region src/builder/child/main.ts
|
|
1375
|
+
/**
|
|
1376
|
+
* The builder child's entry (`mostra-runtime`'s `dist/builder/child/main.js`, ARCHITECTURE §1): the
|
|
1377
|
+
* only process that loads Vite. The supervisor starts one per build through the process manager,
|
|
1378
|
+
* sends `builder/build` over IPC, and stops it after the answer; for `mostra dev` it starts one per
|
|
1379
|
+
* session and sends `builder/dev`, and the child serves until it is stopped (D140 item 12). It
|
|
1380
|
+
* exits with its supervisor (`connectToSupervisor`) and never runs artifact code: bundling reads
|
|
1381
|
+
* modules, it doesn't run them.
|
|
1382
|
+
*/
|
|
1383
|
+
let dev;
|
|
1384
|
+
const supervisor = connectToSupervisor({ onRequest: async (method, params) => {
|
|
1385
|
+
if (method === "builder/build") {
|
|
1386
|
+
const request = params;
|
|
1387
|
+
if (request.hang === true) return new Promise(() => {});
|
|
1388
|
+
return buildSpa(request);
|
|
1389
|
+
}
|
|
1390
|
+
if (method === "builder/dev") {
|
|
1391
|
+
if (dev) throw new Error("This builder child already serves a dev session.");
|
|
1392
|
+
dev = await startDev(params, supervisor);
|
|
1393
|
+
return dev.ready;
|
|
1394
|
+
}
|
|
1395
|
+
if (method === "builder/dev.changed") {
|
|
1396
|
+
await dev?.changed(params.changes);
|
|
1397
|
+
return {};
|
|
1398
|
+
}
|
|
1399
|
+
if (method === "builder/dev.reload") {
|
|
1400
|
+
dev?.reload();
|
|
1401
|
+
return {};
|
|
1402
|
+
}
|
|
1403
|
+
throw new Error(`The builder doesn't serve ${method}.`);
|
|
1404
|
+
} });
|
|
1405
|
+
//#endregion
|
|
1406
|
+
export {};
|
|
1407
|
+
|
|
1408
|
+
//# sourceMappingURL=main.js.map
|