@featurevisor/core 4.13.0 → 4.14.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 (148) hide show
  1. package/lib/builder/applyContextToDatafile.js +21 -1
  2. package/lib/builder/applyContextToDatafile.js.map +1 -1
  3. package/lib/builder/buildDatafile.d.ts +15 -1
  4. package/lib/builder/buildDatafile.js +48 -13
  5. package/lib/builder/buildDatafile.js.map +1 -1
  6. package/lib/builder/buildProject.js +9 -0
  7. package/lib/builder/buildProject.js.map +1 -1
  8. package/lib/builder/environments.d.ts +1 -2
  9. package/lib/builder/hashes.d.ts +9 -0
  10. package/lib/builder/hashes.js +16 -0
  11. package/lib/builder/hashes.js.map +1 -1
  12. package/lib/builder/schemas.d.ts +76 -0
  13. package/lib/builder/schemas.js +406 -0
  14. package/lib/builder/schemas.js.map +1 -0
  15. package/lib/catalog.d.ts +2 -0
  16. package/lib/catalog.js +3 -0
  17. package/lib/catalog.js.map +1 -1
  18. package/lib/cli/options.js +31 -4
  19. package/lib/cli/options.js.map +1 -1
  20. package/lib/config/allowedConditions.d.ts +6 -3
  21. package/lib/config/allowedConditions.js +9 -2
  22. package/lib/config/allowedConditions.js.map +1 -1
  23. package/lib/convert/check.js +5 -1
  24. package/lib/convert/check.js.map +1 -1
  25. package/lib/convert/plan.js +8 -2
  26. package/lib/convert/plan.js.map +1 -1
  27. package/lib/datasource/conditionLocations.d.ts +1 -1
  28. package/lib/datasource/conditionLocations.js +26 -0
  29. package/lib/datasource/conditionLocations.js.map +1 -1
  30. package/lib/datasource/datasource.d.ts +2 -0
  31. package/lib/datasource/datasource.js +5 -3
  32. package/lib/datasource/datasource.js.map +1 -1
  33. package/lib/datasource/expressions.d.ts +1 -1
  34. package/lib/datasource/testSpecs.js +3 -3
  35. package/lib/datasource/testSpecs.js.map +1 -1
  36. package/lib/diff/conditions.js +1 -1
  37. package/lib/diff/conditions.js.map +1 -1
  38. package/lib/diff/index.js +68 -1
  39. package/lib/diff/index.js.map +1 -1
  40. package/lib/diff/schemaWidening.d.ts +15 -0
  41. package/lib/diff/schemaWidening.js +275 -0
  42. package/lib/diff/schemaWidening.js.map +1 -0
  43. package/lib/find-usage/index.d.ts +16 -2
  44. package/lib/find-usage/index.js +114 -10
  45. package/lib/find-usage/index.js.map +1 -1
  46. package/lib/formatter/expressions.js +5 -2
  47. package/lib/formatter/expressions.js.map +1 -1
  48. package/lib/formatter/layout.d.ts +3 -2
  49. package/lib/formatter/layout.js +23 -4
  50. package/lib/formatter/layout.js.map +1 -1
  51. package/lib/formatter/style.d.ts +20 -2
  52. package/lib/formatter/style.js +49 -4
  53. package/lib/formatter/style.js.map +1 -1
  54. package/lib/generate-code/index.d.ts +4 -0
  55. package/lib/generate-code/index.js +10 -0
  56. package/lib/generate-code/index.js.map +1 -1
  57. package/lib/generate-code/typescript.d.ts +5 -0
  58. package/lib/generate-code/typescript.js +265 -25
  59. package/lib/generate-code/typescript.js.map +1 -1
  60. package/lib/generate-code/widenMutations.d.ts +9 -0
  61. package/lib/generate-code/widenMutations.js +134 -0
  62. package/lib/generate-code/widenMutations.js.map +1 -0
  63. package/lib/linter/composedOverrideSchema.js +3 -0
  64. package/lib/linter/composedOverrideSchema.js.map +1 -1
  65. package/lib/linter/conditionKinds.d.ts +1 -1
  66. package/lib/linter/conditionKinds.js +4 -0
  67. package/lib/linter/conditionKinds.js.map +1 -1
  68. package/lib/linter/conditionSchema.d.ts +21 -1
  69. package/lib/linter/conditionSchema.js +261 -135
  70. package/lib/linter/conditionSchema.js.map +1 -1
  71. package/lib/linter/contextWarnings.js +2 -0
  72. package/lib/linter/contextWarnings.js.map +1 -1
  73. package/lib/linter/diagnostics.d.ts +10 -3
  74. package/lib/linter/diagnostics.js +16 -2
  75. package/lib/linter/diagnostics.js.map +1 -1
  76. package/lib/linter/expressionDiagnostics.js +2 -2
  77. package/lib/linter/expressionDiagnostics.js.map +1 -1
  78. package/lib/linter/featureSchema.d.ts +10 -9
  79. package/lib/linter/featureSchema.js +60 -158
  80. package/lib/linter/featureSchema.js.map +1 -1
  81. package/lib/linter/lintProject.js +229 -2
  82. package/lib/linter/lintProject.js.map +1 -1
  83. package/lib/linter/messageWarnings.d.ts +16 -0
  84. package/lib/linter/messageWarnings.js +181 -0
  85. package/lib/linter/messageWarnings.js.map +1 -0
  86. package/lib/linter/regexSafety.d.ts +17 -2
  87. package/lib/linter/regexSafety.js +257 -13
  88. package/lib/linter/regexSafety.js.map +1 -1
  89. package/lib/linter/reservedNames.d.ts +21 -0
  90. package/lib/linter/reservedNames.js +79 -0
  91. package/lib/linter/reservedNames.js.map +1 -1
  92. package/lib/linter/schema.d.ts +45 -3
  93. package/lib/linter/schema.js +341 -35
  94. package/lib/linter/schema.js.map +1 -1
  95. package/lib/linter/schemaAnnotations.d.ts +34 -0
  96. package/lib/linter/schemaAnnotations.js +409 -0
  97. package/lib/linter/schemaAnnotations.js.map +1 -0
  98. package/lib/linter/schemaEngine.d.ts +7 -0
  99. package/lib/linter/schemaEngine.js +80 -0
  100. package/lib/linter/schemaEngine.js.map +1 -0
  101. package/lib/linter/schemaFormats.d.ts +6 -0
  102. package/lib/linter/schemaFormats.js +20 -0
  103. package/lib/linter/schemaFormats.js.map +1 -1
  104. package/lib/linter/schemaMutations.d.ts +38 -0
  105. package/lib/linter/schemaMutations.js +617 -0
  106. package/lib/linter/schemaMutations.js.map +1 -0
  107. package/lib/linter/schemaPatterns.d.ts +26 -0
  108. package/lib/linter/schemaPatterns.js +316 -0
  109. package/lib/linter/schemaPatterns.js.map +1 -0
  110. package/lib/linter/schemaReferences.d.ts +18 -0
  111. package/lib/linter/schemaReferences.js +43 -0
  112. package/lib/linter/schemaReferences.js.map +1 -0
  113. package/lib/linter/targetSchema.d.ts +3 -0
  114. package/lib/linter/targetSchema.js +3 -0
  115. package/lib/linter/targetSchema.js.map +1 -1
  116. package/lib/linter/testSchema.d.ts +1 -1
  117. package/lib/linter/testSchema.js +70 -11
  118. package/lib/linter/testSchema.js.map +1 -1
  119. package/lib/linter/variableSchema.d.ts +5 -5
  120. package/lib/linter/variableSchema.js +5 -5
  121. package/lib/linter/variableSchema.js.map +1 -1
  122. package/lib/linter/warningCodes.d.ts +1 -1
  123. package/lib/linter/warningCodes.js +4 -0
  124. package/lib/linter/warningCodes.js.map +1 -1
  125. package/lib/list/index.js +45 -4
  126. package/lib/list/index.js.map +1 -1
  127. package/lib/list/matrix.d.ts +6 -1
  128. package/lib/list/matrix.js +31 -0
  129. package/lib/list/matrix.js.map +1 -1
  130. package/lib/promoter/index.js +15 -0
  131. package/lib/promoter/index.js.map +1 -1
  132. package/lib/rewrite/conditions.d.ts +2 -1
  133. package/lib/rewrite/conditions.js +1 -0
  134. package/lib/rewrite/conditions.js.map +1 -1
  135. package/lib/schemaNodes.d.ts +50 -0
  136. package/lib/schemaNodes.js +146 -0
  137. package/lib/schemaNodes.js.map +1 -0
  138. package/lib/targeting.d.ts +28 -1
  139. package/lib/targeting.js +111 -0
  140. package/lib/targeting.js.map +1 -1
  141. package/lib/tester/segments.d.ts +3 -0
  142. package/lib/tester/testProject.d.ts +1 -1
  143. package/lib/tester/testProject.js +16 -3
  144. package/lib/tester/testProject.js.map +1 -1
  145. package/lib/tester/testSchema.d.ts +9 -0
  146. package/lib/tester/testSchema.js +130 -0
  147. package/lib/tester/testSchema.js.map +1 -0
  148. package/package.json +7 -6
