@mostra/protocol 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 (125) hide show
  1. package/dist/artifact-path.d.ts +22 -0
  2. package/dist/artifact-path.d.ts.map +1 -0
  3. package/dist/artifact-path.js +39 -0
  4. package/dist/artifact-path.js.map +1 -0
  5. package/dist/diagnostics/codes/index.d.ts +5 -2
  6. package/dist/diagnostics/codes/index.d.ts.map +1 -1
  7. package/dist/diagnostics/codes/index.js +7 -1
  8. package/dist/diagnostics/codes/index.js.map +1 -1
  9. package/dist/diagnostics/codes/license.d.ts +8 -0
  10. package/dist/diagnostics/codes/license.d.ts.map +1 -0
  11. package/dist/diagnostics/codes/license.js +55 -0
  12. package/dist/diagnostics/codes/license.js.map +1 -0
  13. package/dist/diagnostics/codes/pack.d.ts +8 -0
  14. package/dist/diagnostics/codes/pack.d.ts.map +1 -0
  15. package/dist/diagnostics/codes/pack.js +110 -0
  16. package/dist/diagnostics/codes/pack.js.map +1 -0
  17. package/dist/diagnostics/codes/plugin.d.ts +8 -0
  18. package/dist/diagnostics/codes/plugin.d.ts.map +1 -0
  19. package/dist/diagnostics/codes/plugin.js +154 -0
  20. package/dist/diagnostics/codes/plugin.js.map +1 -0
  21. package/dist/diagnostics/diagnostic.d.ts +1 -1
  22. package/dist/diagnostics/diagnostic.d.ts.map +1 -1
  23. package/dist/diagnostics/diagnostic.js +4 -1
  24. package/dist/diagnostics/diagnostic.js.map +1 -1
  25. package/dist/index.d.ts +13 -1
  26. package/dist/index.js +13 -1
  27. package/dist/methods/deps/add.d.ts +6 -0
  28. package/dist/methods/deps/add.d.ts.map +1 -1
  29. package/dist/methods/deps/add.js +1 -0
  30. package/dist/methods/deps/add.js.map +1 -1
  31. package/dist/methods/index.d.ts.map +1 -1
  32. package/dist/methods/index.js +15 -1
  33. package/dist/methods/index.js.map +1 -1
  34. package/dist/methods/mostra/initialize.d.ts +7 -0
  35. package/dist/methods/mostra/initialize.d.ts.map +1 -1
  36. package/dist/methods/mostra/initialize.js +4 -2
  37. package/dist/methods/mostra/initialize.js.map +1 -1
  38. package/dist/methods/pack/add.d.ts +80 -0
  39. package/dist/methods/pack/add.d.ts.map +1 -0
  40. package/dist/methods/pack/add.js +59 -0
  41. package/dist/methods/pack/add.js.map +1 -0
  42. package/dist/methods/plugin/add.d.ts +43 -0
  43. package/dist/methods/plugin/add.d.ts.map +1 -0
  44. package/dist/methods/plugin/add.js +39 -0
  45. package/dist/methods/plugin/add.js.map +1 -0
  46. package/dist/methods/plugin/commands.d.ts +38 -0
  47. package/dist/methods/plugin/commands.d.ts.map +1 -0
  48. package/dist/methods/plugin/commands.js +33 -0
  49. package/dist/methods/plugin/commands.js.map +1 -0
  50. package/dist/methods/plugin/export.d.ts +58 -0
  51. package/dist/methods/plugin/export.d.ts.map +1 -0
  52. package/dist/methods/plugin/export.js +57 -0
  53. package/dist/methods/plugin/export.js.map +1 -0
  54. package/dist/methods/plugin/list.d.ts +26 -0
  55. package/dist/methods/plugin/list.d.ts.map +1 -0
  56. package/dist/methods/plugin/list.js +30 -0
  57. package/dist/methods/plugin/list.js.map +1 -0
  58. package/dist/methods/plugin/remove.d.ts +32 -0
  59. package/dist/methods/plugin/remove.d.ts.map +1 -0
  60. package/dist/methods/plugin/remove.js +33 -0
  61. package/dist/methods/plugin/remove.js.map +1 -0
  62. package/dist/methods/plugin/validate.d.ts +35 -0
  63. package/dist/methods/plugin/validate.d.ts.map +1 -0
  64. package/dist/methods/plugin/validate.js +33 -0
  65. package/dist/methods/plugin/validate.js.map +1 -0
  66. package/dist/plugin/contract-versions.generated.js +14 -0
  67. package/dist/plugin/contract-versions.generated.js.map +1 -0
  68. package/dist/plugin/contracts.d.ts +51 -0
  69. package/dist/plugin/contracts.d.ts.map +1 -0
  70. package/dist/plugin/contracts.js +129 -0
  71. package/dist/plugin/contracts.js.map +1 -0
  72. package/dist/plugin/license.d.ts +87 -0
  73. package/dist/plugin/license.d.ts.map +1 -0
  74. package/dist/plugin/license.js +243 -0
  75. package/dist/plugin/license.js.map +1 -0
  76. package/dist/plugin/manifest.d.ts +141 -0
  77. package/dist/plugin/manifest.d.ts.map +1 -0
  78. package/dist/plugin/manifest.js +281 -0
  79. package/dist/plugin/manifest.js.map +1 -0
  80. package/dist/plugin/registry-item.d.ts +171 -0
  81. package/dist/plugin/registry-item.d.ts.map +1 -0
  82. package/dist/plugin/registry-item.js +162 -0
  83. package/dist/plugin/registry-item.js.map +1 -0
  84. package/dist/plugin/spdx.generated.d.ts +9 -0
  85. package/dist/plugin/spdx.generated.d.ts.map +1 -0
  86. package/dist/plugin/spdx.generated.js +846 -0
  87. package/dist/plugin/spdx.generated.js.map +1 -0
  88. package/dist/plugin.d.ts +7 -0
  89. package/dist/plugin.js +6 -0
  90. package/dist/plugins.d.ts +118 -0
  91. package/dist/plugins.d.ts.map +1 -0
  92. package/dist/plugins.js +109 -0
  93. package/dist/plugins.js.map +1 -0
  94. package/package.json +19 -4
  95. package/schemas/plugin-manifest.draft-07.json +611 -0
  96. package/schemas/plugin-manifest.schema.json +607 -0
  97. package/schemas/protocol.draft-07.json +899 -1
  98. package/schemas/protocol.schema.json +875 -1
  99. package/src/artifact-path.ts +46 -0
  100. package/src/diagnostics/codes/index.ts +14 -2
  101. package/src/diagnostics/codes/license.ts +65 -0
  102. package/src/diagnostics/codes/pack.ts +125 -0
  103. package/src/diagnostics/codes/plugin.ts +173 -0
  104. package/src/diagnostics/diagnostic.ts +7 -1
  105. package/src/index.ts +57 -0
  106. package/src/methods/deps/add.ts +7 -0
  107. package/src/methods/index.ts +14 -0
  108. package/src/methods/mostra/initialize.ts +9 -1
  109. package/src/methods/pack/add.ts +133 -0
  110. package/src/methods/plugin/add.ts +70 -0
  111. package/src/methods/plugin/commands.ts +67 -0
  112. package/src/methods/plugin/export.ts +100 -0
  113. package/src/methods/plugin/list.ts +45 -0
  114. package/src/methods/plugin/remove.ts +58 -0
  115. package/src/methods/plugin/validate.ts +60 -0
  116. package/src/plugin/contract-versions.generated.ts +15 -0
  117. package/src/plugin/contracts.ts +171 -0
  118. package/src/plugin/license.ts +320 -0
  119. package/src/plugin/manifest.ts +546 -0
  120. package/src/plugin/registry-item.ts +330 -0
  121. package/src/plugin/spdx-tables.ts +74 -0
  122. package/src/plugin/spdx.generated.ts +844 -0
  123. package/src/plugin.ts +77 -0
  124. package/src/plugins.ts +239 -0
  125. package/LICENSE +0 -202
