@mostra/runtime 0.14.0 → 0.15.1

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 (61) hide show
  1. package/dist/bin.js +1 -1
  2. package/dist/child-protocol-CPXR6pMu.js +13 -0
  3. package/dist/child-protocol-CPXR6pMu.js.map +1 -0
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +1 -1
  6. package/dist/{instance-CFTw3g-c.js → instance-Bw1BxctF.js} +2581 -189
  7. package/dist/instance-Bw1BxctF.js.map +1 -0
  8. package/dist/plugins/child/host.d.ts +1 -0
  9. package/dist/plugins/child/host.js +165 -0
  10. package/dist/plugins/child/host.js.map +1 -0
  11. package/dist/reference/cli.md +147 -5
  12. package/dist/reference/diagnostics.json +234 -0
  13. package/dist/reference/errors/MOSTRA_LICENSE_ACCEPT_INVALID.md +23 -0
  14. package/dist/reference/errors/MOSTRA_LICENSE_MISMATCH.md +23 -0
  15. package/dist/reference/errors/MOSTRA_LICENSE_UNACCEPTED.md +23 -0
  16. package/dist/reference/errors/MOSTRA_LICENSE_UNDECLARED.md +23 -0
  17. package/dist/reference/errors/MOSTRA_PACK_ADDRESS_INVALID.md +23 -0
  18. package/dist/reference/errors/MOSTRA_PACK_CSS_UNIMPORTED.md +23 -0
  19. package/dist/reference/errors/MOSTRA_PACK_FETCH_FAILED.md +23 -0
  20. package/dist/reference/errors/MOSTRA_PACK_FILE_EXISTS.md +23 -0
  21. package/dist/reference/errors/MOSTRA_PACK_ITEM_INVALID.md +23 -0
  22. package/dist/reference/errors/MOSTRA_PACK_ITEM_NOT_FOUND.md +23 -0
  23. package/dist/reference/errors/MOSTRA_PACK_NOT_APPLIED.md +23 -0
  24. package/dist/reference/errors/MOSTRA_PACK_OFFLINE.md +23 -0
  25. package/dist/reference/errors/MOSTRA_PACK_TARGET_INVALID.md +23 -0
  26. package/dist/reference/errors/MOSTRA_PLUGIN_CONFLICT.md +23 -0
  27. package/dist/reference/errors/MOSTRA_PLUGIN_CONTRACT_UNSUPPORTED.md +23 -0
  28. package/dist/reference/errors/MOSTRA_PLUGIN_ENTRY_INVALID.md +23 -0
  29. package/dist/reference/errors/MOSTRA_PLUGIN_EXPORTER_UNKNOWN.md +23 -0
  30. package/dist/reference/errors/MOSTRA_PLUGIN_FAILED.md +23 -0
  31. package/dist/reference/errors/MOSTRA_PLUGIN_MANIFEST_INVALID.md +23 -0
  32. package/dist/reference/errors/MOSTRA_PLUGIN_MANIFEST_WARNING.md +23 -0
  33. package/dist/reference/errors/MOSTRA_PLUGIN_NOT_A_PLUGIN.md +23 -0
  34. package/dist/reference/errors/MOSTRA_PLUGIN_NOT_INSTALLED.md +23 -0
  35. package/dist/reference/errors/MOSTRA_PLUGIN_OPTIONS_INVALID.md +23 -0
  36. package/dist/reference/errors/MOSTRA_PLUGIN_PLATFORM_UNSUPPORTED.md +23 -0
  37. package/dist/reference/errors/MOSTRA_PLUGIN_SCOPE_INVALID.md +23 -0
  38. package/dist/reference/errors/MOSTRA_PLUGIN_SHADOWED.md +23 -0
  39. package/dist/skill/SKILL.md +4 -2
  40. package/dist/skill/references/mcp.md +2 -2
  41. package/dist/skill/references/plugins.md +51 -0
  42. package/package.json +10 -7
  43. package/src/deps/index.ts +407 -90
  44. package/src/deps/installer.ts +53 -10
  45. package/src/deps/lock.ts +74 -2
  46. package/src/home/settings.ts +3 -0
  47. package/src/instance/index.ts +57 -0
  48. package/src/packs/index.ts +7 -0
  49. package/src/packs/methods.ts +49 -0
  50. package/src/packs/packs.ts +706 -0
  51. package/src/packs/read.ts +759 -0
  52. package/src/platform/index.ts +1 -0
  53. package/src/platform/shell.ts +14 -0
  54. package/src/plugins/child/host.ts +231 -0
  55. package/src/plugins/child-protocol.ts +68 -0
  56. package/src/plugins/index.ts +7 -0
  57. package/src/plugins/location.ts +109 -0
  58. package/src/plugins/methods.ts +269 -0
  59. package/src/plugins/plugins.ts +1396 -0
  60. package/src/publish/publisher.ts +71 -3
  61. package/dist/instance-CFTw3g-c.js.map +0 -1