@@ -0,0 +1,38 @@
1
+ import type { Schema } from "@featurevisor/types";
2
+ import type { z } from "zod";
3
+ import type { AllowedConditions } from "../config";
4
+ type Path = (string | number)[];
5
+ export interface MutationFinding {
6
+ path: Path;
7
+ message: string;
8
+ /** A stable code for machine readable output, such as `regex_backtracking`. */
9
+ code?: string;
10
+ /** Lint reports it as a warning, which does not fail it. */
11
+ warning?: boolean;
12
+ }
13
+ /**
14
+ * Whether a schema varies, by environment or under conditions, itself or
15
+ * through a schema it references, so no variable may use it: a variable's
16
+ * schema, values and type are the same everywhere and for everyone.
17
+ */
18
+ export declare function schemaVaries(key: string, schemasByKey: Record<string, Schema>, seen?: Set<string>): boolean;
19
+ interface MutationLintOptions {
20
+ projectConfig: {
21
+ environments?: unknown;
22
+ allowedConditions?: AllowedConditions;
23
+ };
24
+ schemasByKey: Record<string, Schema>;
25
+ /** The schema files' own Zod, which every resolved and mutated schema must pass. */
26
+ schemaZodSchema: z.ZodTypeAny;
27
+ /** Conditions as features take them, with `input` leaves too. */
28
+ conditionsZodSchema: z.ZodTypeAny;
29
+ }
30
+ /**
31
+ * Checks a schema file's `environments` and `mutations`: every path in a
32
+ * `mutate` reaches into what it changes, every environment's resolved schema
33
+ * and every combination of a node's mutations is still a valid schema,
34
+ * conditions are valid with `input` paths that name fields of their node, keys
35
+ * are unique within a node, and no mutation changes a `type`.
36
+ */
37
+ export declare function getSchemaMutationFindings(root: unknown, options: MutationLintOptions): MutationFinding[];
38
+ export {};
@@ -0,0 +1,617 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.schemaVaries = schemaVaries;
4
+ exports.getSchemaMutationFindings = getSchemaMutationFindings;
5
+ const sdk_1 = require("@featurevisor/sdk");
6
+ const mutationEntries_1 = require("../builder/mutationEntries");
7
+ const variableOverrideProgram_1 = require("../builder/variableOverrideProgram");
8
+ const targeting_1 = require("../targeting");
9
+ const schemaNodes_1 = require("../schemaNodes");
10
+ const conditionSchema_1 = require("./conditionSchema");
11
+ const featureSchema_1 = require("./featureSchema");
12
+ const reservedNames_1 = require("./reservedNames");
13
+ const schemaAnnotations_1 = require("./schemaAnnotations");
14
+ /** A node's lists of mutations: its list, or at a schema's root its list per environment. */
15
+ function mutationLists(mutations) {
16
+ if (Array.isArray(mutations))
17
+ return [mutations];
18
+ return (0, schemaNodes_1.isSchemaNode)(mutations) ? Object.values(mutations).filter(Array.isArray) : [];
19
+ }
20
+ /** Whether a schema has rules that change, by environment or under conditions, at any node. */
21
+ function hasChangingRules(node) {
22
+ if (!(0, schemaNodes_1.isSchemaNode)(node))
23
+ return false;
24
+ if (mutationLists(node.mutations).some((list) => list.length > 0))
25
+ return true;
26
+ if (Array.isArray(node.issues) && node.issues.length > 0)
27
+ return true;
28
+ let inside = false;
29
+ (0, schemaNodes_1.forEachSchemaChild)(node, (child) => {
30
+ inside = inside || hasChangingRules(child);
31
+ });
32
+ return inside;
33
+ }
34
+ /**
35
+ * Whether a schema varies, by environment or under conditions, itself or
36
+ * through a schema it references, so no variable may use it: a variable's
37
+ * schema, values and type are the same everywhere and for everyone.
38
+ */
39
+ function schemaVaries(key, schemasByKey, seen = new Set()) {
40
+ if (seen.has(key))
41
+ return false;
42
+ seen.add(key);
43
+ const schema = schemasByKey[key];
44
+ if (!schema)
45
+ return false;
46
+ if (hasChangingRules(schema))
47
+ return true;
48
+ for (const reference of (0, targeting_1.getSchemaReferences)(schema)) {
49
+ if (schemaVaries(reference, schemasByKey, seen))
50
+ return true;
51
+ }
52
+ return false;
53
+ }
54
+ /** Whether an operation changes a node's `mutations` or `issues`, through its path or in a node it writes. */
55
+ function changesRules(operation) {
56
+ const end = (0, schemaNodes_1.schemaPathEnd)(operation.path);
57
+ if (end === "rules")
58
+ return true;
59
+ return ("value" in operation &&
60
+ (0, schemaNodes_1.writtenSchemaNodes)(end, operation.value).some(({ node }) => hasChangingRules(node)));
61
+ }
62
+ /** What one part of an operation's path reaches in a value, or undefined when it reaches nothing. */
63
+ function step(current, part) {
64
+ if (typeof part === "object") {
65
+ return Array.isArray(current)
66
+ ? current.find((item) => (0, schemaNodes_1.isSchemaNode)(item) &&
67
+ part.select.values.some((value) => item[part.select.property] === value))
68
+ : undefined;
69
+ }
70
+ if (Array.isArray(current) && typeof part === "number")
71
+ return current[part];
72
+ if ((0, schemaNodes_1.isSchemaNode)(current) && typeof part === "string")
73
+ return (0, schemaNodes_1.hasOwn)(current, part) ? current[part] : undefined;
74
+ return undefined;
75
+ }
76
+ /** The part of an operation's path that a value lacks, or undefined when it reaches. */
77
+ function missingPart(target, operation) {
78
+ let current = target;
79
+ const last = operation.path.length - 1;
80
+ for (let index = 0; index <= last; index++) {
81
+ const part = operation.path[index];
82
+ const next = step(current, part);
83
+ if (next === undefined) {
84
+ // A new key can be set at the end, as a new property is added. Anything else must exist.
85
+ const mayBeNew = index === last && operation.op === "set";
86
+ const addable = Array.isArray(current) || ((0, schemaNodes_1.isSchemaNode)(current) && typeof part === "string");
87
+ return mayBeNew && addable ? undefined : index;
88
+ }
89
+ current = next;
90
+ }
91
+ return undefined;
92
+ }
93
+ /**
94
+ * Where a node a mutation writes, or a node inside it, has another `type`
95
+ * than the node it replaces, following `schema` references on both sides. A
96
+ * node written where none was is new, so it changes no type.
97
+ */
98
+ function findTypeChange(target, operation, schemasByKey) {
99
+ if (operation.op !== "set")
100
+ return undefined;
101
+ const compare = (written, replaced, at) => {
102
+ // A reference that names no schema is reported on its own.
103
+ const before = (0, schemaNodes_1.resolveSchemaNode)(replaced, schemasByKey);
104
+ const after = (0, schemaNodes_1.resolveSchemaNode)(written, schemasByKey);
105
+ if (!before || !after)
106
+ return undefined;
107
+ if (after.type !== before.type)
108
+ return { at, from: before.type, to: after.type };
109
+ let found;
110
+ // A node that resolves is a node, so its children are the ones it writes.
111
+ (0, schemaNodes_1.forEachSchemaChild)(written, (child, parts) => {
112
+ found || (found = compare(child, parts.reduce(step, before), [...at, ...parts]));
113
+ });
114
+ return found;
115
+ };
116
+ // A node's `schema` pointed at another schema writes that schema in the node's place.
117
+ const owner = operation.path.slice(0, -1);
118
+ if (operation.path[operation.path.length - 1] === "schema" &&
119
+ (0, schemaNodes_1.schemaPathEnd)(owner) === "node" &&
120
+ typeof operation.value === "string") {
121
+ return compare({ schema: operation.value }, owner.reduce(step, target), owner);
122
+ }
123
+ for (const { node, path } of (0, schemaNodes_1.writtenSchemaNodes)((0, schemaNodes_1.schemaPathEnd)(operation.path), operation.value)) {
124
+ const at = [...operation.path, ...path];
125
+ const found = compare(node, at.reduce(step, target), at);
126
+ if (found)
127
+ return found;
128
+ }
129
+ return undefined;
130
+ }
131
+ function describeType(type) {
132
+ return type === undefined ? "no `type`" : `type ${JSON.stringify(type)}`;
133
+ }
134
+ function readable(path, upTo) {
135
+ return path
136
+ .slice(0, upTo + 1)
137
+ .map((part) => typeof part === "object"
138
+ ? `[${part.select.property}=${part.select.values[0]}]`
139
+ : typeof part === "number"
140
+ ? `[${part}]`
141
+ : part)
142
+ .join(".")
143
+ .replace(/\.\[/g, "[");
144
+ }
145
+ /** Whether conditions read the value validated, through any group. */
146
+ function readsInput(conditions) {
147
+ if (Array.isArray(conditions))
148
+ return conditions.some(readsInput);
149
+ if (!(0, schemaNodes_1.isSchemaNode)(conditions))
150
+ return false;
151
+ if (typeof conditions.input === "string")
152
+ return true;
153
+ return ["and", "or", "not"].some((group) => readsInput(conditions[group]));
154
+ }
155
+ /** A copy of the root with the node at a path replaced, so the whole file can be validated. */
156
+ function withNode(root, path, node) {
157
+ if (path.length === 0)
158
+ return node;
159
+ const [head, ...rest] = path;
160
+ if (Array.isArray(root)) {
161
+ const copy = root.slice();
162
+ copy[head] = withNode(root[head], rest, node);
163
+ return copy;
164
+ }
165
+ const record = root;
166
+ return { ...record, [head]: withNode(record[head], rest, node) };
167
+ }
168
+ /** Each `default` annotation in a schema that its own node's rules reject, by where it sits. */
169
+ function failingDefaults(node, at, schemasByKey, out = []) {
170
+ if (!(0, schemaNodes_1.isSchemaNode)(node))
171
+ return out;
172
+ const annotations = node.annotations;
173
+ if ((0, schemaNodes_1.isSchemaNode)(annotations) &&
174
+ (0, schemaNodes_1.hasOwn)(annotations, "default") &&
175
+ !(0, featureSchema_1.valueMatchesSchema)(node, annotations.default, schemasByKey)) {
176
+ out.push([...at, "annotations", "default"]);
177
+ }
178
+ (0, schemaNodes_1.forEachSchemaChild)(node, (child, part) => failingDefaults(child, [...at, ...part], schemasByKey, out));
179
+ return out;
180
+ }
181
+ /** The field a dot path names in a node, through references, or undefined when there is none. */
182
+ function fieldAt(node, fieldPath, schemasByKey) {
183
+ let current = (0, schemaNodes_1.resolveSchemaNode)(node, schemasByKey);
184
+ let field;
185
+ for (const part of fieldPath.split(".")) {
186
+ const properties = current && (0, schemaNodes_1.isSchemaNode)(current.properties) ? current.properties : undefined;
187
+ if (!properties || !(0, schemaNodes_1.hasOwn)(properties, part) || !(0, schemaNodes_1.isSchemaNode)(properties[part]))
188
+ return undefined;
189
+ field = properties[part];
190
+ current = (0, schemaNodes_1.resolveSchemaNode)(field, schemasByKey);
191
+ }
192
+ return field;
193
+ }
194
+ function namesField(node, fieldPath, schemasByKey) {
195
+ return !!fieldAt(node, fieldPath, schemasByKey);
196
+ }
197
+ function fieldNames(node, schemasByKey) {
198
+ const own = (0, schemaNodes_1.resolveSchemaNode)(node, schemasByKey);
199
+ return ((own && (0, schemaNodes_1.isSchemaNode)(own.properties) ? Object.keys(own.properties) : []).join(", ") || "none");
200
+ }
201
+ /** Calls `visit` with each entry of a list of issues or mutations that is a map, and its path. */
202
+ function forEachEntry(list, at, visit) {
203
+ if (!Array.isArray(list))
204
+ return;
205
+ list.forEach((entry, index) => {
206
+ if ((0, schemaNodes_1.isSchemaNode)(entry))
207
+ visit(entry, [...at, index]);
208
+ });
209
+ }
210
+ /** Reports a key an issue or a mutation shares with an earlier one in its node, then records it. */
211
+ function checkKey(keys, entry, here, noun, findings) {
212
+ if (keys.has(entry.key)) {
213
+ findings.push({
214
+ path: [...here, "key"],
215
+ message: `${noun} key "${entry.key}" is used twice in this node.`,
216
+ });
217
+ }
218
+ keys.add(entry.key);
219
+ }
220
+ /** What a finding of a schema says and where, to report each once. */
221
+ function findingKey({ path, message }) {
222
+ return JSON.stringify([path, message]);
223
+ }
224
+ /** Why the SDK cannot apply an operation that compiles and reaches into its node, in lint's words. */
225
+ const NOT_APPLIED = {
226
+ "Variable mutation expected an array": "what it reaches is not a list",
227
+ "Variable mutation expected an object": "what it reaches is not a map",
228
+ };
229
+ /** A node with steps applied in order, or the first step that cannot apply and why. */
230
+ function applySteps(node, steps) {
231
+ let value = node;
232
+ for (const step of steps) {
233
+ try {
234
+ value = (0, sdk_1.applyVariableOperations)(value, [step.operation]);
235
+ }
236
+ catch (error) {
237
+ const message = error instanceof Error ? error.message : String(error);
238
+ return {
239
+ failed: step,
240
+ reason: NOT_APPLIED[message] ?? `applying it fails with "${message}"`,
241
+ };
242
+ }
243
+ }
244
+ return { value };
245
+ }
246
+ /**
247
+ * Checks a schema file's `environments` and `mutations`: every path in a
248
+ * `mutate` reaches into what it changes, every environment's resolved schema
249
+ * and every combination of a node's mutations is still a valid schema,
250
+ * conditions are valid with `input` paths that name fields of their node, keys
251
+ * are unique within a node, and no mutation changes a `type`.
252
+ */
253
+ function getSchemaMutationFindings(root, options) {
254
+ const { projectConfig, schemasByKey, schemaZodSchema, conditionsZodSchema } = options;
255
+ const findings = [];
256
+ if (!(0, schemaNodes_1.isSchemaNode)(root))
257
+ return findings;
258
+ /** Compiles a `mutate`, reporting what does not compile or reach into its target. */
259
+ const compile = (mutate, target, path, forbidType) => {
260
+ if (!(0, schemaNodes_1.isSchemaNode)(mutate) && !Array.isArray(mutate)) {
261
+ findings.push({
262
+ path,
263
+ message: "`mutate` must be a map from paths to the values they set, such as `properties.displayName.maxLength: 60`, or a list of such maps.",
264
+ });
265
+ return undefined;
266
+ }
267
+ let entries;
268
+ try {
269
+ entries = (0, mutationEntries_1.mutationEntries)(mutate);
270
+ }
271
+ catch (error) {
272
+ findings.push({ path, message: error.message });
273
+ return undefined;
274
+ }
275
+ const operations = [];
276
+ entries.forEach(([notation, value], index) => {
277
+ const at = [...path, ...(0, mutationEntries_1.mutationEntryPath)(mutate, index, notation)];
278
+ let operation;
279
+ try {
280
+ operation = (0, variableOverrideProgram_1.compileVariableMutation)(notation, value);
281
+ }
282
+ catch (error) {
283
+ findings.push({ path: at, message: error.message });
284
+ return;
285
+ }
286
+ // A datafile carries a node's mutations and issues compiled, and the values a mutation writes as written.
287
+ if (changesRules(operation)) {
288
+ findings.push({
289
+ path: at,
290
+ message: "A mutation cannot change `mutations` or `issues`, which apply when validating as the datafile compiles them. Write them on the node they belong to, where their conditions read its fields.",
291
+ });
292
+ return;
293
+ }
294
+ const missing = missingPart(target, operation);
295
+ if (missing !== undefined) {
296
+ findings.push({
297
+ path: at,
298
+ message: `\`${notation}\` reaches nothing: \`${readable(operation.path, missing)}\` is not there. A mutation changes what exists, and creates no objects on the way.`,
299
+ });
300
+ return;
301
+ }
302
+ // A vocabulary is the project's, checked by lint and never delivered, so nothing changes it.
303
+ const vocabulary = operation.path.find((step, index) => (step === "optionSchema" || step === "annotationsSchema") &&
304
+ !["properties", "messages", "annotations", "options"].includes(String(operation.path[index - 1])));
305
+ if (vocabulary !== undefined) {
306
+ findings.push({
307
+ path: at,
308
+ message: `A mutation cannot change \`${vocabulary}\`, a vocabulary lint checks annotations against, which never reaches a datafile.`,
309
+ });
310
+ return;
311
+ }
312
+ // A node's own `type`, never a message or an annotation of that name, nor a field named so.
313
+ const typeAtNode = operation.path[operation.path.length - 1] === "type" &&
314
+ (0, schemaNodes_1.schemaPathEnd)(operation.path.slice(0, -1)) === "node";
315
+ const typeChange = forbidType && !typeAtNode && findTypeChange(target, operation, schemasByKey);
316
+ if (forbidType && (typeAtNode || typeChange)) {
317
+ findings.push({
318
+ path: at,
319
+ message: "A mutation cannot change a `type`, so a field's type is the same whatever matches, for reading form data and for generated types." +
320
+ (typeChange
321
+ ? ` It writes ${describeType(typeChange.to)} at \`${readable(typeChange.at, typeChange.at.length)}\`, which has ${describeType(typeChange.from)}.`
322
+ : ""),
323
+ });
324
+ return;
325
+ }
326
+ operations.push({ operation, notation, mutate: path });
327
+ });
328
+ return operations.length === entries.length ? operations : undefined;
329
+ };
330
+ // A default the authored rules reject is the annotations check's to report, and each
331
+ // other one is reported once, by the first resolved or mutated schema it fails in.
332
+ const reportedDefaults = new Set(failingDefaults(root, [], schemasByKey).map((at) => JSON.stringify(at)));
333
+ // So is every reserved name a mutation writes, and every other annotation finding, by where
334
+ // it sits and what it says.
335
+ const reportedNames = new Set((0, reservedNames_1.findReservedSchemaNames)(root).map(findingKey));
336
+ const authoredAnnotations = (0, schemaAnnotations_1.getSchemaAnnotationFindings)(root, schemasByKey);
337
+ const reportedAnnotations = new Set([...authoredAnnotations.errors, ...authoredAnnotations.warnings].map(findingKey));
338
+ /** Reports a resolved or mutated schema's issues under the entry that made it, and whether it passed. */
339
+ const validate = (schema, path, what) => {
340
+ for (const reserved of (0, reservedNames_1.findReservedSchemaNames)(schema)) {
341
+ if (reportedNames.has(findingKey(reserved)))
342
+ continue;
343
+ reportedNames.add(findingKey(reserved));
344
+ findings.push({
345
+ path,
346
+ message: `${what}, the schema fails: ${reserved.message} (at ${readable(reserved.path, reserved.path.length)})`,
347
+ code: "reserved_name",
348
+ });
349
+ }
350
+ const result = schemaZodSchema.safeParse(schema);
351
+ if (result.success) {
352
+ // A mutation can set a default, or change the rules a default must pass.
353
+ for (const at of failingDefaults(schema, [], schemasByKey)) {
354
+ // By the parts of the path, since a field's name can hold a dot.
355
+ if (reportedDefaults.has(JSON.stringify(at)))
356
+ continue;
357
+ reportedDefaults.add(JSON.stringify(at));
358
+ findings.push({
359
+ path,
360
+ message: `${what}, the \`default\` at ${readable(at, at.length)} does not pass its field's rules.`,
361
+ });
362
+ }
363
+ // A mutation can write annotations, or change what they are checked against.
364
+ const { errors, warnings } = (0, schemaAnnotations_1.getSchemaAnnotationFindings)(schema, schemasByKey);
365
+ for (const [finding, warning] of [
366
+ ...errors.filter((finding) => !finding.failingDefault).map((f) => [f, false]),
367
+ ...warnings.map((f) => [f, true]),
368
+ ]) {
369
+ if (reportedAnnotations.has(findingKey(finding)))
370
+ continue;
371
+ reportedAnnotations.add(findingKey(finding));
372
+ const where = readable(finding.path, finding.path.length) || "the root";
373
+ findings.push(warning
374
+ ? {
375
+ path,
376
+ message: `${what}: ${finding.message} (at ${where})`,
377
+ code: "option_without_title",
378
+ warning,
379
+ }
380
+ : { path, message: `${what}, the annotations fail: ${finding.message} (at ${where})` });
381
+ }
382
+ return true;
383
+ }
384
+ for (const issue of result.error.issues) {
385
+ findings.push({
386
+ path,
387
+ message: `${what}, the schema fails: ${issue.message} (at ${issue.path.join(".") || "the root"})`,
388
+ });
389
+ }
390
+ return false;
391
+ };
392
+ /** Checks the `input` leaves of a mutation's or an issue's conditions against the fields of its node. */
393
+ const checkInputs = (conditions, node, path) => {
394
+ const visit = (value, at) => {
395
+ if (Array.isArray(value))
396
+ return value.forEach((child, i) => visit(child, [...at, i]));
397
+ if (!(0, schemaNodes_1.isSchemaNode)(value))
398
+ return;
399
+ for (const group of ["and", "or", "not"])
400
+ if (Array.isArray(value[group]))
401
+ visit(value[group], [...at, group]);
402
+ for (const [field, read] of [
403
+ [["input"], value.input],
404
+ [["valueFrom", "input"], (0, schemaNodes_1.isSchemaNode)(value.valueFrom) ? value.valueFrom.input : undefined],
405
+ ]) {
406
+ if (typeof read === "string" && !namesField(node, read, schemasByKey)) {
407
+ findings.push({
408
+ path: [...at, ...field],
409
+ message: `\`input('${read}')\` names no field of this node, whose fields are ${fieldNames(node, schemasByKey)}. Paths are relative to the node a mutation or an issue sits on.`,
410
+ });
411
+ }
412
+ }
413
+ // The operator and value must suit the field compared, as an attribute's must.
414
+ if (typeof value.input !== "string" || typeof value.operator !== "string")
415
+ return;
416
+ const own = fieldAt(node, value.input, schemasByKey);
417
+ const from = (0, schemaNodes_1.isSchemaNode)(value.valueFrom) ? value.valueFrom.input : undefined;
418
+ const other = typeof from === "string" ? fieldAt(node, from, schemasByKey) : undefined;
419
+ if (!own || (typeof from === "string" && !other))
420
+ return;
421
+ for (const issue of (0, conditionSchema_1.getInputLeafIssues)(value, own, other, schemasByKey))
422
+ findings.push({ path: [...at, ...issue.path], message: issue.message });
423
+ };
424
+ visit(conditions, path);
425
+ };
426
+ /** Checks conditions as conditions, and their `input` leaves against the node's fields. */
427
+ const checkConditions = (conditions, node, at) => {
428
+ const parsed = conditionsZodSchema.safeParse(conditions);
429
+ let valid = true;
430
+ if (!parsed.success) {
431
+ for (const issue of parsed.error.issues) {
432
+ const { code, warning } = issue.params || {};
433
+ if (!warning)
434
+ valid = false;
435
+ findings.push({
436
+ path: [...at, ...issue.path],
437
+ message: issue.message,
438
+ ...(code ? { code } : {}),
439
+ ...(warning ? { warning } : {}),
440
+ });
441
+ }
442
+ }
443
+ if (valid)
444
+ checkInputs(conditions, node, at);
445
+ return valid;
446
+ };
447
+ /** Issues an object reports when their conditions match, after its own rules, nested at any depth. */
448
+ const checkIssues = (node, path) => {
449
+ const own = (0, schemaNodes_1.resolveSchemaNode)(node, schemasByKey);
450
+ if (!own || (own.type !== "object" && !(0, schemaNodes_1.isSchemaNode)(own.properties))) {
451
+ findings.push({
452
+ path: [...path, "issues"],
453
+ message: "`issues` goes on object nodes only, since its entries compare an object's fields.",
454
+ });
455
+ return;
456
+ }
457
+ // Keys are unique across the whole tree, since each is an issue's `params.refine`.
458
+ const keys = new Set();
459
+ const visitEntries = (list, at, readsAbove) => {
460
+ forEachEntry(list, at, (entry, here) => {
461
+ checkKey(keys, entry, here, "Issue", findings);
462
+ const valid = checkConditions(entry.conditions, node, [...here, "conditions"]);
463
+ // An entry nested under others matches only when they do, so their inputs count too.
464
+ const reads = readsAbove || (valid && readsInput(entry.conditions));
465
+ const nested = Array.isArray(entry.issues) ? entry.issues : undefined;
466
+ if (entry.message === undefined) {
467
+ if (!nested) {
468
+ findings.push({
469
+ path: [...here, "message"],
470
+ message: "An issue needs a `message`, or `issues` nested under it, which it groups under its conditions.",
471
+ });
472
+ }
473
+ else if (entry.path !== undefined) {
474
+ findings.push({
475
+ path: [...here, "path"],
476
+ message: "An issue's `path` says where its `message` goes, so an entry that only groups others takes none.",
477
+ });
478
+ }
479
+ }
480
+ else if (valid && !reads) {
481
+ findings.push({
482
+ path: [...here, "conditions"],
483
+ message: "An issue's conditions read at least one `input`, or it would fail every value for everyone they match. They say when a value fails, such as `input('confirmPassword') != input('password')`.",
484
+ });
485
+ }
486
+ if (typeof entry.path === "string" && !namesField(node, entry.path, schemasByKey)) {
487
+ findings.push({
488
+ path: [...here, "path"],
489
+ message: `\`${entry.path}\` names no field of this node, whose fields are ${fieldNames(node, schemasByKey)}. An issue's path is relative to the node it sits on.`,
490
+ });
491
+ }
492
+ visitEntries(nested, [...here, "issues"], reads);
493
+ });
494
+ };
495
+ visitEntries(node.issues, [...path, "issues"], false);
496
+ };
497
+ /**
498
+ * One list of a node's mutations, at a path, nested at any depth: each
499
+ * mutation after the ones it is nested in, then all of them together.
500
+ */
501
+ const checkMutations = (node, path, list, at) => {
502
+ // Keys are unique across the whole tree, since an issue names the mutation by its key.
503
+ const keys = new Set();
504
+ const all = [];
505
+ let complete = true;
506
+ /**
507
+ * `chain` holds the node as the mutations it is nested in leave it, or
508
+ * undefined when one of them failed.
509
+ */
510
+ const visitList = (entries, at, chain) => {
511
+ forEachEntry(entries, at, (mutation, here) => {
512
+ checkKey(keys, mutation, here, "Mutation", findings);
513
+ checkConditions(mutation.conditions, node, [...here, "conditions"]);
514
+ const nested = Array.isArray(mutation.mutations) ? mutation.mutations : undefined;
515
+ let next = chain;
516
+ if (mutation.mutate === undefined) {
517
+ if (!nested) {
518
+ findings.push({
519
+ path: [...here, "mutate"],
520
+ message: "A mutation needs a `mutate`, or `mutations` nested under it, which it groups under its conditions.",
521
+ });
522
+ }
523
+ }
524
+ else if (!chain) {
525
+ complete = false;
526
+ }
527
+ else {
528
+ // A nested mutation changes what the ones around it leave, so it can reach what they add.
529
+ const steps = compile(mutation.mutate, chain.value, [...here, "mutate"], true);
530
+ const applied = steps && applySteps(chain.value, steps);
531
+ if (!steps || !applied || "failed" in applied) {
532
+ if (applied && "failed" in applied) {
533
+ findings.push({
534
+ path: applied.failed.mutate,
535
+ message: `With mutation "${mutation.key}", \`${applied.failed.notation}\` cannot apply, since ${applied.reason}.`,
536
+ });
537
+ }
538
+ complete = false;
539
+ next = undefined;
540
+ }
541
+ else {
542
+ all.push({ key: String(mutation.key), steps });
543
+ next = { value: applied.value };
544
+ validate(withNode(root, path, applied.value), here, `With mutation "${mutation.key}"`);
545
+ }
546
+ }
547
+ visitList(nested, [...here, "mutations"], next);
548
+ });
549
+ };
550
+ visitList(list, at, { value: node });
551
+ // Every mutation can match together, so the rules must hold with all of them applied.
552
+ if (complete && all.length > 1) {
553
+ const applied = applySteps(node, all.flatMap(({ steps }) => steps));
554
+ if ("failed" in applied) {
555
+ const owner = all.find(({ steps }) => steps.includes(applied.failed));
556
+ findings.push({
557
+ path: applied.failed.mutate,
558
+ message: `With every mutation applied, \`${applied.failed.notation}\` of mutation "${owner.key}" cannot apply, since ${applied.reason}.`,
559
+ });
560
+ }
561
+ else {
562
+ validate(withNode(root, path, applied.value), at, "With every mutation applied");
563
+ }
564
+ }
565
+ };
566
+ const configured = Array.isArray(projectConfig.environments)
567
+ ? projectConfig.environments
568
+ : undefined;
569
+ // Mutations under conditions, at any node, applied when validating.
570
+ const visitNode = (node, path) => {
571
+ if (!(0, schemaNodes_1.isSchemaNode)(node))
572
+ return;
573
+ const mutations = node.mutations;
574
+ if (Array.isArray(mutations)) {
575
+ if (path.length === 0 && configured) {
576
+ findings.push({
577
+ path: ["mutations"],
578
+ message: `In a project with environments, a schema's root \`mutations\` go under environment names, as features' rules do, such as \`mutations: { ${configured[configured.length - 1]}: [...] }\`. A field's own mutations stay a list.`,
579
+ });
580
+ }
581
+ checkMutations(node, path, mutations, [...path, "mutations"]);
582
+ }
583
+ else if ((0, schemaNodes_1.isSchemaNode)(mutations)) {
584
+ if (path.length > 0) {
585
+ findings.push({
586
+ path: [...path, "mutations"],
587
+ message: "Only a schema's root lists its mutations by environment. A field's mutations are a list, the same in every environment.",
588
+ });
589
+ }
590
+ else if (!configured) {
591
+ findings.push({
592
+ path: ["mutations"],
593
+ message: "Mutations by environment need a project with environments, so this schema's `mutations` are a list. In a project with sets, each set has its own schema files.",
594
+ });
595
+ }
596
+ else {
597
+ for (const [environment, list] of Object.entries(mutations)) {
598
+ const at = ["mutations", environment];
599
+ if (!configured.includes(environment)) {
600
+ findings.push({
601
+ path: at,
602
+ message: `Unknown environment "${environment}". Environments: ${configured.join(", ")}.`,
603
+ });
604
+ }
605
+ else if (Array.isArray(list))
606
+ checkMutations(node, path, list, at);
607
+ }
608
+ }
609
+ }
610
+ if (Array.isArray(node.issues))
611
+ checkIssues(node, path);
612
+ (0, schemaNodes_1.forEachSchemaChild)(node, (child, part) => visitNode(child, [...path, ...part]));
613
+ };
614
+ visitNode(root, []);
615
+ return findings;
616
+ }
617
+ //# sourceMappingURL=schemaMutations.js.map