@mostra/runtime 0.0.0-placeholder → 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 +38 -1
  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 -4
  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,348 @@
1
+ /**
2
+ * The SPA render mode's build (D19, ROUND-3 §7): one Vite 8 build of the client, and, when the
3
+ * artifact has `"use server"` modules or `live.ts`, one build of the server bundle the worker
4
+ * loads (WP-08). The build runs in a staging directory whose `node_modules` is a link to the warm
5
+ * set (D91) or to the artifact's lock layout (D95), so an artifact needs no `package.json` (AU-03).
6
+ * Nothing in the artifact runs.
7
+ */
8
+ import type { Dirent } from "node:fs";
9
+ import { mkdir, readdir, realpath, rm, symlink, writeFile } from "node:fs/promises";
10
+ import { join, relative } from "node:path";
11
+ import { stripVTControlCharacters } from "node:util";
12
+ import { createDiagnostic, type Diagnostic } from "@mostra/protocol";
13
+ import tailwind from "@tailwindcss/vite";
14
+ import react from "@vitejs/plugin-react";
15
+ import { build, type InlineConfig, type PluginOption } from "vite";
16
+ import type { FieldCoverage } from "../coverage.ts";
17
+ import {
18
+ type BuildRequest,
19
+ type BuildResponse,
20
+ LIVE_DECLARATION,
21
+ type ServerFunctionEntry,
22
+ STAGING_FILES,
23
+ type VersionRegistry,
24
+ } from "../types.ts";
25
+ import {
26
+ type BuildInputs,
27
+ confinePlugin,
28
+ type FieldHookUse,
29
+ fieldHookUsePlugin,
30
+ mdxPlugin,
31
+ serverClientStubPlugin,
32
+ } from "./plugins.ts";
33
+ import { type ScanResult, scanArtifact } from "./scan.ts";
34
+
35
+ /** Where generated build files live inside the staging directory (never in the snapshot). */
36
+ export const GENERATED = ".mostra-build";
37
+
38
+ export const html = (title: string, versionId: string): string =>
39
+ `<!doctype html>
40
+ <html lang="en">
41
+ <head>
42
+ <meta charset="utf-8" />
43
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
44
+ <meta name="mostra-version" content="${versionId}" />
45
+ <title>${title.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")}</title>
46
+ </head>
47
+ <body>
48
+ <div id="root"></div>
49
+ <script type="module" src="/${GENERATED}/entry.js"></script>
50
+ </body>
51
+ </html>
52
+ `;
53
+
54
+ /**
55
+ * The client entry: hands the page, or the `pages/` routes inside the entry's layout (D57), to the
56
+ * client runtime, which picks the history mode for its delivery target (D111), connects to the
57
+ * shell over the bridge, reports the current page and `mostra/ready` (SH-04), and installs
58
+ * `window.storage` (D53). A single page never loads React Router.
59
+ */
60
+ export function clientEntry(
61
+ request: Pick<BuildRequest, "entry" | "entryHasDefault">,
62
+ scan: ScanResult,
63
+ ): string {
64
+ const source = (file: string): string => JSON.stringify(`../source/${file}`);
65
+ const lines = [`import "./styles.css";`];
66
+ if (scan.pages.length === 0) {
67
+ lines.push(
68
+ `import { mountArtifact } from "@mostra/react";`,
69
+ `import Page from ${source(request.entry)};`,
70
+ `mountArtifact({ page: Page });`,
71
+ );
72
+ return `${lines.join("\n")}\n`;
73
+ }
74
+ lines.push(
75
+ `import { mountRoutes } from "@mostra/react/router";`,
76
+ request.entryHasDefault
77
+ ? `import Layout from ${source(request.entry)};`
78
+ : `import ${source(request.entry)};`,
79
+ );
80
+ for (const [index, page] of scan.pages.entries()) {
81
+ lines.push(`import Page${index} from ${source(page.file)};`);
82
+ }
83
+ const routes = scan.pages
84
+ .map((page, index) => `{ path: ${JSON.stringify(page.path)}, page: Page${index} }`)
85
+ .join(", ");
86
+ const layout = request.entryHasDefault ? ", layout: Layout" : "";
87
+ lines.push(`mountRoutes({ routes: [${routes}]${layout} });`);
88
+ return `${lines.join("\n")}\n`;
89
+ }
90
+
91
+ /** The field coverage, opened by every package outside the artifact that uses the field hooks. */
92
+ export function withPackageUses(
93
+ fields: FieldCoverage,
94
+ uses: readonly FieldHookUse[],
95
+ ): FieldCoverage {
96
+ const packageOf = (file: string): string => {
97
+ const names = [...file.matchAll(/node_modules\/((?:@[^/]+\/)?[^/]+)/g)];
98
+ return names.at(-1)?.[1] ?? file;
99
+ };
100
+ const openReasons = [
101
+ ...fields.openReasons,
102
+ ...[...new Set(uses.map((use) => packageOf(use.importer)))].map((name) => ({
103
+ reason: `the package ${name} uses @mostra/react's field hooks`,
104
+ })),
105
+ ];
106
+ return { ...fields, open: openReasons.length > 0, openReasons };
107
+ }
108
+
109
+ /** The server entry: every server function by ID, and the live sources (loaded by WP-08's worker). */
110
+ export function serverEntry(scan: ScanResult): string {
111
+ const lines: string[] = [];
112
+ const functions: string[] = [];
113
+ [...scan.serverModules.entries()].forEach(([module, entries], index) => {
114
+ lines.push(`import * as module${index} from ${JSON.stringify(`../source/${module}`)};`);
115
+ for (const entry of entries) {
116
+ functions.push(
117
+ ` ${JSON.stringify(entry.id)}: module${index}[${JSON.stringify(entry.export)}],`,
118
+ );
119
+ }
120
+ });
121
+ lines.push(`export const functions = {\n${functions.join("\n")}\n};`);
122
+ if (scan.hasLive) lines.push(`export * as live from "../source/live.ts";`);
123
+ else lines.push("export const live = {};");
124
+ return `${lines.join("\n")}\n`;
125
+ }
126
+
127
+ /** Turns a bundler error into a diagnostic with the file relative to the artifact. */
128
+ export function diagnose(error: unknown, sourceDir: string): Diagnostic {
129
+ const failure = error as {
130
+ message?: string;
131
+ code?: string;
132
+ id?: string;
133
+ loc?: { file?: string; line?: number; column?: number };
134
+ errors?: {
135
+ message?: string;
136
+ code?: string;
137
+ id?: string;
138
+ loc?: { file?: string; line?: number; column?: number };
139
+ }[];
140
+ };
141
+ const first = failure.errors?.[0] ?? failure;
142
+ // Bundler messages carry terminal colours; diagnostics are plain text.
143
+ const rawMessage = stripVTControlCharacters(first.message ?? String(error)).replaceAll(
144
+ `${sourceDir}/`,
145
+ "",
146
+ );
147
+ const file = first.loc?.file ?? first.id;
148
+ const inSource = file?.startsWith(sourceDir) ? relative(sourceDir, file) : undefined;
149
+ const location =
150
+ inSource !== undefined
151
+ ? { file: inSource, line: first.loc?.line ?? 1, column: (first.loc?.column ?? 0) + 1 }
152
+ : undefined;
153
+ const unresolved =
154
+ first.code === "UNRESOLVED_IMPORT" || /\b(?:could not|failed to) resolve\b/i.test(rawMessage);
155
+ return createDiagnostic(unresolved ? "MOSTRA_BUILD_UNRESOLVED" : "MOSTRA_BUILD_FAILED", {
156
+ message: rawMessage.split("\n").slice(0, 6).join("\n"),
157
+ ...(location ? { location } : {}),
158
+ });
159
+ }
160
+
161
+ export function baseConfig(
162
+ request: Pick<BuildRequest, "stagingDir">,
163
+ sourceDir: string,
164
+ plugins: PluginOption[],
165
+ ): InlineConfig {
166
+ return {
167
+ root: request.stagingDir,
168
+ configFile: false,
169
+ envDir: false,
170
+ // Only variables with this prefix would reach the bundle; the builder's environment has none.
171
+ envPrefix: "MOSTRA_ARTIFACT_PUBLIC_",
172
+ logLevel: "warn",
173
+ clearScreen: false,
174
+ base: "/",
175
+ mode: "production",
176
+ resolve: {
177
+ alias: [{ find: /^@\//, replacement: `${sourceDir}/` }],
178
+ dedupe: ["react", "react-dom"],
179
+ },
180
+ // Settings given here are never searched for: no PostCSS config, from anywhere above the
181
+ // home, is loaded or run (VR-01). Tailwind is a plugin of its own.
182
+ css: { postcss: {} },
183
+ plugins,
184
+ };
185
+ }
186
+
187
+ /**
188
+ * The real directories the build's packages and their dependencies live in: for a package in a
189
+ * pnpm store, the store (`.pnpm`) that holds it and its dependencies; otherwise the package's own
190
+ * directory (a workspace link such as `@mostra/react`), followed by the packages it depends on in
191
+ * turn (`@mostra/protocol`, say).
192
+ */
193
+ export async function packageRoots(nodeModules: string): Promise<string[]> {
194
+ const roots = new Set<string>();
195
+ const visit = async (modules: string): Promise<void> => {
196
+ let entries: Dirent[];
197
+ try {
198
+ entries = await readdir(modules, { withFileTypes: true });
199
+ } catch {
200
+ return;
201
+ }
202
+ roots.add(await realpath(modules));
203
+ const packages: string[] = [];
204
+ for (const entry of entries) {
205
+ if (entry.name.startsWith(".")) continue;
206
+ if (entry.name.startsWith("@")) {
207
+ for (const scoped of await readdir(join(modules, entry.name))) {
208
+ packages.push(join(modules, entry.name, scoped));
209
+ }
210
+ } else packages.push(join(modules, entry.name));
211
+ }
212
+ for (const link of packages) {
213
+ let dir: string;
214
+ try {
215
+ dir = await realpath(link);
216
+ } catch {
217
+ continue; // A dangling link brings nothing in.
218
+ }
219
+ const store = dir.lastIndexOf("/.pnpm/");
220
+ const root = store === -1 ? dir : dir.slice(0, store + "/.pnpm".length);
221
+ if (roots.has(root)) continue;
222
+ roots.add(root);
223
+ if (store === -1) await visit(join(dir, "node_modules"));
224
+ }
225
+ };
226
+ await visit(nodeModules);
227
+ return [...roots];
228
+ }
229
+
230
+ /** Runs the SPA build of `request`. */
231
+ export async function buildSpa(input: BuildRequest): Promise<BuildResponse> {
232
+ // Bundler paths are real paths; staging may sit behind a symbolic link (macOS /tmp).
233
+ const request = { ...input, stagingDir: await realpath(input.stagingDir) };
234
+ const sourceDir = join(request.stagingDir, "source");
235
+ const scan = await scanArtifact(sourceDir);
236
+ if (scan.diagnostics.length > 0) return { ok: false, diagnostics: scan.diagnostics };
237
+ if (!request.entryHasDefault && scan.pages.length === 0) {
238
+ return {
239
+ ok: false,
240
+ diagnostics: [
241
+ createDiagnostic("MOSTRA_ARTIFACT_NO_PAGE", {
242
+ message: `${request.entry} has no default export and the artifact has no pages/ folder.`,
243
+ location: { file: request.entry, line: 1, column: 1 },
244
+ }),
245
+ ],
246
+ };
247
+ }
248
+
249
+ const generated = join(request.stagingDir, GENERATED);
250
+ await mkdir(generated, { recursive: true });
251
+ for (const [name, text] of Object.entries(STAGING_FILES)) {
252
+ await writeFile(join(request.stagingDir, name), text);
253
+ }
254
+ const inputs: BuildInputs = {
255
+ sourceDir,
256
+ generatedDir: generated,
257
+ packageRoots: await packageRoots(request.nodeModules),
258
+ };
259
+ await rm(join(request.stagingDir, "node_modules"), { force: true, recursive: true });
260
+ await symlink(request.nodeModules, join(request.stagingDir, "node_modules"), "dir");
261
+ await writeFile(
262
+ join(request.stagingDir, "index.html"),
263
+ html(request.manifest.title, request.versionId),
264
+ );
265
+ await writeFile(join(generated, "entry.js"), clientEntry(request, scan));
266
+ await writeFile(join(generated, "styles.css"), `@import "tailwindcss" source("../source");\n`);
267
+ if (scan.hasLive) await writeFile(join(generated, "mostra-env.d.ts"), LIVE_DECLARATION);
268
+
269
+ const serverModules = new Map<string, readonly ServerFunctionEntry[]>(
270
+ [...scan.serverModules].map(([module, entries]) => [join(sourceDir, module), entries]),
271
+ );
272
+ // Packages that use the field hooks themselves open the version's coverage (D109).
273
+ const hookUses: FieldHookUse[] = [];
274
+ let runtimeDir: string | undefined;
275
+ try {
276
+ runtimeDir = await realpath(join(request.nodeModules, "@mostra", "react"));
277
+ } catch {
278
+ runtimeDir = undefined;
279
+ }
280
+ try {
281
+ await build({
282
+ ...baseConfig(request, sourceDir, [
283
+ fieldHookUsePlugin(
284
+ { sourceDir, generatedDir: generated, ...(runtimeDir ? { runtimeDir } : {}) },
285
+ hookUses,
286
+ ),
287
+ confinePlugin(inputs),
288
+ mdxPlugin(),
289
+ serverClientStubPlugin(serverModules, sourceDir),
290
+ react(),
291
+ tailwind(),
292
+ ]),
293
+ // The artifact's public/ is served as-is at the root (INTERFACES §2.1).
294
+ publicDir: join(sourceDir, "public"),
295
+ build: {
296
+ outDir: join(request.outDir, "client"),
297
+ emptyOutDir: true,
298
+ sourcemap: true,
299
+ reportCompressedSize: false,
300
+ },
301
+ });
302
+ } catch (error) {
303
+ return { ok: false, diagnostics: [diagnose(error, sourceDir)] };
304
+ }
305
+
306
+ const server = scan.serverModules.size > 0 || scan.hasLive;
307
+ if (server) {
308
+ await writeFile(join(generated, "server-entry.js"), serverEntry(scan));
309
+ try {
310
+ await build({
311
+ ...baseConfig(request, sourceDir, [confinePlugin(inputs), mdxPlugin(), react()]),
312
+ publicDir: false,
313
+ // Packages stay external (Vite's default for a server build, D135): the worker resolves
314
+ // them from the layout this build resolved them in (the warm set's, or the lockfile's,
315
+ // whose digest the version's identity covers), so each runs from its own directory with
316
+ // its native addons and its own files, and React exists once. The artifact's own code is
317
+ // bundled; a package Vite can't run unbundled (a linked one, or one whose entry isn't
318
+ // JavaScript) is bundled too.
319
+ ssr: { external: ["@mostra/server"], target: "node" },
320
+ build: {
321
+ ssr: join(generated, "server-entry.js"),
322
+ outDir: join(request.outDir, "server"),
323
+ emptyOutDir: true,
324
+ sourcemap: true,
325
+ rolldownOptions: {
326
+ // The worker provides @mostra/server (WP-08), its own copy, so the two share context.
327
+ external: ["@mostra/server"],
328
+ output: { entryFileNames: "entry.mjs", format: "es" },
329
+ },
330
+ },
331
+ });
332
+ } catch (error) {
333
+ return { ok: false, diagnostics: [diagnose(error, sourceDir)] };
334
+ }
335
+ }
336
+
337
+ const registry: VersionRegistry = {
338
+ schemaVersion: 1,
339
+ entry: request.entry,
340
+ actions: [...scan.serverModules.values()].flat(),
341
+ liveSources: scan.liveSources,
342
+ pages: scan.pages,
343
+ terminals: Object.keys(request.manifest.terminals ?? {}).sort(),
344
+ demos: Object.keys(request.manifest.demos ?? {}).sort(),
345
+ fields: withPackageUses(scan.fields, hookUses),
346
+ };
347
+ return { ok: true, registry, server };
348
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Field coverage (D109): which field IDs a version's code can use, as the builder's static scan
3
+ * records them in `registry.json`, and the one matcher the supervisor judges orphans with. Pure
4
+ * and free of the bundler, so the supervisor and `verify` (WP-09) can use it.
5
+ */
6
+
7
+ /** Where a field ID was found. */
8
+ export interface FieldLocation {
9
+ readonly file: string;
10
+ readonly line: number;
11
+ readonly column: number;
12
+ }
13
+
14
+ /** The client-runtime call that names a field. */
15
+ export type FieldHook = "useField" | "useChoice" | "useForm" | "storage";
16
+
17
+ /** One place the version's code names a field ID. */
18
+ export interface FieldEntry {
19
+ /** A literal field ID. Exactly one of `id` and `template` is set. */
20
+ readonly id?: string;
21
+ /**
22
+ * A template field ID: its literal parts around each `${…}` hole, so `reply.${m.id}` is
23
+ * `["reply.", ""]`. A hole stands for any text.
24
+ */
25
+ readonly template?: readonly string[];
26
+ /** The call that names it. */
27
+ readonly hook: FieldHook;
28
+ /** Its scope, when the code gives it literally; absent when unknown or the default (`viewer`). */
29
+ readonly scope?: "viewer" | "artifact";
30
+ /** Its literal `label`, `required` and `sensitive` options, for `verify` and the shell. */
31
+ readonly label?: string;
32
+ readonly required?: boolean;
33
+ readonly sensitive?: boolean;
34
+ readonly location: FieldLocation;
35
+ }
36
+
37
+ /** The fields a version covers (D109). */
38
+ export interface FieldCoverage {
39
+ /**
40
+ * `true` when the version's code can use field IDs the scan couldn't know (a computed ID, a
41
+ * hook passed around, a package that uses the hooks itself): the version then covers every
42
+ * ID, so nothing is ever orphaned by a guess.
43
+ */
44
+ readonly open: boolean;
45
+ /** Why the coverage is open, for `verify`'s hints; empty when it isn't. */
46
+ readonly openReasons: readonly { readonly reason: string; readonly location?: FieldLocation }[];
47
+ /** Every place a field ID is named, in source order. */
48
+ readonly entries: readonly FieldEntry[];
49
+ }
50
+
51
+ function escapeRegExp(text: string): string {
52
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
53
+ }
54
+
55
+ /**
56
+ * Whether a version with this coverage covers a draft field ID (D109). A version without
57
+ * coverage (built before WP-07) covers everything, as does an open one. Only entries that may be
58
+ * viewer-scoped count: an artifact-scoped field never lives in a draft.
59
+ */
60
+ export function coverageMatcher(coverage: FieldCoverage | undefined): (fieldId: string) => boolean {
61
+ if (coverage === undefined || coverage.open) return () => true;
62
+ const ids = new Set<string>();
63
+ const templates: RegExp[] = [];
64
+ for (const entry of coverage.entries) {
65
+ if (entry.scope === "artifact") continue;
66
+ if (entry.id !== undefined) ids.add(entry.id);
67
+ else if (entry.template !== undefined) {
68
+ templates.push(new RegExp(`^${entry.template.map(escapeRegExp).join("[\\s\\S]*")}$`));
69
+ }
70
+ }
71
+ return (fieldId) => ids.has(fieldId) || templates.some((pattern) => pattern.test(fieldId));
72
+ }