@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.
Files changed (114) 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-D7_UVdoN.js +15752 -0
  18. package/dist/instance-D7_UVdoN.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 +739 -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/index.ts +1209 -0
  51. package/src/gateway/integrity.ts +117 -0
  52. package/src/gateway/listener.ts +217 -0
  53. package/src/gateway/routes.ts +197 -0
  54. package/src/gateway/serve.ts +138 -0
  55. package/src/gc/index.ts +451 -0
  56. package/src/home/acquire.ts +276 -0
  57. package/src/home/index.ts +16 -0
  58. package/src/home/paths.ts +192 -0
  59. package/src/home/platform.ts +34 -0
  60. package/src/home/record.ts +76 -0
  61. package/src/home/settings.ts +113 -0
  62. package/src/index.ts +30 -0
  63. package/src/instance/index.ts +942 -0
  64. package/src/interaction/ephemeral.ts +300 -0
  65. package/src/interaction/events.ts +355 -0
  66. package/src/interaction/fields.ts +392 -0
  67. package/src/interaction/index.ts +1009 -0
  68. package/src/interaction/outbox.ts +493 -0
  69. package/src/interaction/policy.ts +26 -0
  70. package/src/interaction/results.ts +341 -0
  71. package/src/interaction/runs.ts +313 -0
  72. package/src/interaction/signals.ts +120 -0
  73. package/src/interaction/submissions.ts +585 -0
  74. package/src/interaction/subscriptions.ts +258 -0
  75. package/src/interaction/viewers.ts +173 -0
  76. package/src/interaction/wait.ts +201 -0
  77. package/src/ledger/index.ts +442 -0
  78. package/src/ledger/migrations.ts +583 -0
  79. package/src/ledger/requests.ts +105 -0
  80. package/src/ledger/types.ts +28 -0
  81. package/src/live/index.ts +573 -0
  82. package/src/log.ts +316 -0
  83. package/src/processes/child.ts +67 -0
  84. package/src/processes/environment.ts +64 -0
  85. package/src/processes/identity.ts +191 -0
  86. package/src/processes/index.ts +19 -0
  87. package/src/processes/manager.ts +543 -0
  88. package/src/protocol-server/client.ts +94 -0
  89. package/src/protocol-server/index.ts +91 -0
  90. package/src/protocol-server/server.ts +509 -0
  91. package/src/protocol-server/streams.ts +81 -0
  92. package/src/publish/checks.ts +92 -0
  93. package/src/publish/digest.ts +87 -0
  94. package/src/publish/index.ts +23 -0
  95. package/src/publish/manifest.ts +409 -0
  96. package/src/publish/methods.ts +96 -0
  97. package/src/publish/publisher.ts +913 -0
  98. package/src/publish/source.ts +272 -0
  99. package/src/publish/tar.ts +110 -0
  100. package/src/registry/index.ts +481 -0
  101. package/src/registry/store.ts +136 -0
  102. package/src/secrets/index.ts +223 -0
  103. package/src/service/idle.ts +64 -0
  104. package/src/service/index.ts +3 -0
  105. package/src/service/unit.ts +250 -0
  106. package/src/verify/fields.ts +125 -0
  107. package/src/verify/index.ts +913 -0
  108. package/src/verify/regression.ts +157 -0
  109. package/src/verify/runner.ts +230 -0
  110. package/src/verify/sandbox.ts +407 -0
  111. package/src/verify/typecheck.ts +371 -0
  112. package/src/workers/index.ts +17 -0
  113. package/src/workers/launcher.ts +260 -0
  114. package/src/workers/pool.ts +708 -0