@@ -0,0 +1,171 @@
1
+ /**
2
+ * The extension contracts Mostra implements (D30, ARCHITECTURE §13, ROUND-3 §6.1): each
3
+ * contract's package, the versions of it this release serves, where its contributions run, the
4
+ * manifest key that lists them and where a plugin with them may be installed.
5
+ */
6
+ import type { ContractName, PluginScope } from "../plugins.ts";
7
+ import { CONTRACT_VERSIONS } from "./contract-versions.generated.ts";
8
+
9
+ /** One contract as this release implements it. */
10
+ export interface ContractInfo {
11
+ /** Its name. */
12
+ readonly name: ContractName;
13
+ /** Its package: `@mostra/contract-<name>`. */
14
+ readonly package: string;
15
+ /**
16
+ * The versions of it this release serves, newest last. A plugin's range must admit one, and
17
+ * every stamp must be of a served line, at most that version (`stampCompatible`).
18
+ */
19
+ readonly implements: readonly string[];
20
+ /** Where its contributions run: the artifact's page, or Node.js (a child of the instance). */
21
+ readonly runs: "browser" | "node";
22
+ /** The key of the manifest's `contributes` that lists its contributions. */
23
+ readonly key: ContributesKey;
24
+ /** Where a plugin contributing it may be installed (ROUND-3 §6.4). */
25
+ readonly scopes: readonly PluginScope[];
26
+ }
27
+
28
+ /** The keys of a manifest's `contributes`, each a list of one kind of contribution. */
29
+ export type ContributesKey =
30
+ | "embedEngines"
31
+ | "exporters"
32
+ | "verifyChecks"
33
+ | "anchorProviders"
34
+ | "connectors"
35
+ | "cliCommands";
36
+
37
+ const info = (
38
+ name: ContractName,
39
+ key: ContributesKey,
40
+ runs: "browser" | "node",
41
+ scopes: readonly PluginScope[],
42
+ ): ContractInfo => ({
43
+ name,
44
+ package: `@mostra/contract-${name}`,
45
+ implements: [CONTRACT_VERSIONS[name]],
46
+ runs,
47
+ key,
48
+ scopes,
49
+ });
50
+
51
+ /**
52
+ * Every contract, by name. Exporters and CLI commands may also be installed for the whole home
53
+ * (ROUND-3 §6.4); the others change what an artifact's version is, so they belong to one artifact
54
+ * and its lockfile.
55
+ */
56
+ export const PLUGIN_CONTRACTS: Readonly<Record<ContractName, ContractInfo>> = {
57
+ "embed-engine": info("embed-engine", "embedEngines", "browser", ["artifact"]),
58
+ exporter: info("exporter", "exporters", "node", ["artifact", "home"]),
59
+ "verify-check": info("verify-check", "verifyChecks", "node", ["artifact"]),
60
+ "anchor-provider": info("anchor-provider", "anchorProviders", "browser", ["artifact"]),
61
+ connector: info("connector", "connectors", "node", ["artifact"]),
62
+ "cli-command": info("cli-command", "cliCommands", "node", ["artifact", "home"]),
63
+ };
64
+
65
+ /** The contracts in their manifest order. */
66
+ export const CONTRACT_NAMES: readonly ContractName[] = Object.keys(
67
+ PLUGIN_CONTRACTS,
68
+ ) as ContractName[];
69
+
70
+ /** The exporters Mostra builds in (VR-07): a plugin's exporter can't take their IDs. */
71
+ export const BUILT_IN_EXPORTERS: readonly string[] = ["static", "html", "bundle", "snapshot"];
72
+
73
+ /**
74
+ * Every command `mostra` has of its own (D60, INTERFACES §9), as its words: a plugin's command
75
+ * may be none of them, nor a prefix of one, nor have one as its prefix. The CLI's tests keep this
76
+ * list equal to its command table, plus the commands later packages add (`review export`, WP-20;
77
+ * `term dump`, WP-22), which are reserved from today.
78
+ */
79
+ export const CORE_COMMANDS: readonly (readonly string[])[] = [
80
+ ["add"],
81
+ ["daemon", "install"],
82
+ ["daemon", "restart"],
83
+ ["daemon", "start"],
84
+ ["daemon", "status"],
85
+ ["daemon", "stop"],
86
+ ["daemon", "uninstall"],
87
+ ["dev"],
88
+ ["docs"],
89
+ ["doctor"],
90
+ ["export"],
91
+ ["gc"],
92
+ ["host"],
93
+ ["list"],
94
+ ["login"],
95
+ ["logout"],
96
+ ["mcp"],
97
+ ["new"],
98
+ ["open"],
99
+ ["pause"],
100
+ ["plugin", "add"],
101
+ ["plugin", "list"],
102
+ ["plugin", "remove"],
103
+ ["plugin", "validate"],
104
+ ["publish"],
105
+ ["push"],
106
+ ["results"],
107
+ ["review", "export"],
108
+ ["resume"],
109
+ ["roster", "add"],
110
+ ["roster", "get"],
111
+ ["roster", "remove"],
112
+ ["run"],
113
+ ["secret", "list"],
114
+ ["secret", "rm"],
115
+ ["secret", "set"],
116
+ ["share"],
117
+ ["share", "list"],
118
+ ["share", "stop"],
119
+ ["state", "get"],
120
+ ["state", "patch"],
121
+ ["state", "set"],
122
+ ["status"],
123
+ ["telemetry", "off"],
124
+ ["telemetry", "on"],
125
+ ["telemetry", "status"],
126
+ ["term", "dump"],
127
+ ["verify"],
128
+ ["wait"],
129
+ ];
130
+
131
+ /** Whether a command path is taken by `mostra` itself (equal, or a prefix either way). */
132
+ export function coreCommandTaken(path: readonly string[]): readonly string[] | undefined {
133
+ return CORE_COMMANDS.find((core) => {
134
+ const shorter = Math.min(core.length, path.length);
135
+ for (let index = 0; index < shorter; index += 1) {
136
+ if (core[index] !== path[index]) return false;
137
+ }
138
+ return true;
139
+ });
140
+ }
141
+
142
+ /** `major.minor.patch` of a release version, or `undefined`. */
143
+ function versionParts(version: string): [number, number, number] | undefined {
144
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(version);
145
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : undefined;
146
+ }
147
+
148
+ /**
149
+ * Whether this release serves a definition stamped `stamp` for `contract`: the stamp names the
150
+ * contract on a line this release implements (the major, and at 0.x the minor), as each contract
151
+ * package's `stampCompatible` judges it. The version within the line is the manifest's range's to
152
+ * decide, which the loader checks first (D172 item 2): a plugin whose caret range resolved a newer
153
+ * patch of the contract package than this release's loads where its range admits this release's.
154
+ */
155
+ export function stampServed(
156
+ stamp: unknown,
157
+ contract: ContractName,
158
+ /** The versions served; this release's by default (a test stands in an older runtime's). */
159
+ implemented: readonly string[] = PLUGIN_CONTRACTS[contract].implements,
160
+ ): boolean {
161
+ if (typeof stamp !== "object" || stamp === null) return false;
162
+ const { name, version } = stamp as Record<string, unknown>;
163
+ if (name !== contract || typeof version !== "string") return false;
164
+ const theirs = versionParts(version);
165
+ if (theirs === undefined) return false;
166
+ return implemented.some((served) => {
167
+ const ours = versionParts(served);
168
+ if (ours === undefined || theirs[0] !== ours[0]) return false;
169
+ return ours[0] !== 0 || theirs[1] === ours[1];
170
+ });
171
+ }
@@ -0,0 +1,320 @@
1
+ /**
2
+ * License expressions and classes (D31, EX-04): what Mostra shows about a plugin's or a pack's
3
+ * licenses at install, and which of them need a one-time acknowledgment. An SPDX expression is
4
+ * parsed (SPDX 3.0 Annex B: `AND`, `OR`, `WITH`, `+`, parentheses, `LicenseRef-` and
5
+ * `DocumentRef-`), each license in it is classed from the SPDX License List's own flags, and an
6
+ * `OR` takes the branch that needs the fewest acknowledgments, as the person installing may choose.
7
+ */
8
+ import type { LicenseClass } from "../plugins.ts";
9
+ import { SPDX_EXCEPTIONS, SPDX_LICENSES } from "./spdx.generated.ts";
10
+
11
+ export { SPDX_LICENSE_LIST_VERSION } from "./spdx.generated.ts";
12
+
13
+ /** The classes whose licenses need `--accept-license` (or a host's pre-acceptance) at install. */
14
+ export const ACKNOWLEDGED_CLASSES: ReadonlySet<LicenseClass> = new Set([
15
+ "source-available",
16
+ "proprietary",
17
+ "unknown",
18
+ ]);
19
+
20
+ /**
21
+ * OSI-approved licenses that ask derivative or combined works to stay under them (copyleft,
22
+ * strong or weak), by family: everything else OSI-approved is `osi-permissive`. Either class
23
+ * needs no acknowledgment; the difference is shown.
24
+ */
25
+ const COPYLEFT =
26
+ /^(?:A?GPL|LGPL|MPL|EPL|EUPL|CDDL|CPL|OSL|RPL|SPL|Sleepycat|MS-RL|CECILL|CPAL|APSL|QPL|RPSL|NPOSL|SimPL|Watcom|IPL|OSET-PL|Motosoto|Nokia|LPL|CUA-OPL|ErlPL|SISSL|eCos|Interbase|NGPL|EFL|OCLC|LiLiQ-R|AFL)(?:[-.]|$)/;
27
+
28
+ /**
29
+ * Dedications to the public domain, and licenses that ask nothing at all: none needs an
30
+ * acknowledgment, OSI-approved or not (CC0 never was).
31
+ */
32
+ const PUBLIC_DOMAIN: ReadonlySet<string> = new Set([
33
+ "CC0-1.0",
34
+ "PDDL-1.0",
35
+ "CC-PDDC",
36
+ "CC-PDM-1.0",
37
+ "Unlicense",
38
+ "0BSD",
39
+ "WTFPL",
40
+ "MIT-0",
41
+ ]);
42
+
43
+ /** A license of the SPDX License List, as {@link spdxLicense} finds it. */
44
+ export interface SpdxEntry {
45
+ /** Its SPDX ID, in the List's own case. */
46
+ readonly id: string;
47
+ /** OSI-approved, as the List flags it. */
48
+ readonly osi: boolean;
49
+ /** Free (libre) by the FSF, as the List flags it. */
50
+ readonly free: boolean;
51
+ }
52
+
53
+ let byLowerCase: Map<string, SpdxEntry> | undefined;
54
+ let exceptionsByLowerCase: Map<string, string> | undefined;
55
+
56
+ /** An SPDX license ID in its canonical case with its flags, or `undefined` for one the list lacks. */
57
+ export function spdxLicense(id: string): SpdxEntry | undefined {
58
+ if (byLowerCase === undefined) {
59
+ byLowerCase = new Map();
60
+ for (const entry of SPDX_LICENSES) {
61
+ const at = entry.lastIndexOf(":");
62
+ const licenseId = entry.slice(0, at);
63
+ const flags = entry.slice(at + 1);
64
+ byLowerCase.set(licenseId.toLowerCase(), {
65
+ id: licenseId,
66
+ osi: flags.includes("o"),
67
+ free: flags.includes("f"),
68
+ });
69
+ }
70
+ }
71
+ return byLowerCase.get(id.toLowerCase());
72
+ }
73
+
74
+ /** An SPDX exception ID in its canonical case, or `undefined`. */
75
+ function spdxException(id: string): string | undefined {
76
+ exceptionsByLowerCase ??= new Map(SPDX_EXCEPTIONS.map((entry) => [entry.toLowerCase(), entry]));
77
+ return exceptionsByLowerCase.get(id.toLowerCase());
78
+ }
79
+
80
+ /** The pattern of a license reference: `LicenseRef-<idstring>`, optionally `DocumentRef-<idstring>:` first. */
81
+ const LICENSE_REF = /^(?:DocumentRef-[A-Za-z0-9.-]+:)?LicenseRef-[A-Za-z0-9.-]+$/;
82
+
83
+ /** Whether `id` is a license reference (never OSI-approved: it names a license only its author knows). */
84
+ export function isLicenseRef(id: string): boolean {
85
+ return LICENSE_REF.test(id);
86
+ }
87
+
88
+ /** A parsed SPDX license expression. */
89
+ export type LicenseExpression =
90
+ | { readonly kind: "license"; readonly id: string; readonly orLater: boolean }
91
+ | { readonly kind: "ref"; readonly id: string }
92
+ | { readonly kind: "with"; readonly license: LicenseExpression; readonly exception: string }
93
+ | {
94
+ readonly kind: "and" | "or";
95
+ readonly left: LicenseExpression;
96
+ readonly right: LicenseExpression;
97
+ };
98
+
99
+ /** Why an expression didn't parse. */
100
+ export class LicenseExpressionError extends Error {
101
+ /** `LicenseExpressionError`. */
102
+ override readonly name = "LicenseExpressionError";
103
+ }
104
+
105
+ /**
106
+ * Parses an SPDX license expression. License and exception IDs take their canonical case;
107
+ * operators are read in either case, as npm's ecosystem writes them.
108
+ *
109
+ * @throws LicenseExpressionError naming what isn't valid.
110
+ */
111
+ export function parseLicenseExpression(text: string): LicenseExpression {
112
+ const tokens = text.match(/\(|\)|[^\s()]+/g) ?? [];
113
+ if (tokens.length === 0) throw new LicenseExpressionError("The license expression is empty.");
114
+ let at = 0;
115
+ const peek = (): string | undefined => tokens[at];
116
+ const operator = (word: string | undefined): string | undefined => {
117
+ const upper = word?.toUpperCase();
118
+ return upper === "AND" || upper === "OR" || upper === "WITH" ? upper : undefined;
119
+ };
120
+ const simple = (): LicenseExpression => {
121
+ const token = tokens[at++];
122
+ if (token === undefined) throw new LicenseExpressionError("The expression ends too early.");
123
+ if (token === "(") {
124
+ const inner = or();
125
+ if (tokens[at++] !== ")") throw new LicenseExpressionError("A parenthesis isn't closed.");
126
+ return inner;
127
+ }
128
+ if (token === ")" || operator(token) !== undefined) {
129
+ throw new LicenseExpressionError(`"${token}" can't start a license.`);
130
+ }
131
+ if (isLicenseRef(token)) return { kind: "ref", id: token };
132
+ const orLater = token.endsWith("+");
133
+ const bare = orLater ? token.slice(0, -1) : token;
134
+ const known = spdxLicense(bare);
135
+ if (known === undefined) {
136
+ throw new LicenseExpressionError(
137
+ `"${token}" isn't an SPDX license ID or a LicenseRef- reference.`,
138
+ );
139
+ }
140
+ return { kind: "license", id: known.id, orLater };
141
+ };
142
+ const withExpression = (): LicenseExpression => {
143
+ const license = simple();
144
+ if (operator(peek()) !== "WITH") return license;
145
+ at += 1;
146
+ const token = tokens[at++];
147
+ const exception =
148
+ token === undefined
149
+ ? undefined
150
+ : (spdxException(token) ??
151
+ (/^(?:DocumentRef-[A-Za-z0-9.-]+:)?AdditionRef-[A-Za-z0-9.-]+$/.test(token)
152
+ ? token
153
+ : undefined));
154
+ if (exception === undefined) {
155
+ throw new LicenseExpressionError(`"${token ?? ""}" isn't an SPDX license exception.`);
156
+ }
157
+ if (license.kind !== "license" && license.kind !== "ref") {
158
+ throw new LicenseExpressionError("WITH applies to one license.");
159
+ }
160
+ return { kind: "with", license, exception };
161
+ };
162
+ const and = (): LicenseExpression => {
163
+ let left = withExpression();
164
+ while (operator(peek()) === "AND") {
165
+ at += 1;
166
+ left = { kind: "and", left, right: withExpression() };
167
+ }
168
+ return left;
169
+ };
170
+ const or = (): LicenseExpression => {
171
+ let left = and();
172
+ while (operator(peek()) === "OR") {
173
+ at += 1;
174
+ left = { kind: "or", left, right: and() };
175
+ }
176
+ return left;
177
+ };
178
+ const expression = or();
179
+ if (at < tokens.length) {
180
+ throw new LicenseExpressionError(`"${tokens[at]}" doesn't belong where it is.`);
181
+ }
182
+ return expression;
183
+ }
184
+
185
+ /** The canonical text of an expression. */
186
+ export function formatLicenseExpression(expression: LicenseExpression, nested = false): string {
187
+ switch (expression.kind) {
188
+ case "license":
189
+ return `${expression.id}${expression.orLater ? "+" : ""}`;
190
+ case "ref":
191
+ return expression.id;
192
+ case "with":
193
+ return `${formatLicenseExpression(expression.license)} WITH ${expression.exception}`;
194
+ default: {
195
+ const text = `${formatLicenseExpression(expression.left, expression.kind === "and")} ${expression.kind.toUpperCase()} ${formatLicenseExpression(expression.right, expression.kind === "and")}`;
196
+ return nested && expression.kind === "or" ? `(${text})` : text;
197
+ }
198
+ }
199
+ }
200
+
201
+ /** One license an expression comes down to, with its class. */
202
+ export interface LicenseTerm {
203
+ /** The license's ID: an SPDX ID or a `LicenseRef-` reference, which `--accept-license` names. */
204
+ readonly id: string;
205
+ /** Its class (D31). */
206
+ readonly class: LicenseClass;
207
+ }
208
+
209
+ /** The class of one SPDX license ID (canonical case). */
210
+ export function spdxClass(id: string): LicenseClass {
211
+ const known = spdxLicense(id);
212
+ if (known === undefined) return "unknown";
213
+ if (PUBLIC_DOMAIN.has(known.id)) return "public-domain";
214
+ if (known.osi) return COPYLEFT.test(known.id) ? "osi-copyleft" : "osi-permissive";
215
+ if (known.free) return "free";
216
+ return "source-available";
217
+ }
218
+
219
+ /**
220
+ * What an expression comes down to: every license that applies, each with its class. A
221
+ * reference's class is `declared(id)` (what the plugin's manifest says of it, never an OSI class)
222
+ * or `unknown`. An `OR` keeps the branch that needs the fewest acknowledgments, then the first.
223
+ */
224
+ export function licenseTerms(
225
+ expression: LicenseExpression,
226
+ declared: (id: string) => LicenseClass | undefined = () => undefined,
227
+ ): readonly LicenseTerm[] {
228
+ const needs = (terms: readonly LicenseTerm[]): number =>
229
+ terms.filter((term) => ACKNOWLEDGED_CLASSES.has(term.class)).length;
230
+ const walk = (node: LicenseExpression): LicenseTerm[] => {
231
+ switch (node.kind) {
232
+ case "license":
233
+ return [{ id: node.id, class: spdxClass(node.id) }];
234
+ case "ref": {
235
+ const declaredClass = declared(node.id);
236
+ return [
237
+ {
238
+ id: node.id,
239
+ class:
240
+ declaredClass !== undefined && ACKNOWLEDGED_CLASSES.has(declaredClass)
241
+ ? declaredClass
242
+ : "unknown",
243
+ },
244
+ ];
245
+ }
246
+ case "with":
247
+ return walk(node.license);
248
+ case "and": {
249
+ const terms = [...walk(node.left)];
250
+ for (const term of walk(node.right)) {
251
+ if (!terms.some((other) => other.id === term.id)) terms.push(term);
252
+ }
253
+ return terms;
254
+ }
255
+ case "or": {
256
+ const left = walk(node.left);
257
+ const right = walk(node.right);
258
+ return needs(right) < needs(left) ? right : left;
259
+ }
260
+ }
261
+ };
262
+ return walk(expression);
263
+ }
264
+
265
+ /**
266
+ * The license reference Mostra gives a package whose license it can't read (no `license` field,
267
+ * `SEE LICENSE IN …`, a string that isn't an expression), so `--accept-license` can still name
268
+ * it: `LicenseRef-npm-<name>` with the name's `@` and `/` as `-`.
269
+ */
270
+ export function unreadableLicenseRef(packageName: string): string {
271
+ return `LicenseRef-npm-${packageName.replace(/^@/, "").replace(/[^A-Za-z0-9.-]/g, "-")}`;
272
+ }
273
+
274
+ /**
275
+ * The license expression a package's `package.json` declares: `license` (a string, or the old
276
+ * `{ type }` form) or the old `licenses` array (each an alternative), or `undefined`.
277
+ */
278
+ export function packageLicense(manifest: {
279
+ readonly license?: unknown;
280
+ readonly licenses?: unknown;
281
+ }): string | undefined {
282
+ const text = (value: unknown): string | undefined =>
283
+ typeof value === "string"
284
+ ? value
285
+ : typeof value === "object" &&
286
+ value !== null &&
287
+ typeof (value as { type?: unknown }).type === "string"
288
+ ? (value as { type: string }).type
289
+ : undefined;
290
+ const single = text(manifest.license);
291
+ if (single !== undefined) return single.trim();
292
+ if (Array.isArray(manifest.licenses)) {
293
+ const all = manifest.licenses.map(text).filter((value) => value !== undefined);
294
+ if (all.length > 0) return all.length === 1 ? all[0] : `(${all.join(" OR ")})`;
295
+ }
296
+ return undefined;
297
+ }
298
+
299
+ /**
300
+ * The terms of a package's license field: its expression's, or, for a field Mostra can't read,
301
+ * one `unknown` term under {@link unreadableLicenseRef} (`UNLICENSED`, npm's word for "no license
302
+ * granted", is `proprietary`).
303
+ */
304
+ export function packageLicenseTerms(
305
+ packageName: string,
306
+ license: string | undefined,
307
+ declared?: (id: string) => LicenseClass | undefined,
308
+ ): readonly LicenseTerm[] {
309
+ if (license === "UNLICENSED") {
310
+ return [{ id: unreadableLicenseRef(packageName), class: "proprietary" }];
311
+ }
312
+ if (license !== undefined) {
313
+ try {
314
+ return licenseTerms(parseLicenseExpression(license), declared);
315
+ } catch (error) {
316
+ if (!(error instanceof LicenseExpressionError)) throw error;
317
+ }
318
+ }
319
+ return [{ id: unreadableLicenseRef(packageName), class: "unknown" }];
320
+ }