@@ -0,0 +1,1396 @@
1
+ /**
2
+ * Plugins (D30, D31, INTERFACES §14; EX-01, EX-02, EX-04): npm packages with a `"mostra"`
3
+ * manifest, installed for one artifact (recorded in its working lockfile, frozen into each
4
+ * version's `lock.yaml`) or for the whole home (exporters and CLI commands, ROUND-3 §6.4).
5
+ *
6
+ * Every lockfile that names plugins passes one gate (`admit`, D172 items 5, 7 and 8), whoever
7
+ * changes or uses it: `plugin/add` and `plugin/remove`, `pack/add`, `deps/add`, and the resolution
8
+ * of `verify` and `publish` (the deps module calls it). In this order, each refusing before the
9
+ * next starts:
10
+ * 1. each manifest (`checkPluginManifest`), its contract ranges against what this release
11
+ * implements, the scope it is installed in, and conflicts within the scope (two plugins with
12
+ * one ID, a command that begins another's, an ID Mostra builds in);
13
+ * 2. the licenses of everything the change brings, classed (D31), while the install's lifecycle
14
+ * scripts are held: one that needs an acknowledgment and has none refuses before any of the
15
+ * packages' code or scripts have run;
16
+ * 3. the held scripts, then each Node.js entry, loaded in a plugin child (never the supervisor,
17
+ * RT-02), which must export a definition stamped with its contract on a line this release
18
+ * serves.
19
+ *
20
+ * ```ts
21
+ * const plugins = createPlugins({ home, dependencies, processes, log, env, policy });
22
+ * await plugins.add({ kind: "artifact", target }, { packages: ["mostra-pdf"], accept: [] });
23
+ * createDependencies({ …, plugins: () => plugins }); // verify, publish and deps/add pass the gate
24
+ * ```
25
+ */
26
+ import { existsSync, realpathSync } from "node:fs";
27
+ import { mkdir, readFile } from "node:fs/promises";
28
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
29
+ import { fileURLToPath } from "node:url";
30
+ import {
31
+ type ContractName,
32
+ createDiagnostic,
33
+ type Diagnostic,
34
+ type LicenseClass,
35
+ type LicenseDisclosure,
36
+ type LicensedPackage,
37
+ type LicensePolicy,
38
+ type PluginAddResult,
39
+ type PluginCommandInfo,
40
+ type PluginContribution,
41
+ type PluginListResult,
42
+ type PluginRemoveResult,
43
+ type PluginScope,
44
+ type PluginSummary,
45
+ type PluginValidateResult,
46
+ RpcError,
47
+ } from "@mostra/protocol";
48
+ import {
49
+ ACKNOWLEDGED_CLASSES,
50
+ BUILT_IN_EXPORTERS,
51
+ type BundledLicense,
52
+ CONTRACT_NAMES,
53
+ checkPluginManifest,
54
+ formatLicenseExpression,
55
+ isLicenseRef,
56
+ type LicenseTerm,
57
+ licenseTerms,
58
+ manifestScopes,
59
+ PLUGIN_CONTRACTS,
60
+ type PluginManifest,
61
+ packageLicense,
62
+ packageLicenseTerms,
63
+ parseLicenseExpression,
64
+ spdxLicense,
65
+ stampServed,
66
+ } from "@mostra/protocol/plugin";
67
+ import semver from "semver";
68
+ import type {
69
+ Dependencies,
70
+ DependencyTarget,
71
+ Lock,
72
+ LockLicense,
73
+ PluginGate,
74
+ StagedChange,
75
+ } from "../deps/index.ts";
76
+ import { parseLock, runtimeRoot } from "../deps/index.ts";
77
+ import type { RequestKey } from "../ledger/index.ts";
78
+ import type { Environment, Log } from "../log.ts";
79
+ import { OS, shellWord } from "../platform/index.ts";
80
+ import { artifactEnvironment, type ProcessManager } from "../processes/index.ts";
81
+ import {
82
+ EXPORT_METHOD,
83
+ type ExportRequest,
84
+ type ExportResponse,
85
+ INSPECT_METHOD,
86
+ type InspectedEntry,
87
+ } from "./child-protocol.ts";
88
+ import { jsonLocation } from "./location.ts";
89
+
90
+ /**
91
+ * `MOSTRA_TEST_CONTRACT_VERSIONS` (tests only): JSON naming, by contract, the versions a runtime
92
+ * stood in for serves, `{"exporter":["0.0.0"]}`; the others keep this release's.
93
+ */
94
+ export function testContractVersions(text: string): (contract: ContractName) => readonly string[] {
95
+ const parsed = JSON.parse(text) as Partial<Record<ContractName, string[]>>;
96
+ return (contract) => parsed[contract] ?? PLUGIN_CONTRACTS[contract].implements;
97
+ }
98
+
99
+ /** Where a plugin call acts: one artifact's lockfile, or the home's own. */
100
+ export type Scope =
101
+ | { readonly kind: "artifact"; readonly target: DependencyTarget }
102
+ | { readonly kind: "home" };
103
+
104
+ /** Options for {@link createPlugins}. */
105
+ export interface PluginsOptions {
106
+ /** The home's real path: the home's own plugins install from `<home>/plugins`. */
107
+ readonly home: string;
108
+ readonly dependencies: Dependencies;
109
+ readonly processes: ProcessManager;
110
+ readonly log: Log;
111
+ /** The supervisor's environment, from which plugin children get the artifact environment. */
112
+ readonly env: Environment;
113
+ /** The home's license policy (`HomeConfig.licenses`), read at each install. */
114
+ readonly policy: () => LicensePolicy | undefined;
115
+ /** This runtime's release, which exporters are told. */
116
+ readonly runtimeVersion: string;
117
+ /**
118
+ * The contract versions this runtime serves: `PLUGIN_CONTRACTS`' by default. Tests stand in a
119
+ * runtime that serves others (`MOSTRA_TEST_CONTRACT_VERSIONS`), to see a recorded plugin go out
120
+ * of range at load (ROUND-3 §6.4).
121
+ */
122
+ readonly implemented?: (contract: ContractName) => readonly string[];
123
+ /** How long one plugin child may take: loading entries, or an export. Default 120 s. */
124
+ readonly childTimeoutMs?: number;
125
+ }
126
+
127
+ /** The plugins of one instance; the deps module's plugin gate. */
128
+ export interface Plugins extends PluginGate {
129
+ /**
130
+ * `plugin/validate`: a plugin package as Mostra would load it, installing nothing. Its entries
131
+ * load only when every license it brings that needs an acknowledgment has one (`accept`).
132
+ */
133
+ validate(path: string, accept: readonly string[]): Promise<PluginValidateResult>;
134
+ /** `plugin/add`. */
135
+ add(
136
+ scope: Scope,
137
+ input: {
138
+ readonly packages: readonly string[];
139
+ readonly accept: readonly string[];
140
+ readonly request?: RequestKey | undefined;
141
+ },
142
+ ): Promise<PluginAddResult>;
143
+ /** `plugin/list`. */
144
+ list(scope: Scope): Promise<PluginListResult>;
145
+ /** `plugin/remove`. */
146
+ remove(
147
+ scope: Scope,
148
+ input: { readonly packages: readonly string[]; readonly request?: RequestKey | undefined },
149
+ ): Promise<PluginRemoveResult>;
150
+ /**
151
+ * The gate for a change another module makes (a pack's items and npm packages): the scope's
152
+ * plugins as they were, the licenses of `packages` (their closures) and `items`, the held
153
+ * scripts, the entries. Answers the lockfile's plugins and acknowledgments after the change, and
154
+ * the disclosures of what the change itself brought.
155
+ */
156
+ admitChange(
157
+ scope: Scope,
158
+ input: {
159
+ readonly staged: StagedChange;
160
+ readonly packages?: readonly string[];
161
+ readonly items?: readonly ItemLicense[];
162
+ readonly accept: readonly string[];
163
+ readonly command: string;
164
+ },
165
+ ): Promise<{
166
+ readonly plugins: readonly string[];
167
+ readonly licenses: Readonly<Record<string, LockLicense>>;
168
+ readonly disclosures: readonly LicenseDisclosure[];
169
+ }>;
170
+ /**
171
+ * The exporters a version can use: its own plugins, as its `lock.yaml` froze them, in the
172
+ * layout it was built against; then the home's (an artifact's own wins over the home's of one
173
+ * ID). An exporter whose plugin this release can't load carries the refusal as `problem`.
174
+ */
175
+ exporters(input: {
176
+ readonly artifactId: string;
177
+ readonly versionDir: string;
178
+ readonly sourceDir?: string;
179
+ }): Promise<readonly ExporterRef[]>;
180
+ /**
181
+ * The CLI commands an artifact's plugins and the home's contribute (the artifact's own wins),
182
+ * read from layouts already installed: a lookup never starts an install.
183
+ */
184
+ commands(target: DependencyTarget | undefined): Promise<readonly PluginCommandInfo[]>;
185
+ /**
186
+ * The file of the pack item `item` (its `name`) that the plugin `pkg` carries, among the
187
+ * artifact's plugins and the home's, for `mostra add plugin:<package>/<item>`.
188
+ */
189
+ packItem(target: DependencyTarget, pkg: string, item: string): Promise<string | undefined>;
190
+ /**
191
+ * Runs an exporter on a version's directory, in a plugin child, which checks its stamp, its ID
192
+ * and the options against its schema before it runs (D172 item 9).
193
+ */
194
+ runExport(input: {
195
+ readonly exporter: ExporterRef;
196
+ readonly versionDir: string;
197
+ readonly version: Readonly<Record<string, unknown>>;
198
+ readonly options: Readonly<Record<string, unknown>>;
199
+ }): Promise<ExportDone>;
200
+ }
201
+
202
+ /** What an exporter that ran returned. */
203
+ export type ExportDone = Exclude<ExportResponse, { readonly refused: unknown }>;
204
+
205
+ /** An exporter a plugin contributes, as `plugin/export` runs it. */
206
+ export interface ExporterRef {
207
+ readonly id: string;
208
+ readonly package: string;
209
+ readonly scope: PluginScope;
210
+ readonly file: string;
211
+ readonly export: string;
212
+ readonly dir: string;
213
+ /** Why its plugin can't load here (a contract this release doesn't serve): the export refuses. */
214
+ readonly problem?: Diagnostic;
215
+ }
216
+
217
+ /** A plugin package as it is installed (or as `plugin/validate` finds it). */
218
+ interface Installed {
219
+ readonly name: string;
220
+ readonly version: string;
221
+ /** Its package directory, real. */
222
+ readonly dir: string;
223
+ readonly packageFile: string;
224
+ readonly text: string;
225
+ readonly json: Record<string, unknown>;
226
+ /** The manifest, when it has no error. */
227
+ readonly manifest?: PluginManifest;
228
+ /** What its manifest check found, located in `package.json`. */
229
+ readonly issues: readonly Diagnostic[];
230
+ readonly scope: PluginScope;
231
+ }
232
+
233
+ /** The key of the home's own working lockfile. */
234
+ const HOME_KEY = "home:plugins";
235
+
236
+ /** The plugin child's entry: the compiled one beside the compiled supervisor, else the source. */
237
+ function childEntry(): string {
238
+ return fileURLToPath(import.meta.url).endsWith(".ts")
239
+ ? join(runtimeRoot(), "src/plugins/child/host.ts")
240
+ : join(runtimeRoot(), "dist/plugins/child/host.js");
241
+ }
242
+
243
+ /** `inner` is `outer` or inside it (both real paths). */
244
+ function isInside(outer: string, inner: string): boolean {
245
+ const from = relative(outer, inner);
246
+ return from === "" || (!from.startsWith(`..${sep}`) && from !== ".." && !isAbsolute(from));
247
+ }
248
+
249
+ const error = (code: Parameters<typeof createDiagnostic>[0], message: string): RpcError =>
250
+ new RpcError(createDiagnostic(code, { message }));
251
+
252
+ /** Creates the plugins of one instance. */
253
+ export function createPlugins(options: PluginsOptions): Plugins {
254
+ const implementedOf = (contract: ContractName): readonly string[] =>
255
+ options.implemented?.(contract) ?? PLUGIN_CONTRACTS[contract].implements;
256
+ const { dependencies, log } = options;
257
+ const homeTarget: DependencyTarget = {
258
+ key: HOME_KEY,
259
+ artifactDir: join(options.home, "plugins"),
260
+ artifactPath: "--global",
261
+ };
262
+ const childTimeoutMs = options.childTimeoutMs ?? 120_000;
263
+
264
+ const targetOf = async (scope: Scope): Promise<DependencyTarget> => {
265
+ if (scope.kind === "artifact") return scope.target;
266
+ await mkdir(homeTarget.artifactDir, { recursive: true });
267
+ return homeTarget;
268
+ };
269
+
270
+ /** Reads a package directory's `package.json` and manifest. */
271
+ const readPackage = async (dir: string, scope: PluginScope): Promise<Installed> => {
272
+ const real = realpathSync(dir);
273
+ const packageFile = join(real, "package.json");
274
+ const text = await readFile(packageFile, "utf8");
275
+ let json: Record<string, unknown>;
276
+ try {
277
+ json = JSON.parse(text) as Record<string, unknown>;
278
+ } catch {
279
+ throw new RpcError(
280
+ createDiagnostic("MOSTRA_PLUGIN_MANIFEST_INVALID", {
281
+ message: `${packageFile} isn't JSON.`,
282
+ location: { file: packageFile, line: 1, column: 1 },
283
+ }),
284
+ );
285
+ }
286
+ const name = typeof json["name"] === "string" ? json["name"] : "";
287
+ const version = typeof json["version"] === "string" ? json["version"] : "0.0.0";
288
+ const issues: Diagnostic[] = [];
289
+ let manifest: PluginManifest | undefined;
290
+ if (json["mostra"] !== undefined) {
291
+ const check = checkPluginManifest(json["mostra"]);
292
+ manifest = check.manifest;
293
+ for (const issue of check.issues) {
294
+ issues.push(
295
+ createDiagnostic(
296
+ issue.severity === "error"
297
+ ? "MOSTRA_PLUGIN_MANIFEST_INVALID"
298
+ : "MOSTRA_PLUGIN_MANIFEST_WARNING",
299
+ {
300
+ message: `${issue.path.join(".")}: ${issue.message}`,
301
+ location: { file: packageFile, ...jsonLocation(text, issue.path) },
302
+ },
303
+ ),
304
+ );
305
+ }
306
+ }
307
+ return {
308
+ name,
309
+ version,
310
+ dir: real,
311
+ packageFile,
312
+ text,
313
+ json,
314
+ ...(manifest ? { manifest } : {}),
315
+ issues,
316
+ scope,
317
+ };
318
+ };
319
+
320
+ const at = (plugin: Installed, path: readonly (string | number)[]) => ({
321
+ file: plugin.packageFile,
322
+ ...jsonLocation(plugin.text, ["mostra", ...path]),
323
+ });
324
+
325
+ /** The checks of one set of plugins that need no code to run: ranges, scope, files, platform. */
326
+ const staticChecks = (plugin: Installed): Diagnostic[] => {
327
+ const found: Diagnostic[] = [...plugin.issues];
328
+ const manifest = plugin.manifest;
329
+ if (manifest === undefined) {
330
+ if (plugin.json["mostra"] === undefined) {
331
+ found.push(
332
+ createDiagnostic("MOSTRA_PLUGIN_NOT_A_PLUGIN", {
333
+ message: `${plugin.name || plugin.dir} has no "mostra" key in its package.json, so it isn't a Mostra plugin.`,
334
+ location: { file: plugin.packageFile, line: 1, column: 1 },
335
+ }),
336
+ );
337
+ }
338
+ return found;
339
+ }
340
+ for (const [contract, range] of Object.entries(manifest.contracts) as [
341
+ ContractName,
342
+ string,
343
+ ][]) {
344
+ const valid = semver.validRange(range);
345
+ const implemented = implementedOf(contract);
346
+ if (valid === null) {
347
+ found.push(
348
+ createDiagnostic("MOSTRA_PLUGIN_MANIFEST_INVALID", {
349
+ message: `contracts.${contract}: "${range}" isn't a semver range.`,
350
+ location: at(plugin, ["contracts", contract]),
351
+ }),
352
+ );
353
+ } else if (!implemented.some((version) => semver.satisfies(version, range))) {
354
+ found.push(
355
+ createDiagnostic("MOSTRA_PLUGIN_CONTRACT_UNSUPPORTED", {
356
+ message: `${plugin.name}@${plugin.version} needs the ${contract} contract at ${range}; this Mostra implements ${PLUGIN_CONTRACTS[contract].package} ${implemented.join(", ")}.`,
357
+ location: at(plugin, ["contracts", contract]),
358
+ }),
359
+ );
360
+ }
361
+ }
362
+ if (!manifestScopes(manifest).includes(plugin.scope)) {
363
+ found.push(
364
+ createDiagnostic("MOSTRA_PLUGIN_SCOPE_INVALID", {
365
+ message: `${plugin.name} contributes more than exporters and CLI commands, so it is installed for an artifact, not for the home.`,
366
+ location: at(plugin, ["contributes"]),
367
+ }),
368
+ );
369
+ }
370
+ for (const name of CONTRACT_NAMES) {
371
+ const key = PLUGIN_CONTRACTS[name].key;
372
+ (manifest.contributes[key] ?? []).forEach((entry, index) => {
373
+ const file = resolve(plugin.dir, entry.entry);
374
+ if (!existsSync(file) || !isInside(plugin.dir, realpathSync(file))) {
375
+ found.push(
376
+ createDiagnostic("MOSTRA_PLUGIN_ENTRY_INVALID", {
377
+ message: `contributes.${key}[${index}]: ${entry.entry} isn't a file of ${plugin.name}.`,
378
+ location: at(plugin, ["contributes", key, index, "entry"]),
379
+ }),
380
+ );
381
+ }
382
+ });
383
+ }
384
+ (manifest.contributes.packs ?? []).forEach((pack, index) => {
385
+ const file = resolve(plugin.dir, pack.item);
386
+ if (!existsSync(file) || !isInside(plugin.dir, realpathSync(file))) {
387
+ found.push(
388
+ createDiagnostic("MOSTRA_PLUGIN_ENTRY_INVALID", {
389
+ message: `contributes.packs[${index}]: ${pack.item} isn't a file of ${plugin.name}.`,
390
+ location: at(plugin, ["contributes", "packs", index, "item"]),
391
+ }),
392
+ );
393
+ }
394
+ });
395
+ if (manifest.platforms !== undefined && !manifest.platforms.includes(OS)) {
396
+ found.push(
397
+ createDiagnostic("MOSTRA_PLUGIN_PLATFORM_UNSUPPORTED", {
398
+ message: `${plugin.name} names ${manifest.platforms.join(", ")}, not ${OS}.`,
399
+ location: at(plugin, ["platforms"]),
400
+ }),
401
+ );
402
+ }
403
+ return found;
404
+ };
405
+
406
+ /** Every contribution of a manifest, with its contract and position. */
407
+ const contributionsOf = (manifest: PluginManifest) => {
408
+ const all: {
409
+ contract: ContractName;
410
+ id: string;
411
+ entry: string;
412
+ export: string;
413
+ path: (string | number)[];
414
+ }[] = [];
415
+ for (const name of CONTRACT_NAMES) {
416
+ const key = PLUGIN_CONTRACTS[name].key;
417
+ (manifest.contributes[key] ?? []).forEach((entry, index) => {
418
+ all.push({
419
+ contract: name,
420
+ id: "command" in entry ? entry.command : entry.id,
421
+ entry: entry.entry,
422
+ export: entry.export ?? "default",
423
+ path: ["contributes", key, index],
424
+ });
425
+ });
426
+ }
427
+ return all;
428
+ };
429
+
430
+ /**
431
+ * Conflicts within `set`: two plugins contributing one ID of a contract, a CLI command whose
432
+ * words begin another's (`foo` and `foo bar`: the longer would swallow the shorter's arguments),
433
+ * an exporter ID Mostra builds in. Those refuse. Against `others` (the home's plugins, when
434
+ * `set` is an artifact's) a shared exporter or command is a warning: the artifact's own wins in
435
+ * the artifact (D172 item 5), so a home install never breaks an artifact.
436
+ */
437
+ const conflicts = (set: readonly Installed[], others: readonly Installed[]) => {
438
+ const found = new Map<Installed, Diagnostic[]>();
439
+ const add = (plugin: Installed, diagnostic: Diagnostic) => {
440
+ found.set(plugin, [...(found.get(plugin) ?? []), diagnostic]);
441
+ };
442
+ const owner = new Map<string, Installed>();
443
+ const commands: { words: string[]; plugin: Installed }[] = [];
444
+ for (const plugin of set) {
445
+ for (const item of plugin.manifest ? contributionsOf(plugin.manifest) : []) {
446
+ if (item.contract === "exporter" && BUILT_IN_EXPORTERS.includes(item.id)) {
447
+ add(
448
+ plugin,
449
+ createDiagnostic("MOSTRA_PLUGIN_CONFLICT", {
450
+ message: `${plugin.name} contributes the exporter "${item.id}", which Mostra builds in.`,
451
+ location: at(plugin, [...item.path, "id"]),
452
+ }),
453
+ );
454
+ continue;
455
+ }
456
+ const key = `${item.contract}:${item.id}`;
457
+ const first = owner.get(key);
458
+ if (first !== undefined && first !== plugin) {
459
+ add(
460
+ plugin,
461
+ createDiagnostic("MOSTRA_PLUGIN_CONFLICT", {
462
+ message: `${plugin.name} and ${first.name} both contribute the ${item.contract} "${item.id}"; nothing is overridden: remove one.`,
463
+ location: at(plugin, item.path),
464
+ }),
465
+ );
466
+ continue;
467
+ }
468
+ owner.set(key, plugin);
469
+ if (item.contract !== "cli-command") continue;
470
+ const words = item.id.split(" ");
471
+ const prefix = commands.find(
472
+ (other) =>
473
+ other.plugin !== plugin &&
474
+ other.words.length !== words.length &&
475
+ other.words
476
+ .slice(0, Math.min(other.words.length, words.length))
477
+ .every((word, index) => word === words[index]),
478
+ );
479
+ if (prefix !== undefined) {
480
+ add(
481
+ plugin,
482
+ createDiagnostic("MOSTRA_PLUGIN_CONFLICT", {
483
+ message: `${plugin.name}'s command "${item.id}" and ${prefix.plugin.name}'s "${prefix.words.join(" ")}" begin with the same words, so one would take the other's arguments: remove one.`,
484
+ location: at(plugin, item.path),
485
+ }),
486
+ );
487
+ } else commands.push({ words, plugin });
488
+ }
489
+ }
490
+ for (const other of others) {
491
+ for (const item of other.manifest ? contributionsOf(other.manifest) : []) {
492
+ if (item.contract !== "exporter" && item.contract !== "cli-command") continue;
493
+ const mine = owner.get(`${item.contract}:${item.id}`);
494
+ if (mine === undefined) continue;
495
+ add(
496
+ mine,
497
+ createDiagnostic("MOSTRA_PLUGIN_SHADOWED", {
498
+ message: `${mine.name} and the home's ${other.name} both contribute the ${item.contract} "${item.id}"; this artifact uses ${mine.name}'s.`,
499
+ }),
500
+ );
501
+ }
502
+ }
503
+ return found;
504
+ };
505
+
506
+ /** Loads the Node.js entries of plugins whose static checks passed, in one plugin child. */
507
+ const inspectEntries = async (
508
+ set: readonly Installed[],
509
+ cwd: string,
510
+ ): Promise<Map<Installed, Diagnostic[]>> => {
511
+ const found = new Map<Installed, Diagnostic[]>();
512
+ const jobs: {
513
+ plugin: Installed;
514
+ item: ReturnType<typeof contributionsOf>[number];
515
+ file: string;
516
+ }[] = [];
517
+ for (const plugin of set) {
518
+ for (const item of plugin.manifest ? contributionsOf(plugin.manifest) : []) {
519
+ if (PLUGIN_CONTRACTS[item.contract].runs !== "node") continue;
520
+ jobs.push({ plugin, item, file: realpathSync(resolve(plugin.dir, item.entry)) });
521
+ }
522
+ }
523
+ if (jobs.length === 0) return found;
524
+ const answers = await inChild<InspectedEntry[]>(
525
+ cwd,
526
+ "plugins",
527
+ (child) =>
528
+ child.request(
529
+ INSPECT_METHOD,
530
+ { entries: jobs.map((job) => ({ file: job.file, export: job.item.export })) },
531
+ { timeoutMs: childTimeoutMs },
532
+ ) as Promise<InspectedEntry[]>,
533
+ );
534
+ jobs.forEach((job, index) => {
535
+ const answer = answers[index];
536
+ const where = at(job.plugin, [...job.item.path, "entry"]);
537
+ const problem = (
538
+ message: string,
539
+ code:
540
+ | "MOSTRA_PLUGIN_ENTRY_INVALID"
541
+ | "MOSTRA_PLUGIN_CONTRACT_UNSUPPORTED" = "MOSTRA_PLUGIN_ENTRY_INVALID",
542
+ ) =>
543
+ found.set(job.plugin, [
544
+ ...(found.get(job.plugin) ?? []),
545
+ createDiagnostic(code, { message, location: where }),
546
+ ]);
547
+ const label = `${job.plugin.name}'s ${job.item.contract} "${job.item.id}" (${job.item.entry}${job.item.export === "default" ? "" : `#${job.item.export}`})`;
548
+ if (answer === undefined || !answer.ok) {
549
+ problem(`${label} didn't load: ${answer && !answer.ok ? answer.error : "no answer"}.`);
550
+ return;
551
+ }
552
+ const stamp = answer.stamp as { name?: unknown; version?: unknown } | null;
553
+ if (stamp === null || typeof stamp !== "object" || typeof stamp.name !== "string") {
554
+ problem(
555
+ `${label} exports no stamped definition: export what ${PLUGIN_CONTRACTS[job.item.contract].package}'s define function returns.`,
556
+ );
557
+ return;
558
+ }
559
+ if (stamp.name !== job.item.contract) {
560
+ problem(`${label} exports a ${stamp.name} definition, not a ${job.item.contract}.`);
561
+ return;
562
+ }
563
+ if (!stampServed(stamp, job.item.contract, implementedOf(job.item.contract))) {
564
+ problem(
565
+ `${label} was built with ${PLUGIN_CONTRACTS[job.item.contract].package} ${String(stamp.version)}, of another line than the ${implementedOf(job.item.contract).join(", ")} this Mostra serves.`,
566
+ "MOSTRA_PLUGIN_CONTRACT_UNSUPPORTED",
567
+ );
568
+ return;
569
+ }
570
+ const id = job.item.contract === "cli-command" ? answer.path?.join(" ") : answer.id;
571
+ if (id !== job.item.id) {
572
+ problem(
573
+ `${label}'s definition is "${id ?? "(none)"}", not "${job.item.id}" as the manifest says.`,
574
+ );
575
+ }
576
+ });
577
+ return found;
578
+ };
579
+
580
+ /** Runs a plugin child for one task and stops it. */
581
+ const inChild = async <T>(
582
+ cwd: string,
583
+ ownerRef: string,
584
+ task: (child: Awaited<ReturnType<ProcessManager["spawn"]>>) => Promise<T>,
585
+ ): Promise<T> => {
586
+ const child = await options.processes.spawn({
587
+ kind: "plugin",
588
+ ownerRef,
589
+ command: process.execPath,
590
+ args: [childEntry()],
591
+ cwd,
592
+ env: artifactEnvironment(options.env),
593
+ ipc: {},
594
+ });
595
+ try {
596
+ return await task(child);
597
+ } catch (problem) {
598
+ // A refusal of the plugin's own stays as it is; anything else (the child crashed, hung past
599
+ // its limit, or answered nonsense) is the plugin's failure, said as one.
600
+ if (
601
+ problem instanceof RpcError &&
602
+ /^MOSTRA_(PLUGIN|LICENSE)_/.test(problem.diagnostic.code)
603
+ ) {
604
+ throw problem;
605
+ }
606
+ const reason =
607
+ problem instanceof RpcError
608
+ ? `${problem.diagnostic.code}: ${problem.diagnostic.message}`
609
+ : problem instanceof Error
610
+ ? problem.message
611
+ : String(problem);
612
+ throw error("MOSTRA_PLUGIN_FAILED", `A plugin's child (${ownerRef}) failed: ${reason}`);
613
+ } finally {
614
+ await child.stop(2000);
615
+ }
616
+ };
617
+
618
+ /** Reads a scope's plugins from its working lockfile and layout. */
619
+ const installedOf = async (
620
+ lock: Lock | undefined,
621
+ nodeModules: string | undefined,
622
+ scope: PluginScope,
623
+ ): Promise<Installed[]> => {
624
+ const found: Installed[] = [];
625
+ for (const name of lock?.plugins ?? []) {
626
+ const dir = nodeModules ? join(nodeModules, name) : undefined;
627
+ if (dir === undefined || !existsSync(join(dir, "package.json"))) {
628
+ throw error(
629
+ "MOSTRA_PLUGIN_NOT_INSTALLED",
630
+ `The lockfile names the plugin ${name}, which its layout doesn't hold.`,
631
+ );
632
+ }
633
+ found.push(await readPackage(dir, scope));
634
+ }
635
+ return found;
636
+ };
637
+
638
+ /**
639
+ * The home's own plugins as they stand, for the shadow warnings and the home's exporters and
640
+ * commands; `install: false` reads only a layout already installed (nothing starts).
641
+ */
642
+ const homePlugins = async (install: boolean): Promise<Installed[]> => {
643
+ const staged = await dependencies.working(homeTarget, { install }).catch(() => undefined);
644
+ if (staged?.nodeModules === undefined) return [];
645
+ return installedOf(staged.lock, staged.nodeModules, "home").catch(() => []);
646
+ };
647
+
648
+ /**
649
+ * Every package a plugin's code can reach at run time, the plugin included: its dependencies,
650
+ * optional dependencies, peer dependencies (the installer installs them, `auto-install-peers`)
651
+ * and bundled dependencies, as Node resolves each from the package's real directory.
652
+ */
653
+ const closure = async (root: string) => {
654
+ const seen = new Map<
655
+ string,
656
+ { name: string; version: string; dir: string; json: Record<string, unknown> }
657
+ >();
658
+ const names = (value: unknown): string[] =>
659
+ Array.isArray(value)
660
+ ? value.filter((name): name is string => typeof name === "string")
661
+ : typeof value === "object" && value !== null
662
+ ? Object.keys(value)
663
+ : [];
664
+ const visit = async (dir: string): Promise<void> => {
665
+ const real = realpathSync(dir);
666
+ if (seen.has(real)) return;
667
+ const json = JSON.parse(await readFile(join(real, "package.json"), "utf8")) as Record<
668
+ string,
669
+ unknown
670
+ >;
671
+ seen.set(real, {
672
+ name: String(json["name"] ?? ""),
673
+ version: String(json["version"] ?? ""),
674
+ dir: real,
675
+ json,
676
+ });
677
+ const deps = new Set([
678
+ ...names(json["dependencies"]),
679
+ ...names(json["optionalDependencies"]),
680
+ ...names(json["peerDependencies"]),
681
+ ...names(json["bundleDependencies"]),
682
+ ...names(json["bundledDependencies"]),
683
+ ]);
684
+ for (const dep of [...deps].sort()) {
685
+ const found = locate(real, dep);
686
+ if (found !== undefined) await visit(found);
687
+ }
688
+ };
689
+ await visit(root);
690
+ return [...seen.values()];
691
+ };
692
+
693
+ /** Node's resolution of a package directory from `from` (pnpm's isolated layout puts it beside). */
694
+ const locate = (from: string, name: string): string | undefined => {
695
+ let dir = from;
696
+ for (;;) {
697
+ if (!dir.endsWith(`${sep}node_modules`)) {
698
+ const candidate = join(dir, "node_modules", name);
699
+ if (existsSync(join(candidate, "package.json"))) return candidate;
700
+ }
701
+ const parent = dirname(dir);
702
+ if (parent === dir) return undefined;
703
+ dir = parent;
704
+ }
705
+ };
706
+
707
+ /**
708
+ * Every license an install brings, classed, with where its acknowledgment stands, and the
709
+ * acknowledgments it makes: each plugin's whole closure, each other package's (a pack's npm
710
+ * dependencies), and each pack item's own `mostra.license`. A license that needs an
711
+ * acknowledgment is accepted by an earlier one of the same class, by `accept`, or by the
712
+ * home's policy (D31).
713
+ *
714
+ * What a plugin declares (`bundledLicenses`) describes a package whose own license field Mostra
715
+ * can't read, and only ever as a license that needs an acknowledgment: no declaration makes a
716
+ * package OSI-licensed (D172 item 7).
717
+ */
718
+ const disclose = async (input: {
719
+ readonly plugins: readonly Installed[];
720
+ readonly packages?: readonly Installed[];
721
+ readonly items?: readonly ItemLicense[];
722
+ readonly previous: Readonly<Record<string, LockLicense>> | undefined;
723
+ readonly accept: readonly string[];
724
+ }): Promise<{
725
+ disclosures: LicenseDisclosure[];
726
+ record: Record<string, LockLicense>;
727
+ missing: LicenseDisclosure[];
728
+ warnings: Map<Installed, Diagnostic[]>;
729
+ /** Each plugin's or package's closure, by package name. */
730
+ closures: Map<Installed, Set<string>>;
731
+ }> => {
732
+ const closures = new Map<Installed, Set<string>>();
733
+ type Entry = {
734
+ class: LicenseTerm["class"];
735
+ packages: Map<string, LicensedPackage>;
736
+ summary?: string;
737
+ url?: string;
738
+ };
739
+ const byId = new Map<string, Entry>();
740
+ const entry = (id: string, licenseClass: LicenseTerm["class"]): Entry => {
741
+ const found = byId.get(id) ?? { class: licenseClass, packages: new Map() };
742
+ byId.set(id, found);
743
+ return found;
744
+ };
745
+ const warnings = new Map<Installed, Diagnostic[]>();
746
+ const warn = (owner: Installed, diagnostic: Diagnostic) =>
747
+ warnings.set(owner, [...(warnings.get(owner) ?? []), diagnostic]);
748
+ const policy = options.policy()?.accept ?? [];
749
+ for (const owner of [...input.plugins, ...(input.packages ?? [])]) {
750
+ const isPlugin = input.plugins.includes(owner);
751
+ const declared = new Map<string, BundledLicense>(
752
+ (owner.manifest?.bundledLicenses ?? []).map((bundled) => [bundled.package, bundled]),
753
+ );
754
+ const classOf = (id: string) =>
755
+ [...declared.values()].find((bundled) => bundled.license === id)?.class;
756
+ const packages = await closure(owner.dir);
757
+ closures.set(owner, new Set(packages.map((pkg) => pkg.name)));
758
+ for (const pkg of packages) {
759
+ const field = packageLicense(pkg.json as { license?: unknown; licenses?: unknown });
760
+ const bundled = declared.get(pkg.name);
761
+ let terms: readonly LicenseTerm[];
762
+ let shown: string;
763
+ const readable = field !== undefined && field !== "UNLICENSED" && isReadable(field);
764
+ if (readable) {
765
+ terms = packageLicenseTerms(pkg.name, field, classOf);
766
+ shown = field;
767
+ if (bundled !== undefined && !sameExpression(bundled.license, field)) {
768
+ warn(
769
+ owner,
770
+ createDiagnostic("MOSTRA_LICENSE_MISMATCH", {
771
+ message: `${owner.name} declares ${pkg.name} as ${bundled.license}; ${pkg.name}@${pkg.version} itself says ${field}, which is what Mostra shows.`,
772
+ }),
773
+ );
774
+ }
775
+ } else {
776
+ const unreadable = packageLicenseTerms(pkg.name, field, classOf);
777
+ const declaredTerms =
778
+ bundled !== undefined && isReadable(bundled.license)
779
+ ? licenseTerms(parseLicenseExpression(bundled.license), classOf)
780
+ : undefined;
781
+ if (declaredTerms?.every((term) => ACKNOWLEDGED_CLASSES.has(term.class))) {
782
+ terms = declaredTerms ?? unreadable;
783
+ shown = bundled?.license ?? "";
784
+ } else {
785
+ terms = unreadable;
786
+ shown = field ?? "(none)";
787
+ if (declaredTerms !== undefined) {
788
+ warn(
789
+ owner,
790
+ createDiagnostic("MOSTRA_LICENSE_MISMATCH", {
791
+ message: `${owner.name} declares ${pkg.name} as ${bundled?.license}, which Mostra can't confirm: ${pkg.name}@${pkg.version}'s own license field is ${field === undefined ? "absent" : `"${field}"`}, so it is shown as ${unreadable.map((term) => term.id).join(" AND ")} (${unreadable.map((term) => term.class).join(", ")}).`,
792
+ }),
793
+ );
794
+ }
795
+ }
796
+ }
797
+ if (
798
+ isPlugin &&
799
+ pkg.dir !== owner.dir &&
800
+ bundled === undefined &&
801
+ terms.some((term) => ACKNOWLEDGED_CLASSES.has(term.class))
802
+ ) {
803
+ warn(
804
+ owner,
805
+ createDiagnostic("MOSTRA_LICENSE_UNDECLARED", {
806
+ message: `${owner.name} brings ${pkg.name}@${pkg.version} (${shown}) without declaring it in bundledLicenses.`,
807
+ }),
808
+ );
809
+ }
810
+ for (const term of terms) {
811
+ const slot = entry(term.id, term.class);
812
+ slot.packages.set(`${pkg.name}@${pkg.version}`, {
813
+ name: pkg.name,
814
+ version: pkg.version,
815
+ license: shown,
816
+ });
817
+ const describing = [...declared.values()].find((item) => item.license === term.id);
818
+ if (describing?.summary !== undefined) slot.summary = describing.summary;
819
+ if (describing?.url !== undefined) slot.url = describing.url;
820
+ }
821
+ }
822
+ if (isPlugin && owner.manifest !== undefined) {
823
+ const own = packageLicense(owner.json as { license?: unknown; licenses?: unknown });
824
+ if (own !== undefined && !sameExpression(own, owner.manifest.license)) {
825
+ warn(
826
+ owner,
827
+ createDiagnostic("MOSTRA_LICENSE_MISMATCH", {
828
+ message: `${owner.name}'s manifest says ${owner.manifest.license}; its package.json says ${own}, which is what Mostra shows.`,
829
+ location: at(owner, ["license"]),
830
+ }),
831
+ );
832
+ }
833
+ }
834
+ }
835
+ for (const item of input.items ?? []) {
836
+ const terms = (() => {
837
+ try {
838
+ return licenseTerms(parseLicenseExpression(item.license), (id) =>
839
+ isLicenseRef(id) ? item.class : undefined,
840
+ );
841
+ } catch {
842
+ return [{ id: unreadableItemRef(item.name), class: "unknown" as const }];
843
+ }
844
+ })();
845
+ for (const term of terms) {
846
+ entry(term.id, term.class).packages.set(`item:${item.name}`, {
847
+ name: item.name,
848
+ license: item.license,
849
+ item: true,
850
+ });
851
+ }
852
+ }
853
+ const now = new Date().toISOString();
854
+ const disclosures: LicenseDisclosure[] = [];
855
+ const record: Record<string, LockLicense> = {};
856
+ const missing: LicenseDisclosure[] = [];
857
+ for (const [id, found] of [...byId.entries()].sort(([a], [b]) => (a < b ? -1 : 1))) {
858
+ const base = {
859
+ id,
860
+ class: found.class,
861
+ packages: [...found.packages.values()].sort((a, b) => (a.name < b.name ? -1 : 1)),
862
+ ...(found.summary !== undefined ? { summary: found.summary } : {}),
863
+ ...(found.url !== undefined ? { url: found.url } : {}),
864
+ };
865
+ if (!ACKNOWLEDGED_CLASSES.has(found.class)) {
866
+ disclosures.push({ ...base, acknowledgment: "not-needed" });
867
+ continue;
868
+ }
869
+ // An acknowledgment counts for the license as it was then: one Mostra now classes otherwise
870
+ // (a newer SPDX list, a plugin's other declaration) is asked again.
871
+ const earlier = input.previous?.[id]?.class === found.class ? input.previous[id] : undefined;
872
+ const accepted: LockLicense | undefined =
873
+ earlier ??
874
+ (input.accept.includes(id) || input.accept.includes("*")
875
+ ? { class: found.class, by: "flag" }
876
+ : policy.includes(id) || policy.includes("*")
877
+ ? { class: found.class, by: "host" }
878
+ : undefined);
879
+ if (accepted === undefined) {
880
+ const disclosure: LicenseDisclosure = { ...base, acknowledgment: "missing" };
881
+ disclosures.push(disclosure);
882
+ missing.push(disclosure);
883
+ continue;
884
+ }
885
+ record[id] = accepted;
886
+ if (earlier === undefined) {
887
+ // The lockfile keeps no time (D172 item 6); the log says when, and by what.
888
+ log.info("plugins.license_accepted", {
889
+ license: id,
890
+ class: found.class,
891
+ by: accepted.by,
892
+ packages: base.packages.map((pkg) =>
893
+ pkg.version ? `${pkg.name}@${pkg.version}` : pkg.name,
894
+ ),
895
+ });
896
+ }
897
+ disclosures.push({
898
+ ...base,
899
+ acknowledgment: accepted.by === "host" ? "host" : "accepted",
900
+ ...(earlier === undefined ? { acceptedAt: now } : {}),
901
+ });
902
+ }
903
+ return { disclosures, record, missing, warnings, closures };
904
+ };
905
+
906
+ /** Summarizes a loaded plugin. */
907
+ const summary = (plugin: Installed, diagnostics: readonly Diagnostic[]): PluginSummary => {
908
+ const manifest = plugin.manifest;
909
+ const contributions: PluginContribution[] = manifest
910
+ ? contributionsOf(manifest).map((item) => ({ contract: item.contract, id: item.id }))
911
+ : [];
912
+ return {
913
+ package: plugin.name,
914
+ version: plugin.version,
915
+ name: manifest?.name ?? plugin.name,
916
+ ...(manifest?.title !== undefined ? { title: manifest.title } : {}),
917
+ ...(manifest?.description !== undefined ? { description: manifest.description } : {}),
918
+ scope: plugin.scope,
919
+ contracts: { ...(manifest?.contracts ?? {}) } as Record<string, string>,
920
+ contributions,
921
+ packs: (manifest?.contributes.packs ?? []).map((pack) => pack.item),
922
+ effects: [...(manifest?.effects ?? [])],
923
+ license: manifest?.license ?? String(plugin.json["license"] ?? ""),
924
+ ...(manifest?.platforms !== undefined ? { platforms: [...manifest.platforms] } : {}),
925
+ status: diagnostics.some((diagnostic) => diagnostic.severity === "error") ? "error" : "ok",
926
+ diagnostics: [...diagnostics],
927
+ };
928
+ };
929
+
930
+ /** Static checks and conflicts of a set: everything that needs no code to run. */
931
+ const statics = (
932
+ set: readonly Installed[],
933
+ others: readonly Installed[],
934
+ ): Map<Installed, Diagnostic[]> => {
935
+ const found = new Map<Installed, Diagnostic[]>(
936
+ set.map((plugin) => [plugin, staticChecks(plugin)]),
937
+ );
938
+ for (const [plugin, list] of conflicts(set, others)) {
939
+ found.set(plugin, [...(found.get(plugin) ?? []), ...list]);
940
+ }
941
+ return found;
942
+ };
943
+
944
+ const merged = (
945
+ set: readonly Installed[],
946
+ ...maps: readonly ReadonlyMap<Installed, readonly Diagnostic[]>[]
947
+ ): Map<Installed, Diagnostic[]> =>
948
+ new Map(set.map((plugin) => [plugin, maps.flatMap((map) => [...(map.get(plugin) ?? [])])]));
949
+
950
+ const firstError = (
951
+ found: ReadonlyMap<Installed, readonly Diagnostic[]>,
952
+ prefer: readonly Installed[] = [],
953
+ ): Diagnostic | undefined => {
954
+ for (const plugin of [...prefer, ...found.keys()]) {
955
+ const hit = found.get(plugin)?.find((diagnostic) => diagnostic.severity === "error");
956
+ if (hit !== undefined) return hit;
957
+ }
958
+ return undefined;
959
+ };
960
+
961
+ const unacceptedError = (missing: readonly LicenseDisclosure[], command: string): RpcError =>
962
+ new RpcError(
963
+ createDiagnostic("MOSTRA_LICENSE_UNACCEPTED", {
964
+ message: `This install brings ${missing.length === 1 ? "a license" : "licenses"} that need an acknowledgment: ${missing
965
+ .map(
966
+ (license) =>
967
+ `${license.id} (${license.class}; ${license.packages.map((pkg) => (pkg.version ? `${pkg.name}@${pkg.version}` : `the item ${pkg.name}`)).join(", ")})${license.summary ? `: ${license.summary}` : ""}${license.url ? ` ${license.url}` : ""}`,
968
+ )
969
+ .join("; ")}. Nothing was installed, and nothing of it ran.`,
970
+ fix: {
971
+ kind: "command",
972
+ command: `${command} ${missing.map((license) => `--accept-license ${shellWord(license.id)}`).join(" ")}`,
973
+ },
974
+ }),
975
+ );
976
+
977
+ const checkAccepted = (accept: readonly string[]): void => {
978
+ for (const id of accept) {
979
+ if (id === "*" || isLicenseRef(id) || spdxLicense(id) !== undefined) continue;
980
+ throw error(
981
+ "MOSTRA_LICENSE_ACCEPT_INVALID",
982
+ `"${id}" isn't an SPDX license ID, a LicenseRef- reference or *.`,
983
+ );
984
+ }
985
+ };
986
+
987
+ const scopeOf = (target: DependencyTarget): PluginScope =>
988
+ target.key === HOME_KEY ? "home" : "artifact";
989
+
990
+ const scopeFlag = (scope: Scope): string =>
991
+ scope.kind === "home" ? "--global" : `--artifact ${shellWord(scope.target.artifactPath)}`;
992
+
993
+ /**
994
+ * The gate (D172 items 5, 7 and 8): admits a staged lockfile's plugins, `order` in load order,
995
+ * with the licenses of everything the change brings. In this order, each refusing before the
996
+ * next starts: the static checks and conflicts; the licenses (nothing of the packages has run,
997
+ * their scripts are held); then `staged.ready()` runs the held scripts, and the Node.js
998
+ * entries load in a plugin child. Answers the lockfile's plugins and its acknowledgments after
999
+ * the change: every earlier one, and the ones this change made.
1000
+ */
1001
+ const admitSet = async (input: {
1002
+ readonly scope: PluginScope;
1003
+ readonly target: DependencyTarget;
1004
+ readonly staged: StagedChange;
1005
+ readonly order: readonly string[];
1006
+ readonly fresh?: readonly string[];
1007
+ readonly packages?: readonly string[];
1008
+ readonly items?: readonly ItemLicense[];
1009
+ readonly accept: readonly string[];
1010
+ readonly command: string;
1011
+ }) => {
1012
+ checkAccepted(input.accept);
1013
+ const set = await installedOf(
1014
+ { ...input.staged.lock, plugins: [...input.order] },
1015
+ input.staged.nodeModules,
1016
+ input.scope,
1017
+ );
1018
+ const fresh = set.filter((plugin) => input.fresh?.includes(plugin.name));
1019
+ const others = input.scope === "artifact" ? await homePlugins(false) : [];
1020
+ const checked = statics(set, others);
1021
+ const refusal = firstError(checked, fresh);
1022
+ if (refusal !== undefined) throw new RpcError(refusal);
1023
+ const extra: Installed[] = [];
1024
+ for (const name of input.packages ?? []) {
1025
+ const dir = join(input.staged.nodeModules, name);
1026
+ if (existsSync(join(dir, "package.json"))) extra.push(await readPackage(dir, "artifact"));
1027
+ }
1028
+ const licenses = await disclose({
1029
+ plugins: set,
1030
+ packages: extra,
1031
+ ...(input.items !== undefined ? { items: input.items } : {}),
1032
+ previous: input.staged.previous?.licenses,
1033
+ accept: input.accept,
1034
+ });
1035
+ if (licenses.missing.length > 0) throw unacceptedError(licenses.missing, input.command);
1036
+ await input.staged.ready();
1037
+ const entries = await inspectEntries(set, input.target.artifactDir);
1038
+ const loaded = merged(set, checked, entries, licenses.warnings);
1039
+ const broken = firstError(loaded, fresh);
1040
+ if (broken !== undefined) throw new RpcError(broken);
1041
+ return {
1042
+ set,
1043
+ fresh,
1044
+ loaded,
1045
+ licenses,
1046
+ plugins: [...input.order],
1047
+ // An acknowledgment is given once for the artifact (D31): it stays when a later change no
1048
+ // longer needs it, and one this change made joins it.
1049
+ record: { ...(input.staged.previous?.licenses ?? {}), ...licenses.record },
1050
+ };
1051
+ };
1052
+
1053
+ return {
1054
+ async admit(input) {
1055
+ const scope = scopeOf(input.target);
1056
+ const admitted = await admitSet({
1057
+ scope,
1058
+ target: input.target,
1059
+ staged: input.staged,
1060
+ order: input.staged.lock.plugins ?? [],
1061
+ accept: input.accept,
1062
+ command: input.command,
1063
+ });
1064
+ return { plugins: admitted.plugins, licenses: admitted.record };
1065
+ },
1066
+
1067
+ async admitChange(scope, input) {
1068
+ const target = scope.kind === "artifact" ? scope.target : homeTarget;
1069
+ const admitted = await admitSet({
1070
+ scope: scope.kind,
1071
+ target,
1072
+ staged: input.staged,
1073
+ order: input.staged.previous?.plugins ?? [],
1074
+ ...(input.packages !== undefined ? { packages: input.packages } : {}),
1075
+ ...(input.items !== undefined ? { items: input.items } : {}),
1076
+ accept: input.accept,
1077
+ command: input.command,
1078
+ });
1079
+ return {
1080
+ plugins: admitted.plugins,
1081
+ licenses: admitted.record,
1082
+ disclosures: admitted.licenses.disclosures.filter((license) =>
1083
+ license.packages.some(
1084
+ (pkg) =>
1085
+ pkg.item === true ||
1086
+ [...admitted.licenses.closures.entries()].some(
1087
+ ([owner, names]) => !admitted.set.includes(owner) && names.has(pkg.name),
1088
+ ),
1089
+ ),
1090
+ ),
1091
+ };
1092
+ },
1093
+
1094
+ async validate(path, accept) {
1095
+ checkAccepted(accept);
1096
+ const diagnostics: Diagnostic[] = [];
1097
+ if (!existsSync(join(path, "package.json"))) {
1098
+ throw error("MOSTRA_PLUGIN_NOT_A_PLUGIN", `${path} has no package.json.`);
1099
+ }
1100
+ const plugin = await readPackage(path, "artifact");
1101
+ const checked = statics([plugin], []);
1102
+ diagnostics.push(...(checked.get(plugin) ?? []));
1103
+ let blocked = false;
1104
+ if (plugin.manifest !== undefined) {
1105
+ // Licenses as far as the package's own directory shows them (its dependencies when
1106
+ // installed beside it), before any of its code runs: nothing loads whose license needs an
1107
+ // acknowledgment it hasn't been given.
1108
+ const licenses = await disclose({ plugins: [plugin], previous: undefined, accept }).catch(
1109
+ (problem: unknown) => {
1110
+ log.warn("plugins.validate_licenses", { message: String(problem) });
1111
+ return undefined;
1112
+ },
1113
+ );
1114
+ diagnostics.push(...(licenses?.warnings.get(plugin) ?? []));
1115
+ if (licenses !== undefined && licenses.missing.length > 0) {
1116
+ blocked = true;
1117
+ const refusal = unacceptedError(
1118
+ licenses.missing,
1119
+ `mostra plugin validate ${shellWord(path)}`,
1120
+ ).diagnostic;
1121
+ diagnostics.push({
1122
+ ...refusal,
1123
+ message: `${plugin.name} brings ${licenses.missing.map((license) => license.id).join(", ")}, which need an acknowledgment; its entries weren't loaded.`,
1124
+ });
1125
+ }
1126
+ }
1127
+ if (!blocked && firstError(checked) === undefined) {
1128
+ diagnostics.push(...((await inspectEntries([plugin], plugin.dir)).get(plugin) ?? []));
1129
+ }
1130
+ const valid = !diagnostics.some((diagnostic) => diagnostic.severity === "error");
1131
+ return {
1132
+ valid,
1133
+ ...(plugin.manifest !== undefined ? { plugin: summary(plugin, diagnostics) } : {}),
1134
+ diagnostics,
1135
+ };
1136
+ },
1137
+
1138
+ async add(scope, input) {
1139
+ const target = await targetOf(scope);
1140
+ return dependencies.change<PluginAddResult>(
1141
+ { ...target, add: input.packages, request: input.request },
1142
+ async (staged: StagedChange) => {
1143
+ const names = staged.added.map((pkg) => pkg.name);
1144
+ const previous = staged.previous?.plugins ?? [];
1145
+ const admitted = await admitSet({
1146
+ scope: scope.kind,
1147
+ target,
1148
+ staged,
1149
+ order: [...previous, ...names.filter((name) => !previous.includes(name))],
1150
+ fresh: names,
1151
+ accept: input.accept,
1152
+ command: `mostra plugin add ${input.packages.map(shellWord).join(" ")} ${scopeFlag(scope)}`,
1153
+ });
1154
+ log.info("plugins.added", {
1155
+ scope: scope.kind,
1156
+ plugins: names,
1157
+ licenses: Object.keys(admitted.licenses.record),
1158
+ });
1159
+ return {
1160
+ plugins: admitted.plugins,
1161
+ licenses: admitted.record,
1162
+ result: (lockDigest) => ({
1163
+ plugins: admitted.set.map((plugin) =>
1164
+ summary(plugin, admitted.loaded.get(plugin) ?? []),
1165
+ ),
1166
+ added: names,
1167
+ licenses: admitted.licenses.disclosures.filter((license) =>
1168
+ license.packages.some((pkg) =>
1169
+ admitted.fresh.some((plugin) =>
1170
+ admitted.licenses.closures.get(plugin)?.has(pkg.name),
1171
+ ),
1172
+ ),
1173
+ ),
1174
+ lockDigest,
1175
+ }),
1176
+ };
1177
+ },
1178
+ );
1179
+ },
1180
+
1181
+ async list(scope) {
1182
+ const target = await targetOf(scope);
1183
+ const staged = await dependencies.working(target);
1184
+ const set = await installedOf(staged?.lock, staged?.nodeModules, scope.kind);
1185
+ const others = scope.kind === "artifact" ? await homePlugins(false) : [];
1186
+ // What needs no code: listing never runs a plugin.
1187
+ const checked = statics(set, others);
1188
+ const licenses = await disclose({
1189
+ plugins: set,
1190
+ previous: staged?.lock.licenses,
1191
+ accept: [],
1192
+ });
1193
+ return {
1194
+ plugins: set.map((plugin) =>
1195
+ summary(plugin, [
1196
+ ...(checked.get(plugin) ?? []),
1197
+ ...(licenses.warnings.get(plugin) ?? []),
1198
+ ]),
1199
+ ),
1200
+ licenses: licenses.disclosures,
1201
+ };
1202
+ },
1203
+
1204
+ async remove(scope, input) {
1205
+ const target = await targetOf(scope);
1206
+ return dependencies.change<PluginRemoveResult>(
1207
+ { ...target, add: [], remove: input.packages, request: input.request },
1208
+ async (staged) => {
1209
+ // Read inside the change, which holds the lockfile's queue: a plugin another call
1210
+ // added meanwhile stays (WP-16 review R01 finding 4).
1211
+ const plugins = staged.previous?.plugins ?? [];
1212
+ for (const name of input.packages) {
1213
+ if (!plugins.includes(name)) {
1214
+ throw error(
1215
+ "MOSTRA_PLUGIN_NOT_INSTALLED",
1216
+ `${name} isn't a plugin of ${scope.kind === "home" ? "the home" : scope.target.artifactPath}; it has ${plugins.length > 0 ? plugins.join(", ") : "none"}.`,
1217
+ );
1218
+ }
1219
+ }
1220
+ const order = plugins.filter((name) => !input.packages.includes(name));
1221
+ const set = await installedOf(
1222
+ { ...staged.lock, plugins: order },
1223
+ staged.nodeModules,
1224
+ scope.kind,
1225
+ );
1226
+ const others = scope.kind === "artifact" ? await homePlugins(false) : [];
1227
+ const checked = statics(set, others);
1228
+ return {
1229
+ plugins: order,
1230
+ licenses: { ...(staged.previous?.licenses ?? {}) },
1231
+ result: (lockDigest) => ({
1232
+ removed: [...input.packages],
1233
+ plugins: set.map((plugin) => summary(plugin, checked.get(plugin) ?? [])),
1234
+ lockDigest,
1235
+ }),
1236
+ };
1237
+ },
1238
+ );
1239
+ },
1240
+
1241
+ async packItem(target, pkg, item) {
1242
+ const staged = await dependencies.working(target).catch(() => undefined);
1243
+ const own = await installedOf(staged?.lock, staged?.nodeModules, "artifact");
1244
+ for (const plugin of [...own, ...(await homePlugins(true))]) {
1245
+ if (plugin.name !== pkg) continue;
1246
+ for (const pack of plugin.manifest?.contributes.packs ?? []) {
1247
+ const file = resolve(plugin.dir, pack.item);
1248
+ if (!existsSync(file) || !isInside(plugin.dir, realpathSync(file))) continue;
1249
+ try {
1250
+ const data = JSON.parse(await readFile(file, "utf8")) as { name?: unknown };
1251
+ if (data.name === item) return realpathSync(file);
1252
+ } catch {
1253
+ // Not an item: `plugin/validate` reports it.
1254
+ }
1255
+ }
1256
+ }
1257
+ return undefined;
1258
+ },
1259
+
1260
+ async commands(target) {
1261
+ // A lookup for a word `mostra` doesn't know: it reads only layouts already installed, so a
1262
+ // typo never starts an install (WP-16 review, R01's addendum).
1263
+ const own =
1264
+ target === undefined
1265
+ ? []
1266
+ : await (async () => {
1267
+ const staged = await dependencies
1268
+ .working(target, { install: false })
1269
+ .catch(() => undefined);
1270
+ if (staged?.nodeModules === undefined) return [];
1271
+ return installedOf(staged.lock, staged.nodeModules, "artifact").catch(() => []);
1272
+ })();
1273
+ const found: PluginCommandInfo[] = [];
1274
+ // The artifact's own command wins over the home's of the same words (D172 item 5).
1275
+ for (const plugin of [...own, ...(await homePlugins(false))]) {
1276
+ for (const item of plugin.manifest ? contributionsOf(plugin.manifest) : []) {
1277
+ if (item.contract !== "cli-command") continue;
1278
+ if (found.some((command) => command.command === item.id)) continue;
1279
+ const file = resolve(plugin.dir, item.entry);
1280
+ if (!existsSync(file)) continue;
1281
+ found.push({
1282
+ command: item.id,
1283
+ package: plugin.name,
1284
+ version: plugin.version,
1285
+ scope: plugin.scope,
1286
+ file: realpathSync(file),
1287
+ export: item.export,
1288
+ });
1289
+ }
1290
+ }
1291
+ return found;
1292
+ },
1293
+
1294
+ async exporters(input) {
1295
+ // The version's own plugins, as its lockfile froze them (D172 item 6), in the layout it was
1296
+ // built against; then the home's. The artifact's own wins over the home's of one ID.
1297
+ const text = await readFile(join(input.versionDir, "lock.yaml"), "utf8");
1298
+ const lock = parseLock(text);
1299
+ const own =
1300
+ (lock.plugins ?? []).length === 0
1301
+ ? []
1302
+ : await installedOf(
1303
+ lock,
1304
+ await dependencies.runtimeModules({
1305
+ artifactId: input.artifactId,
1306
+ versionDir: input.versionDir,
1307
+ ...(input.sourceDir !== undefined ? { sourceDir: input.sourceDir } : {}),
1308
+ }),
1309
+ "artifact",
1310
+ );
1311
+ const home = await homePlugins(true);
1312
+ const found: ExporterRef[] = [];
1313
+ for (const plugin of [...own, ...home]) {
1314
+ const problem = staticChecks(plugin).find((diagnostic) => diagnostic.severity === "error");
1315
+ for (const item of plugin.manifest ? contributionsOf(plugin.manifest) : []) {
1316
+ if (item.contract !== "exporter") continue;
1317
+ if (found.some((exporter) => exporter.id === item.id)) continue;
1318
+ found.push({
1319
+ id: item.id,
1320
+ package: plugin.name,
1321
+ scope: plugin.scope,
1322
+ file: realpathSync(resolve(plugin.dir, item.entry)),
1323
+ export: item.export,
1324
+ dir: plugin.dir,
1325
+ ...(problem !== undefined ? { problem } : {}),
1326
+ });
1327
+ }
1328
+ }
1329
+ return found;
1330
+ },
1331
+
1332
+ async runExport(input) {
1333
+ if (input.exporter.problem !== undefined) throw new RpcError(input.exporter.problem);
1334
+ const request: ExportRequest = {
1335
+ file: input.exporter.file,
1336
+ export: input.exporter.export,
1337
+ id: input.exporter.id,
1338
+ implemented: implementedOf("exporter"),
1339
+ versionDir: input.versionDir,
1340
+ version: input.version,
1341
+ options: input.options,
1342
+ mostraVersion: options.runtimeVersion,
1343
+ };
1344
+ const answer = await inChild<ExportResponse>(
1345
+ input.exporter.dir,
1346
+ `export:${input.exporter.id}`,
1347
+ (child) =>
1348
+ child.request(EXPORT_METHOD, request as unknown as Record<string, unknown>, {
1349
+ timeoutMs: childTimeoutMs,
1350
+ }) as Promise<ExportResponse>,
1351
+ );
1352
+ if ("refused" in answer) {
1353
+ throw error(
1354
+ answer.refused.code,
1355
+ `The exporter "${input.exporter.id}" (${input.exporter.package}) wasn't run: ${answer.refused.message}.`,
1356
+ );
1357
+ }
1358
+ return answer;
1359
+ },
1360
+ };
1361
+ }
1362
+
1363
+ /** A pack item's own license (its `mostra.license`), disclosed as a package's is. */
1364
+ export interface ItemLicense {
1365
+ readonly name: string;
1366
+ readonly license: string;
1367
+ /** For a `LicenseRef-`, the class the item declares (`mostra.licenseClass`). */
1368
+ readonly class?: LicenseClass;
1369
+ }
1370
+
1371
+ /** The reference an item's unreadable license is shown as. */
1372
+ function unreadableItemRef(name: string): string {
1373
+ return `LicenseRef-item-${name.replace(/[^A-Za-z0-9.-]/g, "-")}`;
1374
+ }
1375
+
1376
+ /** Whether `text` parses as a license expression. */
1377
+ function isReadable(text: string): boolean {
1378
+ try {
1379
+ parseLicenseExpression(text);
1380
+ return true;
1381
+ } catch {
1382
+ return false;
1383
+ }
1384
+ }
1385
+
1386
+ /** Whether two license expressions are the same once canonical. */
1387
+ function sameExpression(a: string, b: string): boolean {
1388
+ try {
1389
+ return (
1390
+ formatLicenseExpression(parseLicenseExpression(a)) ===
1391
+ formatLicenseExpression(parseLicenseExpression(b))
1392
+ );
1393
+ } catch {
1394
+ return a.trim() === b.trim();
1395
+ }
1396
+ }