@@ -0,0 +1,92 @@
1
+ /**
2
+ * `instance/check` (D140 item 18): the checks only the supervisor can run, because it holds the
3
+ * ledger's lock (D81). `mostra doctor` shows them beside the checks the CLI runs itself.
4
+ */
5
+ import { existsSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { createDiagnostic, type InstanceCheck, RpcError } from "@mostra/protocol";
8
+ import type { Ledger } from "../ledger/index.ts";
9
+ import type { Registry } from "../registry/index.ts";
10
+ import { versionDamage } from "./publisher.ts";
11
+
12
+ /** What the checks read. */
13
+ export interface InstanceCheckInputs {
14
+ /** Also hash every version against its output digest. */
15
+ readonly deep: boolean;
16
+ readonly ledger: Ledger;
17
+ readonly registry: Registry;
18
+ /** The shell's built files, when the runtime found them. */
19
+ readonly shellDir: string | undefined;
20
+ /** Finds the warm set; throws `MOSTRA_ENV_WARM_MISSING` when it is incomplete. */
21
+ readonly warm: () => unknown;
22
+ }
23
+
24
+ /** Runs the checks in order: the ledger, the version store, the shell, the warm set. */
25
+ export async function instanceChecks(inputs: InstanceCheckInputs): Promise<InstanceCheck[]> {
26
+ const checks: InstanceCheck[] = [];
27
+ const integrity = inputs.ledger.checkIntegrity();
28
+ checks.push(
29
+ integrity.ok
30
+ ? { name: "ledger", status: "ok" }
31
+ : {
32
+ name: "ledger",
33
+ status: "error",
34
+ diagnostic: createDiagnostic("MOSTRA_HOME_LEDGER_UNREADABLE", {
35
+ message: `SQLite's integrity check of the ledger failed: ${integrity.problems.slice(0, 3).join("; ")}.`,
36
+ }),
37
+ },
38
+ );
39
+ // Collected versions have no files by design (D140 item 14); every other version must.
40
+ const versions = inputs.ledger.read((db) =>
41
+ db.all<{ id: string; number: number; artifact_id: string }>(
42
+ "SELECT id, number, artifact_id FROM version WHERE id NOT IN (SELECT version_id FROM version_collected) ORDER BY artifact_id, number",
43
+ ),
44
+ );
45
+ const damaged: string[] = [];
46
+ for (const version of versions) {
47
+ const dir = inputs.registry.store.versionDir(version.id);
48
+ const damage = inputs.deep
49
+ ? await versionDamage(dir)
50
+ : existsSync(join(dir, "manifest.json"))
51
+ ? undefined
52
+ : "its files are missing";
53
+ if (damage !== undefined)
54
+ damaged.push(`${version.artifact_id} version ${version.number}: ${damage}`);
55
+ }
56
+ checks.push(
57
+ damaged.length === 0
58
+ ? { name: "versions", status: "ok" }
59
+ : {
60
+ name: "versions",
61
+ status: "error",
62
+ diagnostic: createDiagnostic("MOSTRA_HOME_INTEGRITY", {
63
+ message: `${damaged.length} published ${damaged.length === 1 ? "version is" : "versions are"} damaged: ${damaged.slice(0, 3).join("; ")}${damaged.length > 3 ? " …" : ""}.`,
64
+ }),
65
+ },
66
+ );
67
+ checks.push(
68
+ inputs.shellDir !== undefined
69
+ ? { name: "shell", status: "ok" }
70
+ : {
71
+ name: "shell",
72
+ status: "error",
73
+ diagnostic: createDiagnostic("MOSTRA_ENV_SHELL_MISSING", {
74
+ message: "The runtime has no built shell, so no capability link can open.",
75
+ }),
76
+ },
77
+ );
78
+ try {
79
+ inputs.warm();
80
+ checks.push({ name: "warm", status: "ok" });
81
+ } catch (error) {
82
+ checks.push({
83
+ name: "warm",
84
+ status: "error",
85
+ diagnostic:
86
+ error instanceof RpcError
87
+ ? error.diagnostic
88
+ : createDiagnostic("MOSTRA_ENV_WARM_MISSING", { message: String(error) }),
89
+ });
90
+ }
91
+ return checks;
92
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Identity and digests (DATA_MODEL §2, D77, D89). Pure functions over bytes and listings; the
3
+ * snapshot module feeds them files, and publish combines them into the version ID.
4
+ */
5
+ import { createHash } from "node:crypto";
6
+ import { VersionId } from "@mostra/protocol";
7
+
8
+ /** One file of a canonical listing. */
9
+ export interface ListedFile {
10
+ /** Relative, `/`-separated, NFC path. */
11
+ readonly path: string;
12
+ /** Whether any execute bit is set. */
13
+ readonly executable: boolean;
14
+ /** SHA-256 of the file's bytes, lowercase hex. */
15
+ readonly sha256: string;
16
+ }
17
+
18
+ /** The environment a version is built in; its canonical JSON's SHA-256 is `envDigest`. */
19
+ export interface BuildEnvironment {
20
+ readonly mostraVersion: string;
21
+ /** The kit's release, or `null` while the runtime ships no kit (WP-18). */
22
+ readonly kitVersion: string | null;
23
+ readonly kitBase: "base" | "radix";
24
+ readonly mode: "spa";
25
+ /** SHA-256 of the frozen lockfile (`lock.yaml`). */
26
+ readonly lockDigest: string;
27
+ /** SHA-256 of the render mode's build settings and target list. */
28
+ readonly buildConfigDigest: string;
29
+ /** The browser protocol revision the client runtime speaks, or `null` before WP-07 defines it. */
30
+ readonly browserProtocolRevision: string | null;
31
+ }
32
+
33
+ /** SHA-256 as lowercase hex. */
34
+ export function sha256Hex(data: string | Uint8Array): string {
35
+ return createHash("sha256").update(data).digest("hex");
36
+ }
37
+
38
+ /**
39
+ * Canonical JSON (RFC 8785 for the values Mostra hashes: objects with string keys, arrays,
40
+ * strings, finite numbers, booleans and null): keys sorted by UTF-16 code units, no whitespace.
41
+ */
42
+ export function canonicalJson(value: unknown): string {
43
+ if (value === null || typeof value !== "object") {
44
+ if (typeof value === "number" && !Number.isFinite(value)) {
45
+ throw new TypeError("Canonical JSON has no representation for a non-finite number.");
46
+ }
47
+ if (value === undefined) throw new TypeError("Canonical JSON has no undefined.");
48
+ return JSON.stringify(value);
49
+ }
50
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
51
+ const entries = Object.entries(value as Record<string, unknown>)
52
+ .filter(([, item]) => item !== undefined)
53
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
54
+ return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`).join(",")}}`;
55
+ }
56
+
57
+ /** Orders paths by their UTF-8 bytes, so the listing is the same on every platform. */
58
+ function byUtf8(a: string, b: string): number {
59
+ return Buffer.compare(Buffer.from(a, "utf8"), Buffer.from(b, "utf8"));
60
+ }
61
+
62
+ /**
63
+ * The SHA-256 of a tree's canonical listing (DATA_MODEL §2): the JSON array of
64
+ * `[path, executable, sha256]` for every file, sorted by the path's UTF-8 bytes.
65
+ */
66
+ export function listingDigest(files: readonly ListedFile[]): string {
67
+ const sorted = [...files].sort((a, b) => byUtf8(a.path, b.path));
68
+ return sha256Hex(JSON.stringify(sorted.map((file) => [file.path, file.executable, file.sha256])));
69
+ }
70
+
71
+ /** `envDigest`: the SHA-256 of the environment's canonical JSON. */
72
+ export function environmentDigest(environment: BuildEnvironment): string {
73
+ return sha256Hex(canonicalJson(environment));
74
+ }
75
+
76
+ /**
77
+ * The version ID (D89): SHA-256 over the artifact ID's UTF-8 bytes, one `0x00` byte, then the
78
+ * 32 bytes of `sourceDigest` and of `envDigest`, encoded by `VersionId.fromSha256` (D77).
79
+ */
80
+ export function versionIdFor(artifactId: string, sourceDigest: string, envDigest: string): string {
81
+ const hash = createHash("sha256");
82
+ hash.update(Buffer.from(artifactId, "utf8"));
83
+ hash.update(Buffer.from([0]));
84
+ hash.update(Buffer.from(sourceDigest, "hex"));
85
+ hash.update(Buffer.from(envDigest, "hex"));
86
+ return VersionId.fromSha256(new Uint8Array(hash.digest()));
87
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Publish (ARCHITECTURE §3, VR-01, VR-02, VR-11): snapshots, digests, the source archive and the
3
+ * atomic publish pipeline, and the authoring methods of the host protocol.
4
+ */
5
+
6
+ export { instanceChecks } from "./checks.ts";
7
+ export {
8
+ canonicalJson,
9
+ environmentDigest,
10
+ listingDigest,
11
+ sha256Hex,
12
+ versionIdFor,
13
+ } from "./digest.ts";
14
+ export { extractManifest } from "./manifest.ts";
15
+ export { artifactMethods, canonicalRef } from "./methods.ts";
16
+ export {
17
+ createPublisher,
18
+ type Publisher,
19
+ versionDamage,
20
+ versionOutputDigest,
21
+ } from "./publisher.ts";
22
+ export { listSource, type ResolvedSource, resolveSource } from "./source.ts";
23
+ export { readTar } from "./tar.ts";
@@ -0,0 +1,409 @@
1
+ /**
2
+ * Static manifest extraction (D51, AU-07): reads an entry's manifest without running any of the
3
+ * artifact's code. A TSX or JSX entry is parsed with Oxc and its `export const artifact =
4
+ * defineArtifact({...})` is read as a literal; an MDX entry's YAML frontmatter is the manifest.
5
+ * Values that need evaluation are `MOSTRA_MANIFEST_NOT_LITERAL`; values the manifest doesn't allow
6
+ * are `MOSTRA_MANIFEST_INVALID`; unknown keys are `MOSTRA_MANIFEST_UNKNOWN_KEY` warnings.
7
+ */
8
+
9
+ import { createRequire } from "node:module";
10
+ import {
11
+ ARTIFACT_MANIFEST_KEYS,
12
+ ArtifactManifest,
13
+ createDiagnostic,
14
+ type Diagnostic,
15
+ RpcError,
16
+ } from "@mostra/protocol";
17
+ import type * as Oxc from "oxc-parser";
18
+ import { parseDocument } from "yaml";
19
+
20
+ let oxc: typeof Oxc | undefined;
21
+ /**
22
+ * Loads the native parser on first use: importing this module loads no native code, so the
23
+ * platform gate answers before anything platform-specific loads (RT-07), as the ledger does.
24
+ */
25
+ function parser(): typeof Oxc {
26
+ oxc ??= createRequire(import.meta.url)("oxc-parser") as typeof Oxc;
27
+ return oxc;
28
+ }
29
+
30
+ /** What an entry declares. */
31
+ export interface ExtractedManifest {
32
+ /** The validated manifest, or `undefined` when the entry declares none (defaults apply). */
33
+ readonly manifest: ArtifactManifest | undefined;
34
+ /** Whether the entry has a default export (the page, or with `pages/` the layout). */
35
+ readonly hasDefaultExport: boolean;
36
+ /** Warnings, such as unknown keys. */
37
+ readonly warnings: readonly Diagnostic[];
38
+ }
39
+
40
+ interface Node {
41
+ readonly type: string;
42
+ readonly start: number;
43
+ readonly end: number;
44
+ readonly [key: string]: unknown;
45
+ }
46
+
47
+ const REACT_PACKAGE = "@mostra/react";
48
+
49
+ /** Line and column (1-based) of a UTF-16 offset. */
50
+ function position(text: string, offset: number): { line: number; column: number } {
51
+ let line = 1;
52
+ let lineStart = 0;
53
+ for (
54
+ let index = text.indexOf("\n");
55
+ index !== -1 && index < offset;
56
+ index = text.indexOf("\n", index + 1)
57
+ ) {
58
+ line += 1;
59
+ lineStart = index + 1;
60
+ }
61
+ return { line, column: offset - lineStart + 1 };
62
+ }
63
+
64
+ class Extraction {
65
+ readonly file: string;
66
+ readonly text: string;
67
+
68
+ constructor(file: string, text: string) {
69
+ this.file = file;
70
+ this.text = text;
71
+ }
72
+
73
+ fail(
74
+ code: "MOSTRA_MANIFEST_NOT_LITERAL" | "MOSTRA_MANIFEST_INVALID" | "MOSTRA_BUILD_FAILED",
75
+ message: string,
76
+ offset: number,
77
+ ): never {
78
+ throw new RpcError(
79
+ createDiagnostic(code, {
80
+ message,
81
+ location: { file: this.file, ...position(this.text, offset) },
82
+ }),
83
+ );
84
+ }
85
+ }
86
+
87
+ /** Unwraps `( … )`, `x as const`, `x satisfies T` and `x!`. */
88
+ function unwrap(node: Node): Node {
89
+ let current = node;
90
+ while (
91
+ current.type === "ParenthesizedExpression" ||
92
+ current.type === "TSAsExpression" ||
93
+ current.type === "TSSatisfiesExpression" ||
94
+ current.type === "TSNonNullExpression"
95
+ ) {
96
+ current = current["expression"] as Node;
97
+ }
98
+ return current;
99
+ }
100
+
101
+ /** Converts a literal expression to its value, or fails with NOT_LITERAL at the first value that isn't one. */
102
+ function literal(node: Node, x: Extraction): unknown {
103
+ const value = unwrap(node);
104
+ switch (value.type) {
105
+ case "Literal": {
106
+ const raw = value["value"];
107
+ if (value["regex"] !== undefined || typeof raw === "bigint") {
108
+ return x.fail(
109
+ "MOSTRA_MANIFEST_NOT_LITERAL",
110
+ "A regular expression or BigInt isn't a manifest value.",
111
+ value.start,
112
+ );
113
+ }
114
+ return raw;
115
+ }
116
+ case "TemplateLiteral": {
117
+ const expressions = value["expressions"] as Node[];
118
+ if (expressions.length > 0) {
119
+ return x.fail(
120
+ "MOSTRA_MANIFEST_NOT_LITERAL",
121
+ "A template literal with a placeholder needs evaluation; write the string itself.",
122
+ value.start,
123
+ );
124
+ }
125
+ const [quasi] = value["quasis"] as { value: { cooked: string } }[];
126
+ return quasi?.value.cooked ?? "";
127
+ }
128
+ case "UnaryExpression": {
129
+ const argument = unwrap(value["argument"] as Node);
130
+ if (
131
+ (value["operator"] === "-" || value["operator"] === "+") &&
132
+ argument.type === "Literal" &&
133
+ typeof argument["value"] === "number"
134
+ ) {
135
+ return value["operator"] === "-" ? -argument["value"] : argument["value"];
136
+ }
137
+ return x.fail(
138
+ "MOSTRA_MANIFEST_NOT_LITERAL",
139
+ "Only a sign in front of a number is allowed.",
140
+ value.start,
141
+ );
142
+ }
143
+ case "ArrayExpression":
144
+ return (value["elements"] as (Node | null)[]).map((element) => {
145
+ if (element === null || element.type === "SpreadElement") {
146
+ return x.fail(
147
+ "MOSTRA_MANIFEST_NOT_LITERAL",
148
+ "Arrays in the manifest list their items: no holes or spreads.",
149
+ element?.start ?? value.start,
150
+ );
151
+ }
152
+ return literal(element, x);
153
+ });
154
+ case "ObjectExpression": {
155
+ const result: Record<string, unknown> = {};
156
+ for (const property of value["properties"] as Node[]) {
157
+ if (
158
+ property.type !== "Property" ||
159
+ property["computed"] ||
160
+ property["method"] ||
161
+ property["kind"] !== "init"
162
+ ) {
163
+ return x.fail(
164
+ "MOSTRA_MANIFEST_NOT_LITERAL",
165
+ property.type === "SpreadElement"
166
+ ? "A spread needs evaluation; write the properties out."
167
+ : "Manifest objects have plain `key: value` properties: no computed keys, methods or accessors.",
168
+ property.start,
169
+ );
170
+ }
171
+ if (property["shorthand"]) {
172
+ return x.fail(
173
+ "MOSTRA_MANIFEST_NOT_LITERAL",
174
+ "A shorthand property refers to a variable; write its value.",
175
+ property.start,
176
+ );
177
+ }
178
+ const key = property["key"] as Node;
179
+ const name =
180
+ key.type === "Identifier"
181
+ ? (key["name"] as string)
182
+ : key.type === "Literal"
183
+ ? String(key["value"])
184
+ : undefined;
185
+ if (name === undefined) {
186
+ return x.fail(
187
+ "MOSTRA_MANIFEST_NOT_LITERAL",
188
+ "Property names must be plain names or strings.",
189
+ key.start,
190
+ );
191
+ }
192
+ result[name] = literal(property["value"] as Node, x);
193
+ }
194
+ return result;
195
+ }
196
+ default:
197
+ return x.fail(
198
+ "MOSTRA_MANIFEST_NOT_LITERAL",
199
+ value.type === "Identifier"
200
+ ? `\`${String(value["name"])}\` is a variable; Mostra reads the manifest without running code, so write its value.`
201
+ : "This value needs evaluation; Mostra reads the manifest without running code, so write it as a literal.",
202
+ value.start,
203
+ );
204
+ }
205
+ }
206
+
207
+ interface ModuleFacts {
208
+ /** The node exported as `artifact`, if any: the initializer of the exported (or re-exported) const. */
209
+ readonly artifact: { readonly init: Node | undefined; readonly at: number } | undefined;
210
+ readonly hasDefaultExport: boolean;
211
+ /** Local names bound to `defineArtifact` from `@mostra/react`. */
212
+ readonly defineArtifact: ReadonlySet<string>;
213
+ /** Local namespace names of `@mostra/react`. */
214
+ readonly namespaces: ReadonlySet<string>;
215
+ }
216
+
217
+ function moduleFacts(program: Node): ModuleFacts {
218
+ const body = program["body"] as Node[];
219
+ const defineNames = new Set<string>();
220
+ const namespaces = new Set<string>();
221
+ const locals = new Map<string, { init: Node | undefined; at: number; constant: boolean }>();
222
+ let artifact: ModuleFacts["artifact"];
223
+ let hasDefaultExport = false;
224
+ let exportedLocal: { name: string; at: number } | undefined;
225
+
226
+ const declare = (declaration: Node, exported: boolean): void => {
227
+ if (declaration.type !== "VariableDeclaration") return;
228
+ for (const declarator of declaration["declarations"] as Node[]) {
229
+ const id = declarator["id"] as Node;
230
+ if (id.type !== "Identifier") continue;
231
+ const entry = {
232
+ init: (declarator["init"] as Node | null) ?? undefined,
233
+ at: declarator.start,
234
+ constant: declaration["kind"] === "const",
235
+ };
236
+ locals.set(id["name"] as string, entry);
237
+ if (exported && id["name"] === "artifact")
238
+ artifact = { init: entry.constant ? entry.init : undefined, at: entry.at };
239
+ }
240
+ };
241
+
242
+ for (const statement of body) {
243
+ if (
244
+ statement.type === "ImportDeclaration" &&
245
+ (statement["source"] as Node)["value"] === REACT_PACKAGE
246
+ ) {
247
+ for (const specifier of statement["specifiers"] as Node[]) {
248
+ const local = (specifier["local"] as Node)["name"] as string;
249
+ if (specifier.type === "ImportNamespaceSpecifier") namespaces.add(local);
250
+ if (specifier.type === "ImportSpecifier") {
251
+ const imported = specifier["imported"] as Node;
252
+ if ((imported["name"] ?? imported["value"]) === "defineArtifact") defineNames.add(local);
253
+ }
254
+ }
255
+ } else if (statement.type === "ExportDefaultDeclaration") {
256
+ hasDefaultExport = true;
257
+ } else if (statement.type === "ExportNamedDeclaration") {
258
+ const declaration = statement["declaration"] as Node | null;
259
+ if (declaration) declare(declaration, true);
260
+ for (const specifier of (statement["specifiers"] as Node[]) ?? []) {
261
+ const exported = specifier["exported"] as Node;
262
+ const name = (exported["name"] ?? exported["value"]) as string;
263
+ const local = (specifier["local"] as Node)["name"] as string;
264
+ if (name === "default") hasDefaultExport = true;
265
+ if (name === "artifact") {
266
+ if (statement["source"]) artifact = { init: undefined, at: specifier.start };
267
+ else exportedLocal = { name: local, at: specifier.start };
268
+ }
269
+ }
270
+ } else {
271
+ declare(statement, false);
272
+ }
273
+ }
274
+ if (exportedLocal) {
275
+ const local = locals.get(exportedLocal.name);
276
+ artifact = {
277
+ init: local?.constant ? local.init : undefined,
278
+ at: local?.at ?? exportedLocal.at,
279
+ };
280
+ }
281
+ return { artifact, hasDefaultExport, defineArtifact: defineNames, namespaces };
282
+ }
283
+
284
+ /** Validates an extracted object as a manifest, with unknown keys as warnings. */
285
+ function validate(
286
+ raw: unknown,
287
+ x: Extraction,
288
+ at: number,
289
+ ): { manifest: ArtifactManifest; warnings: Diagnostic[] } {
290
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
291
+ return x.fail(
292
+ "MOSTRA_MANIFEST_INVALID",
293
+ "The manifest must be an object with at least a title.",
294
+ at,
295
+ );
296
+ }
297
+ const warnings: Diagnostic[] = [];
298
+ const known = new Set<string>(ARTIFACT_MANIFEST_KEYS);
299
+ for (const key of Object.keys(raw)) {
300
+ if (!known.has(key)) {
301
+ warnings.push(
302
+ createDiagnostic("MOSTRA_MANIFEST_UNKNOWN_KEY", {
303
+ message: `The manifest key \`${key}\` isn't one this Mostra release knows; it is ignored.`,
304
+ location: { file: x.file, ...position(x.text, at) },
305
+ }),
306
+ );
307
+ }
308
+ }
309
+ const checked = ArtifactManifest.safeParse(raw);
310
+ if (!checked.success) {
311
+ const issue = checked.error.issues[0];
312
+ const path = issue?.path.join(".") || "(manifest)";
313
+ return x.fail(
314
+ "MOSTRA_MANIFEST_INVALID",
315
+ `The manifest field \`${path}\` is invalid: ${issue?.message ?? "unexpected value"}.`,
316
+ at,
317
+ );
318
+ }
319
+ return { manifest: checked.data, warnings };
320
+ }
321
+
322
+ function extractScript(file: string, text: string): ExtractedManifest {
323
+ const x = new Extraction(file, text);
324
+ const parsed = parser().parseSync(file, text, { lang: file.endsWith(".jsx") ? "jsx" : "tsx" });
325
+ const [error] = parsed.errors;
326
+ if (error) {
327
+ return x.fail(
328
+ "MOSTRA_BUILD_FAILED",
329
+ `${error.message} in ${file}.`,
330
+ error.labels[0]?.start ?? 0,
331
+ );
332
+ }
333
+ const facts = moduleFacts(parsed.program as unknown as Node);
334
+ if (facts.artifact === undefined) {
335
+ return { manifest: undefined, hasDefaultExport: facts.hasDefaultExport, warnings: [] };
336
+ }
337
+ const { init, at } = facts.artifact;
338
+ if (init === undefined) {
339
+ return x.fail(
340
+ "MOSTRA_MANIFEST_NOT_LITERAL",
341
+ "Declare the manifest as `export const artifact = defineArtifact({ ... })` so Mostra can read it without running code.",
342
+ at,
343
+ );
344
+ }
345
+ const call = unwrap(init);
346
+ const callee = call.type === "CallExpression" ? unwrap(call["callee"] as Node) : undefined;
347
+ const isDefineArtifact =
348
+ callee !== undefined &&
349
+ ((callee.type === "Identifier" && facts.defineArtifact.has(callee["name"] as string)) ||
350
+ (callee.type === "MemberExpression" &&
351
+ !callee["computed"] &&
352
+ (callee["object"] as Node).type === "Identifier" &&
353
+ facts.namespaces.has((callee["object"] as Node)["name"] as string) &&
354
+ (callee["property"] as Node)["name"] === "defineArtifact"));
355
+ if (callee?.type === "Identifier" && callee["name"] === "defineArtifact" && !isDefineArtifact) {
356
+ return x.fail(
357
+ "MOSTRA_MANIFEST_INVALID",
358
+ '`defineArtifact` isn\'t imported: add `import { defineArtifact } from "@mostra/react"`.',
359
+ call.start,
360
+ );
361
+ }
362
+ const args = call["arguments"] as Node[] | undefined;
363
+ const [argument] = args ?? [];
364
+ if (
365
+ !isDefineArtifact ||
366
+ args?.length !== 1 ||
367
+ argument === undefined ||
368
+ unwrap(argument).type !== "ObjectExpression"
369
+ ) {
370
+ return x.fail(
371
+ "MOSTRA_MANIFEST_NOT_LITERAL",
372
+ "The exported `artifact` must be `defineArtifact({ ... })` with one object literal.",
373
+ call.start,
374
+ );
375
+ }
376
+ const { manifest, warnings } = validate(literal(argument, x), x, argument.start);
377
+ return { manifest, hasDefaultExport: facts.hasDefaultExport, warnings };
378
+ }
379
+
380
+ /** An MDX entry's frontmatter: a `---` fenced YAML block on the first line. */
381
+ function extractFrontmatter(file: string, text: string): ExtractedManifest {
382
+ const x = new Extraction(file, text);
383
+ const match = /^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(text);
384
+ if (!match) return { manifest: undefined, hasDefaultExport: true, warnings: [] };
385
+ const yamlText = match[1] ?? "";
386
+ const document = parseDocument(yamlText, { prettyErrors: false, uniqueKeys: true });
387
+ const [error] = document.errors;
388
+ if (error) {
389
+ const offset = 4 + (error.pos[0] ?? 0);
390
+ return x.fail(
391
+ "MOSTRA_MANIFEST_INVALID",
392
+ `The frontmatter isn't valid YAML: ${error.message.split("\n")[0]}`,
393
+ offset,
394
+ );
395
+ }
396
+ const raw = document.toJS() as unknown;
397
+ if (raw === null || raw === undefined)
398
+ return { manifest: undefined, hasDefaultExport: true, warnings: [] };
399
+ const { manifest, warnings } = validate(raw, x, 0);
400
+ return { manifest, hasDefaultExport: true, warnings };
401
+ }
402
+
403
+ /**
404
+ * Reads the manifest of an entry file's `text`. `file` is the entry's path inside the artifact,
405
+ * used for the language and in diagnostics' locations.
406
+ */
407
+ export function extractManifest(file: string, text: string): ExtractedManifest {
408
+ return file.endsWith(".mdx") ? extractFrontmatter(file, text) : extractScript(file, text);
409
+ }