@cplieger/deadset-ts 8.0.0-dev.6 → 8.0.0-dev.8

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 (193) hide show
  1. package/dist/bin/mapper-connection.js +2 -1
  2. package/dist/bin/node-host.js +24 -5
  3. package/dist/src/analysis.js +37 -56
  4. package/dist/src/automatic-types.js +10 -29
  5. package/dist/src/build-scripts.js +17 -29
  6. package/dist/src/component-layer.js +4 -2
  7. package/dist/src/components.js +2 -3
  8. package/dist/src/config.js +6 -82
  9. package/dist/src/configuration-files.js +27 -168
  10. package/dist/src/configured-declarations.js +15 -20
  11. package/dist/src/consumers.js +2 -2
  12. package/dist/src/contract/config.generated.js +544 -0
  13. package/dist/src/contract/contract.generated.js +13 -0
  14. package/dist/src/contract/report.generated.js +3 -2
  15. package/dist/src/conventions.js +20 -60
  16. package/dist/src/dependencies.js +25 -43
  17. package/dist/src/discover.js +14 -40
  18. package/dist/src/edges.js +38 -122
  19. package/dist/src/element-access.js +4 -6
  20. package/dist/src/entry-point-gaps.js +2 -8
  21. package/dist/src/entry-points.js +3 -10
  22. package/dist/src/enum-group.js +3 -10
  23. package/dist/src/erased-stores.js +4 -6
  24. package/dist/src/exempt-classes.js +0 -4
  25. package/dist/src/exempt.js +6 -22
  26. package/dist/src/file-facts.js +2 -25
  27. package/dist/src/findings/completion.js +5 -4
  28. package/dist/src/findings/emitters.js +1 -1
  29. package/dist/src/findings/intra-function.js +1 -1
  30. package/dist/src/findings/non-code-artifacts.js +2 -2
  31. package/dist/src/findings/reads-and-writes.js +2 -1
  32. package/dist/src/findings/self-check.js +3 -2
  33. package/dist/src/findings/unused-declarations.js +1 -1
  34. package/dist/src/findings/visibility-narrowing.js +2 -2
  35. package/dist/src/findings-pass.js +7 -12
  36. package/dist/src/framework-lifecycle.js +7 -7
  37. package/dist/src/fs/document.js +59 -0
  38. package/dist/src/fs/manifest.js +43 -0
  39. package/dist/src/fs/tree.js +88 -0
  40. package/dist/src/git-ignore.js +34 -25
  41. package/dist/src/html-entries.js +6 -33
  42. package/dist/src/in-operands.js +2 -1
  43. package/dist/src/injection-container.js +1 -1
  44. package/dist/src/intra-function-parts.js +10 -13
  45. package/dist/src/inventory.js +2 -21
  46. package/dist/src/json-document.js +198 -67
  47. package/dist/src/keyof-comparisons.js +4 -6
  48. package/dist/src/kinds.js +0 -7
  49. package/dist/src/manifest.js +5 -43
  50. package/dist/src/mdx-entries.js +3 -26
  51. package/dist/src/partial.js +2 -1
  52. package/dist/src/paths.js +26 -15
  53. package/dist/src/position.js +2 -1
  54. package/dist/src/print.js +11 -79
  55. package/dist/src/product.js +13 -0
  56. package/dist/src/references.js +14 -27
  57. package/dist/src/report-schema.js +3 -225
  58. package/dist/src/report.js +22 -31
  59. package/dist/src/reporters/sarif.js +4 -2
  60. package/dist/src/reporters/template.js +4 -19
  61. package/dist/src/resolve.js +245 -724
  62. package/dist/src/roots.js +7 -17
  63. package/dist/src/run.js +55 -61
  64. package/dist/src/schema.js +320 -343
  65. package/dist/src/scope.js +34 -103
  66. package/dist/src/serialization-contract.js +5 -9
  67. package/dist/src/session.js +2 -1
  68. package/dist/src/suppress-file.js +21 -25
  69. package/dist/src/suppress.js +3 -3
  70. package/dist/src/symbol-keys.js +3 -5
  71. package/dist/src/template-field.js +9 -19
  72. package/dist/src/test-globals.js +6 -28
  73. package/dist/src/test-joins.js +6 -6
  74. package/dist/src/text/compare.js +26 -0
  75. package/dist/src/text/glob.js +194 -0
  76. package/dist/src/text/shell.js +159 -0
  77. package/dist/src/{yaml-document.js → text/yaml.js} +38 -0
  78. package/dist/src/type-errors.js +14 -38
  79. package/dist/src/unseen-loads.js +2 -9
  80. package/dist/src/unwrap.js +23 -0
  81. package/dist/src/usage.js +10 -0
  82. package/dist/src/verbs/analyze.js +25 -26
  83. package/dist/src/verbs/describe.js +4 -4
  84. package/dist/src/verbs/explain.js +8 -6
  85. package/dist/src/verbs/print-projects.js +4 -3
  86. package/dist/src/verbs/print-retained.js +2 -1
  87. package/dist/src/verbs/print-roots.js +2 -1
  88. package/dist/src/verbs/version.js +2 -1
  89. package/dist/src/workflow-steps.js +9 -46
  90. package/dist/src/workspace-manifests.js +2 -2
  91. package/dist/src/workspace-programs.js +5 -3
  92. package/dist/src/workspace-resolution.js +13 -17
  93. package/dist/src/workspace.js +28 -116
  94. package/jsr.json +1 -1
  95. package/package.json +1 -1
  96. package/src/analysis.ts +55 -76
  97. package/src/automatic-types.ts +11 -29
  98. package/src/build-scripts.ts +17 -38
  99. package/src/component-layer.ts +4 -2
  100. package/src/components.ts +2 -4
  101. package/src/config.ts +31 -296
  102. package/src/configuration-files.ts +27 -170
  103. package/src/configured-declarations.ts +18 -23
  104. package/src/consumers.ts +4 -4
  105. package/src/contract/config.generated.ts +798 -0
  106. package/src/contract/contract.generated.ts +25 -0
  107. package/src/contract/report.generated.ts +3 -2
  108. package/src/conventions.ts +26 -74
  109. package/src/dependencies.ts +32 -50
  110. package/src/discover.ts +15 -40
  111. package/src/edges.ts +41 -140
  112. package/src/element-access.ts +4 -7
  113. package/src/entry-point-gaps.ts +3 -9
  114. package/src/entry-points.ts +2 -13
  115. package/src/enum-group.ts +2 -11
  116. package/src/erased-stores.ts +3 -7
  117. package/src/exempt-classes.ts +0 -5
  118. package/src/exempt.ts +8 -30
  119. package/src/file-facts.ts +6 -24
  120. package/src/findings/completion.ts +5 -6
  121. package/src/findings/emitter.ts +2 -2
  122. package/src/findings/emitters.ts +1 -1
  123. package/src/findings/intra-function.ts +1 -1
  124. package/src/findings/non-code-artifacts.ts +4 -4
  125. package/src/findings/reads-and-writes.ts +2 -1
  126. package/src/findings/self-check.ts +3 -2
  127. package/src/findings/unused-declarations.ts +1 -1
  128. package/src/findings/visibility-narrowing.ts +2 -2
  129. package/src/findings-pass.ts +9 -15
  130. package/src/framework-lifecycle.ts +7 -7
  131. package/src/fs/document.ts +74 -0
  132. package/src/fs/manifest.ts +52 -0
  133. package/src/fs/tree.ts +110 -0
  134. package/src/git-ignore.ts +38 -25
  135. package/src/host.ts +12 -5
  136. package/src/html-entries.ts +6 -33
  137. package/src/in-operands.ts +2 -1
  138. package/src/injection-container.ts +1 -1
  139. package/src/intra-function-parts.ts +10 -14
  140. package/src/inventory.ts +2 -20
  141. package/src/json-document.ts +241 -76
  142. package/src/keyof-comparisons.ts +3 -7
  143. package/src/kinds.ts +0 -8
  144. package/src/manifest.ts +5 -46
  145. package/src/mdx-entries.ts +3 -26
  146. package/src/partial.ts +2 -1
  147. package/src/paths.ts +27 -15
  148. package/src/position.ts +2 -1
  149. package/src/print.ts +12 -92
  150. package/src/product.ts +18 -0
  151. package/src/references.ts +14 -29
  152. package/src/report-schema.ts +3 -301
  153. package/src/report.ts +24 -34
  154. package/src/reporters/sarif.ts +4 -4
  155. package/src/reporters/template.ts +4 -20
  156. package/src/resolve.ts +283 -1114
  157. package/src/roots.ts +7 -20
  158. package/src/run.ts +57 -75
  159. package/src/schema.ts +391 -388
  160. package/src/scope.ts +40 -126
  161. package/src/serialization-contract.ts +5 -10
  162. package/src/session.ts +2 -1
  163. package/src/suppress-file.ts +21 -29
  164. package/src/suppress.ts +3 -3
  165. package/src/symbol-keys.ts +2 -5
  166. package/src/template-field.ts +15 -25
  167. package/src/test-globals.ts +9 -27
  168. package/src/test-joins.ts +6 -8
  169. package/src/text/compare.ts +27 -0
  170. package/src/text/glob.ts +210 -0
  171. package/src/text/shell.ts +161 -0
  172. package/src/{yaml-document.ts → text/yaml.ts} +46 -0
  173. package/src/type-errors.ts +25 -36
  174. package/src/unseen-loads.ts +1 -12
  175. package/src/unwrap.ts +34 -0
  176. package/src/usage.ts +10 -0
  177. package/src/verbs/analyze.ts +32 -42
  178. package/src/verbs/describe.ts +4 -4
  179. package/src/verbs/explain.ts +8 -10
  180. package/src/verbs/print-projects.ts +4 -3
  181. package/src/verbs/print-retained.ts +2 -1
  182. package/src/verbs/print-roots.ts +2 -1
  183. package/src/verbs/verb.ts +2 -2
  184. package/src/verbs/version.ts +2 -1
  185. package/src/workflow-steps.ts +9 -44
  186. package/src/workspace-manifests.ts +2 -2
  187. package/src/workspace-programs.ts +5 -3
  188. package/src/workspace-resolution.ts +21 -17
  189. package/src/workspace.ts +35 -121
  190. package/dist/src/glob.js +0 -65
  191. package/dist/src/pnpm-workspace.js +0 -120
  192. package/src/glob.ts +0 -67
  193. package/src/pnpm-workspace.ts +0 -135
@@ -1,394 +1,371 @@
1
- import { ConfigError } from "./config.js";
2
- const leaf = { kind: "leaf" };
3
- const integer = { kind: "leaf", integer: true };
4
- /** A list of declarations, each entry in one of the three shapes the `ts` section states. */
5
- const declarations = {
6
- kind: "list",
7
- members: { symbol: leaf, module: leaf, name: leaf, global: leaf },
8
- };
9
1
  /**
10
- * The closed key list the Contract's configuration schema declares, derived from
11
- * that schema key by key. A test pins the two equal, so a Contract change that
12
- * adds a key fails there rather than being silently unimplemented.
2
+ * Holds a value to a JSON Schema the generator copies from the Contract. It evaluates the
3
+ * keywords the Contract's schemas use; the schemas' patterns are written to match alike in
4
+ * RE2 and in ECMAScript.
13
5
  */
14
- export const SCHEMA_ROOT = {
15
- kind: "section",
16
- members: {
17
- contract_version: leaf,
18
- target: {
19
- kind: "section",
20
- members: { kind: { kind: "object", members: { go: leaf, ts: leaf } } },
21
- },
22
- analysis: {
23
- kind: "section",
24
- members: {
25
- languages: leaf,
26
- min_confidence: leaf,
27
- generated_files: leaf,
28
- consumer_tests: leaf,
29
- configurations: {
30
- kind: "list",
31
- members: { id: leaf, os: leaf, arch: leaf, tags: leaf, project: leaf },
32
- },
33
- matrix: { kind: "section", members: { complete: leaf } },
34
- template_dirs: leaf,
35
- template_delimiters: {
36
- kind: "object",
37
- members: { left: leaf, right: leaf },
38
- },
39
- },
40
- },
41
- consumers: { kind: "section", members: { complete: leaf } },
42
- roots: { kind: "section", members: { patterns: leaf } },
43
- severity: { kind: "map" },
44
- exemptions: { kind: "section", members: { disabled: leaf } },
45
- reporters: {
46
- kind: "section",
47
- members: {
48
- formats: leaf,
49
- sort: leaf,
50
- cascade: leaf,
51
- max_findings: integer,
52
- fail_on: leaf,
53
- },
54
- },
55
- providers: {
56
- kind: "section",
57
- members: {
58
- analyzers: {
59
- kind: "list",
60
- members: {
61
- name: leaf,
62
- languages: leaf,
63
- command: leaf,
64
- source: leaf,
65
- version: leaf,
66
- digest: leaf,
67
- },
68
- },
69
- },
70
- },
71
- go: { kind: "section", members: {} },
72
- ts: {
73
- kind: "section",
74
- members: {
75
- test_files: leaf,
76
- entry_files: leaf,
77
- component_extensions: leaf,
78
- disabled_conventions: leaf,
79
- injection_registrations: declarations,
80
- lifecycle_contracts: {
81
- kind: "list",
82
- members: { components: declarations, bases: declarations, members: leaf },
83
- },
84
- serializers: declarations,
85
- roots_complete: leaf,
86
- },
87
- },
88
- provenance: { kind: "map" },
89
- },
90
- };
91
- /** The name of the severity object, whose member names the key list leaves open. */
92
- export const SEVERITY_SECTION = "severity";
6
+ import { isRecord, pointerOf, pointerSegments } from "./json-document.js";
7
+ import { bytewise } from "./text/compare.js";
93
8
  /**
94
- * The node one member name resolves to, and whether the key list declares it. A
95
- * member of an open object, and any member below a setting, resolves to a leaf,
96
- * so the walk descends far enough to find a repeated member at any depth.
9
+ * Every keyword the validator evaluates or knows to carry no assertion. A schema naming
10
+ * another fails every check rather than passing values the keyword would refuse.
97
11
  */
98
- function memberOf(node, name) {
99
- if (node.kind === "section" || node.kind === "list" || node.kind === "object") {
100
- const members = node.members ?? {};
101
- return Object.hasOwn(members, name) ? members[name] : undefined;
12
+ const KEYWORDS = new Set([
13
+ ...["$schema", "$id", "$comment", "$defs", "title", "description", "default", "examples"],
14
+ ...["$ref", "type", "enum", "const", "pattern", "minLength", "minimum", "maximum"],
15
+ ...["properties", "additionalProperties", "propertyNames", "required", "minProperties"],
16
+ ...["items", "minItems", "maxItems", "uniqueItems"],
17
+ ...["allOf", "anyOf", "oneOf", "not", "if", "then", "else"],
18
+ ]);
19
+ const patterns = new Map();
20
+ function pattern(source) {
21
+ let held = patterns.get(source);
22
+ if (held === undefined) {
23
+ held = new RegExp(source, "u");
24
+ patterns.set(source, held);
102
25
  }
103
- return leaf;
26
+ return held;
104
27
  }
105
- function joinKey(at, name) {
106
- return at === "" ? name : `${at}.${name}`;
107
- }
108
- function collect(node, at, keys, settingsOnly) {
109
- for (const [name, child] of Object.entries(node.members ?? {})) {
110
- const path = joinKey(at, name);
111
- if (!settingsOnly) {
112
- keys.push(path);
113
- collect(child, child.kind === "list" ? `${path}[]` : path, keys, settingsOnly);
114
- continue;
115
- }
116
- if (child.kind === "leaf" || child.kind === "list" || child.kind === "object") {
117
- keys.push(path);
118
- continue;
119
- }
120
- collect(child, path, keys, settingsOnly);
28
+ function typeOf(value) {
29
+ if (value === null) {
30
+ return "null";
121
31
  }
122
- }
123
- /**
124
- * Every key the closed key list declares, as a dotted path, in ascending order:
125
- * the sections, the settings, and the two open objects. A list's entry members
126
- * are spelled under the list's own path followed by empty brackets.
127
- */
128
- export function declaredKeys() {
129
- const keys = [];
130
- collect(SCHEMA_ROOT, "", keys, false);
131
- return keys.sort();
132
- }
133
- /**
134
- * The dotted path of every setting that holds one value, in ascending order. A
135
- * list and a setting written as an object are each one setting, their members not
136
- * addressable on their own, and the severity object is not among them: it
137
- * resolves per code.
138
- */
139
- export function settingPaths() {
140
- const paths = [];
141
- collect(SCHEMA_ROOT, "", paths, true);
142
- return paths.sort();
143
- }
144
- /**
145
- * Whether one dotted path names a setting a source may supply: a setting of the
146
- * closed key list, or one code of the severity object, whose member names the key
147
- * list leaves open. It is the predicate the command maps its own flag names
148
- * through, so a flag that would be refused as an unimplemented key is a failing
149
- * test rather than a flag nothing reads.
150
- *
151
- * A section holds no value of its own, so `analysis` is false. A setting written
152
- * as an object is supplied whole, so `analysis.template_delimiters` is true and
153
- * `analysis.template_delimiters.left` is false. A severity code is a declared
154
- * setting whatever it names, so `severity.DS9999` is true here and refused by
155
- * resolution: this answers the shape of a path, and resolution answers the
156
- * vocabulary.
157
- */
158
- export function declaresSetting(path) {
159
- if (settingPaths().includes(path)) {
160
- return true;
32
+ if (Array.isArray(value)) {
33
+ return "array";
161
34
  }
162
- const dot = path.indexOf(".");
163
- if (dot < 0) {
164
- return false;
35
+ if (typeof value === "number") {
36
+ return Number.isInteger(value) ? "integer" : "number";
165
37
  }
166
- const code = path.slice(dot + 1);
167
- return path.slice(0, dot) === SEVERITY_SECTION && code !== "" && !code.includes(".");
38
+ return typeof value;
168
39
  }
169
- /** The Levenshtein distance between two strings, counted in code points. */
170
- function editDistance(a, b) {
171
- const from = Array.from(a);
172
- const to = Array.from(b);
173
- let previous = Array.from({ length: to.length + 1 }, (_unused, index) => index);
174
- let current = new Array(to.length + 1).fill(0);
175
- for (let i = 1; i <= from.length; i += 1) {
176
- current[0] = i;
177
- for (let j = 1; j <= to.length; j += 1) {
178
- const substitution = (previous[j - 1] ?? 0) + (from[i - 1] === to[j - 1] ? 0 : 1);
179
- current[j] = Math.min(substitution, (previous[j] ?? 0) + 1, (current[j - 1] ?? 0) + 1);
180
- }
181
- [previous, current] = [current, previous];
40
+ function hasType(value, name) {
41
+ const held = typeOf(value);
42
+ return held === name || (name === "number" && held === "integer");
43
+ }
44
+ /** The types a schema names, none where it names no type. */
45
+ function typesOf(schema) {
46
+ const types = schema["type"];
47
+ if (types === undefined) {
48
+ return [];
182
49
  }
183
- return previous[to.length] ?? 0;
50
+ return (Array.isArray(types) ? types : [types]).filter((one) => typeof one === "string");
184
51
  }
185
- function sharedSegments(a, b) {
186
- let shared = 0;
187
- while (shared < a.length && shared < b.length && a[shared] === b[shared]) {
188
- shared += 1;
52
+ /** One value's encoding with object members sorted, so two equal values encode alike. */
53
+ function canonical(value) {
54
+ if (Array.isArray(value)) {
55
+ return `[${value.map(canonical).join(",")}]`;
56
+ }
57
+ if (isRecord(value)) {
58
+ return `{${Object.keys(value)
59
+ .sort(bytewise)
60
+ .map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`)
61
+ .join(",")}}`;
189
62
  }
190
- return shared;
63
+ return JSON.stringify(value);
191
64
  }
192
- /**
193
- * The implemented key closest to `key`: the one sharing the most leading dotted
194
- * segments, and among those the smallest edit distance over the whole path, ties
195
- * broken in ascending order.
196
- */
197
- export function nearestKey(key) {
198
- const segments = key.split(".");
199
- let nearest = "";
200
- let bestShared = -1;
201
- let bestDistance = 0;
202
- for (const candidate of declaredKeys()) {
203
- const shared = sharedSegments(segments, candidate.split("."));
204
- const distance = editDistance(key, candidate);
205
- if (shared < bestShared || (shared === bestShared && distance >= bestDistance)) {
206
- continue;
207
- }
208
- nearest = candidate;
209
- bestShared = shared;
210
- bestDistance = distance;
65
+ /** A string's length in code points, which JSON Schema's minLength counts. */
66
+ function codePoints(value) {
67
+ let counted = 0;
68
+ for (const _point of value) {
69
+ counted += 1;
211
70
  }
212
- return nearest;
71
+ return counted;
213
72
  }
214
- /** A refusal of a document that is not one instance of the closed key list. */
215
- export function malformed(label, path, detail) {
216
- const message = path === "" ? `${label}: ${detail}` : `${label}: ${path}: ${detail}`;
217
- return new ConfigError("malformed", path, message);
73
+ /** The schemas of a list keyword, none where the schema does not write it. */
74
+ function listOf(schema, keyword) {
75
+ const held = schema[keyword];
76
+ return Array.isArray(held) ? held : [];
218
77
  }
219
- /**
220
- * A refusal of a key the closed key list does not declare, naming the nearest key
221
- * it does.
222
- */
223
- function unimplementedKey(label, path) {
224
- const nearest = nearestKey(path);
225
- let hint = "";
226
- if (nearest === path) {
227
- hint = `. ${JSON.stringify(path)} is one setting written as nested objects, not as one key`;
78
+ /** Whether a reader fixes refusal `a` before `b`: an object's before one inside it, then by kind. */
79
+ function before(a, b) {
80
+ if (a.pointer === b.pointer) {
81
+ return rank(a) < rank(b);
228
82
  }
229
- else if (nearest !== "") {
230
- hint = `. The nearest implemented key is ${JSON.stringify(nearest)}`;
83
+ return b.pointer.startsWith(`${a.pointer}/`);
84
+ }
85
+ /** The order of the refusals of one place: an undeclared member, a missing one, any other. */
86
+ function rank(refusal) {
87
+ if (refusal.keyword === "additionalProperties" || refusal.keyword === "propertyNames") {
88
+ return 0;
231
89
  }
232
- return new ConfigError("unimplemented-key", path, `${label}: key ${JSON.stringify(path)} is not implemented${hint}`);
90
+ return refusal.keyword === "required" ? 1 : 2;
233
91
  }
234
- const SPACE = new Set([0x20, 0x09, 0x0a, 0x0d]);
235
- function skipSpace(cursor) {
236
- while (cursor.at < cursor.text.length && SPACE.has(cursor.text.charCodeAt(cursor.at))) {
237
- cursor.at += 1;
92
+ /** The value one JSON Pointer segment names inside `value`, or undefined. */
93
+ function valueAt(value, segment) {
94
+ if (Array.isArray(value)) {
95
+ return /^[0-9]+$/u.test(segment) ? value[Number(segment)] : undefined;
238
96
  }
97
+ return isRecord(value) && Object.hasOwn(value, segment) ? value[segment] : undefined;
239
98
  }
240
99
  /**
241
- * The string literal at the cursor, decoded by the standard library: the walk
242
- * finds the literal's extent and the parse reads it, so an escaped member name
243
- * compares equal to the name it spells.
100
+ * The schema `properties` declares for the member `name`, or undefined: a member named as an
101
+ * `Object.prototype` property, such as `__proto__`, is declared only where it is written.
244
102
  */
245
- function readName(cursor, at, label) {
246
- const start = cursor.at;
247
- cursor.at += 1;
248
- while (cursor.at < cursor.text.length) {
249
- const ch = cursor.text.charCodeAt(cursor.at);
250
- if (ch === 0x5c) {
251
- cursor.at += 2;
252
- continue;
253
- }
254
- cursor.at += 1;
255
- if (ch === 0x22) {
256
- return JSON.parse(cursor.text.slice(start, cursor.at));
103
+ function declaredMember(properties, name) {
104
+ return Object.hasOwn(properties, name) ? properties[name] : undefined;
105
+ }
106
+ /** The keyword checks over one set of schema documents, each named as a `$ref` names it. */
107
+ class Checker {
108
+ documents;
109
+ constructor(documents) {
110
+ this.documents = documents;
111
+ }
112
+ resolve(doc, ref) {
113
+ const [file = "", pointer = ""] = ref.split("#");
114
+ const target = file === "" ? doc : file;
115
+ let schema = this.documents[target];
116
+ for (const token of pointerSegments(pointer)) {
117
+ schema = isRecord(schema) ? schema[token] : undefined;
257
118
  }
119
+ if (!isRecord(schema)) {
120
+ throw new Error(`schema: ${ref} names no schema`);
121
+ }
122
+ return [target, schema];
258
123
  }
259
- throw malformed(label, at, "a member name is not terminated");
260
- }
261
- function skipScalar(cursor) {
262
- while (cursor.at < cursor.text.length) {
263
- const ch = cursor.text.charCodeAt(cursor.at);
264
- if (ch === 0x2c || ch === 0x7d || ch === 0x5d || SPACE.has(ch)) {
124
+ refusals(doc, schema, value, at) {
125
+ const found = [];
126
+ this.check(doc, schema, value, at, found);
127
+ return found;
128
+ }
129
+ matches(doc, schema, value, at) {
130
+ return this.refusals(doc, schema, value, at).length === 0;
131
+ }
132
+ check(doc, schema, value, at, found) {
133
+ for (const keyword of Object.keys(schema)) {
134
+ if (!KEYWORDS.has(keyword) && !keyword.startsWith("x-")) {
135
+ throw new Error(`schema: the keyword ${keyword} is not one this validator evaluates`);
136
+ }
137
+ }
138
+ const refuse = (keyword, reason, member = "") => {
139
+ found.push({ pointer: at, keyword, reason, member });
140
+ };
141
+ if (typeof schema["$ref"] === "string") {
142
+ const [target, referenced] = this.resolve(doc, schema["$ref"]);
143
+ this.check(target, referenced, value, at, found);
144
+ }
145
+ const named = typesOf(schema);
146
+ if (named.length > 0 && !named.some((one) => hasType(value, one))) {
147
+ refuse("type", `the value is ${typeOf(value)}, want ${named.join(", ")}`);
265
148
  return;
266
149
  }
267
- cursor.at += 1;
268
- }
269
- }
270
- /** A number the document writes as an optional minus sign and digits alone. */
271
- const INTEGER_TEXT = /^-?[0-9]+$/u;
272
- /** The start of a JSON number: a minus sign or a digit. */
273
- const NUMBER_START = /^[-0-9]/u;
274
- /**
275
- * Refuses a number written with a fraction or an exponent where the key list
276
- * declares an integer. A parse reads `100.0` and `1e2` as the integer 100, so only
277
- * the text can tell them apart. A scalar that is no number is the decoder's to
278
- * refuse by its type.
279
- */
280
- function checkInteger(text, at, label) {
281
- if (NUMBER_START.test(text) && !INTEGER_TEXT.test(text)) {
282
- throw malformed(label, at, `${text} is written with a fraction or an exponent, and an integer is digits alone`);
150
+ this.checkValue(schema, value, refuse);
151
+ if (Array.isArray(value)) {
152
+ this.checkArray(doc, schema, value, at, found, refuse);
153
+ }
154
+ else if (isRecord(value)) {
155
+ this.checkObject(doc, schema, value, at, found, refuse);
156
+ }
157
+ this.checkApplicators(doc, schema, value, at, found, refuse);
283
158
  }
284
- }
285
- function walkValue(cursor, at, node, label) {
286
- skipSpace(cursor);
287
- const ch = cursor.text.charCodeAt(cursor.at);
288
- if (ch === 0x7b) {
289
- cursor.at += 1;
290
- walkObject(cursor, at, node, label);
291
- return;
159
+ checkValue(schema, value, refuse) {
160
+ const values = schema["enum"];
161
+ if (Array.isArray(values) && !values.some((one) => canonical(one) === canonical(value))) {
162
+ refuse("enum", `${canonical(value)} is not one of ${values.map(canonical).join(", ")}`);
163
+ }
164
+ if (schema["const"] !== undefined && canonical(schema["const"]) !== canonical(value)) {
165
+ refuse("const", `${canonical(value)} is not ${canonical(schema["const"])}`);
166
+ }
167
+ if (typeof value === "string") {
168
+ if (typeof schema["pattern"] === "string" && !pattern(schema["pattern"]).test(value)) {
169
+ refuse("pattern", `${JSON.stringify(value)} does not match ${schema["pattern"]}`);
170
+ }
171
+ if (typeof schema["minLength"] === "number" && codePoints(value) < schema["minLength"]) {
172
+ refuse("minLength", `${JSON.stringify(value)} is shorter than ${String(schema["minLength"])} characters`);
173
+ }
174
+ }
175
+ if (typeof value === "number") {
176
+ if (typeof schema["minimum"] === "number" && value < schema["minimum"]) {
177
+ refuse("minimum", `${String(value)} is below ${String(schema["minimum"])}`);
178
+ }
179
+ if (typeof schema["maximum"] === "number" && value > schema["maximum"]) {
180
+ refuse("maximum", `${String(value)} is above ${String(schema["maximum"])}`);
181
+ }
182
+ }
292
183
  }
293
- if (ch === 0x5b) {
294
- cursor.at += 1;
295
- walkArray(cursor, at, node, label);
296
- return;
184
+ checkObject(doc, schema, value, at, found, refuse) {
185
+ const properties = isRecord(schema["properties"]) ? schema["properties"] : {};
186
+ const additional = schema["additionalProperties"];
187
+ const names = schema["propertyNames"];
188
+ for (const name of Object.keys(value).sort(bytewise)) {
189
+ const [refusedName] = isRecord(names) ? this.refusals(doc, names, name, at) : [];
190
+ if (refusedName !== undefined) {
191
+ refuse("propertyNames", `the member name ${JSON.stringify(name)}: ${refusedName.reason}`, name);
192
+ }
193
+ const member = `${at}${pointerOf([name])}`;
194
+ const declared = declaredMember(properties, name);
195
+ if (isRecord(declared)) {
196
+ this.check(doc, declared, value[name], member, found);
197
+ }
198
+ else if (additional === false) {
199
+ refuse("additionalProperties", `the member ${JSON.stringify(name)} is not one the schema declares`, name);
200
+ }
201
+ else if (isRecord(additional)) {
202
+ this.check(doc, additional, value[name], member, found);
203
+ }
204
+ }
205
+ for (const name of Array.isArray(schema["required"]) ? schema["required"] : []) {
206
+ if (!Object.hasOwn(value, name)) {
207
+ refuse("required", `the member ${JSON.stringify(name)} is absent`, name);
208
+ }
209
+ }
210
+ const fewest = schema["minProperties"];
211
+ if (typeof fewest === "number" && Object.keys(value).length < fewest) {
212
+ refuse("minProperties", `the object holds ${String(Object.keys(value).length)} members, fewer than ${String(fewest)}`);
213
+ }
297
214
  }
298
- if (ch === 0x22) {
299
- readName(cursor, at, label);
300
- return;
215
+ checkArray(doc, schema, value, at, found, refuse) {
216
+ const items = schema["items"];
217
+ if (isRecord(items)) {
218
+ value.forEach((item, i) => {
219
+ this.check(doc, items, item, `${at}/${String(i)}`, found);
220
+ });
221
+ }
222
+ if (typeof schema["minItems"] === "number" && value.length < schema["minItems"]) {
223
+ refuse("minItems", `the array holds ${String(value.length)} items, fewer than ${String(schema["minItems"])}`);
224
+ }
225
+ if (typeof schema["maxItems"] === "number" && value.length > schema["maxItems"]) {
226
+ refuse("maxItems", `the array holds ${String(value.length)} items, more than ${String(schema["maxItems"])}`);
227
+ }
228
+ if (schema["uniqueItems"] === true && new Set(value.map(canonical)).size !== value.length) {
229
+ refuse("uniqueItems", "the array lists one value twice");
230
+ }
301
231
  }
302
- const start = cursor.at;
303
- skipScalar(cursor);
304
- if (node.integer === true) {
305
- checkInteger(cursor.text.slice(start, cursor.at), at, label);
232
+ checkApplicators(doc, schema, value, at, found, refuse) {
233
+ for (const each of listOf(schema, "allOf")) {
234
+ this.check(doc, each, value, at, found);
235
+ }
236
+ const matching = (keyword) => listOf(schema, keyword).filter((each) => this.matches(doc, each, value, at)).length;
237
+ if (schema["anyOf"] !== undefined && matching("anyOf") === 0) {
238
+ refuse("anyOf", "the value matches none of the alternatives");
239
+ }
240
+ if (schema["oneOf"] !== undefined && matching("oneOf") !== 1) {
241
+ refuse("oneOf", `the value matches ${String(matching("oneOf"))} of the alternatives, want exactly one`);
242
+ }
243
+ if (isRecord(schema["not"]) && this.matches(doc, schema["not"], value, at)) {
244
+ refuse("not", "the value matches a schema it must not match");
245
+ }
246
+ if (isRecord(schema["if"])) {
247
+ const branch = this.matches(doc, schema["if"], value, at) ? schema["then"] : schema["else"];
248
+ if (isRecord(branch)) {
249
+ this.check(doc, branch, value, at, found);
250
+ }
251
+ }
306
252
  }
307
- }
308
- function walkObject(cursor, at, node, label) {
309
- const seen = new Set();
310
- for (;;) {
311
- skipSpace(cursor);
312
- const ch = cursor.text.charCodeAt(cursor.at);
313
- if (ch === 0x7d) {
314
- cursor.at += 1;
315
- return;
253
+ /**
254
+ * The refusal of `value` a reader fixes first, none for an instance: an object's
255
+ * refusal before any inside it, at one place an undeclared member, then a missing one,
256
+ * then any other, else the order the check finds them in. A oneOf no alternative
257
+ * matches is explained by the first refusal of the alternative the value was written
258
+ * for: the one whose type admits it, or of several, the one declaring the most of an
259
+ * object's members, then the fewest. Where two remain, the refusal is the oneOf's own.
260
+ */
261
+ first(doc, schema, value, at) {
262
+ const found = [];
263
+ this.check(doc, schema, value, at, found);
264
+ let first = found[0];
265
+ for (const other of found.slice(1)) {
266
+ if (first !== undefined && before(other, first)) {
267
+ first = other;
268
+ }
316
269
  }
317
- if (ch === 0x2c) {
318
- cursor.at += 1;
319
- continue;
270
+ if (first?.keyword !== "oneOf") {
271
+ return first;
320
272
  }
321
- if (ch !== 0x22) {
322
- throw malformed(label, at, "a member name is expected");
273
+ let held = value;
274
+ let holders = [[doc, schema]];
275
+ for (const segment of pointerSegments(first.pointer.slice(at.length))) {
276
+ holders = holders.flatMap(([d, s]) => this.applied(d, s, held).flatMap(([d2, s2]) => this.member(d2, s2, held, segment)));
277
+ held = valueAt(held, segment);
323
278
  }
324
- const name = readName(cursor, at, label);
325
- const path = joinKey(at, name);
326
- if (seen.has(name)) {
327
- throw malformed(label, path, `member ${JSON.stringify(name)} is written twice, so neither value is chosen`);
279
+ for (const [d, holder] of holders) {
280
+ const alternatives = listOf(holder, "oneOf");
281
+ if (alternatives.some((each) => this.matches(d, each, held, first.pointer))) {
282
+ continue;
283
+ }
284
+ const alternative = closest(alternatives, held);
285
+ const inner = alternative && this.first(d, alternative, held, first.pointer);
286
+ if (inner !== undefined) {
287
+ return inner;
288
+ }
328
289
  }
329
- seen.add(name);
330
- const child = memberOf(node, name);
331
- if (child === undefined) {
332
- throw unimplementedKey(label, path);
290
+ return first;
291
+ }
292
+ /** The schemas checked at one place when `schema` is: it, its `$ref`, its allOf and its if branch. */
293
+ applied(doc, schema, value) {
294
+ const held = [[doc, schema]];
295
+ if (typeof schema["$ref"] === "string") {
296
+ const [target, referenced] = this.resolve(doc, schema["$ref"]);
297
+ held.push(...this.applied(target, referenced, value));
333
298
  }
334
- skipSpace(cursor);
335
- if (cursor.text.charCodeAt(cursor.at) !== 0x3a) {
336
- throw malformed(label, path, "a member name is followed by a colon");
299
+ for (const each of listOf(schema, "allOf")) {
300
+ held.push(...this.applied(doc, each, value));
301
+ }
302
+ if (isRecord(schema["if"])) {
303
+ const branch = this.matches(doc, schema["if"], value, "") ? schema["then"] : schema["else"];
304
+ if (isRecord(branch)) {
305
+ held.push(...this.applied(doc, branch, value));
306
+ }
337
307
  }
338
- cursor.at += 1;
339
- walkValue(cursor, path, child, label);
308
+ return held;
309
+ }
310
+ /** The schemas `schema` checks the member or the entry `segment` names in `value` with. */
311
+ member(doc, schema, value, segment) {
312
+ if (Array.isArray(value)) {
313
+ return isRecord(schema["items"]) ? [[doc, schema["items"]]] : [];
314
+ }
315
+ const properties = isRecord(schema["properties"]) ? schema["properties"] : {};
316
+ const declared = declaredMember(properties, segment);
317
+ if (isRecord(declared)) {
318
+ return [[doc, declared]];
319
+ }
320
+ const additional = schema["additionalProperties"];
321
+ return isRecord(additional) ? [[doc, additional]] : [];
340
322
  }
341
323
  }
342
- function walkArray(cursor, at, node, label) {
343
- const entry = node.kind === "list" ? { kind: "section", members: node.members ?? {} } : leaf;
344
- let index = 0;
345
- for (;;) {
346
- skipSpace(cursor);
347
- const ch = cursor.text.charCodeAt(cursor.at);
348
- if (ch === 0x5d) {
349
- cursor.at += 1;
350
- return;
324
+ /** The alternative a value matching none of them was written for, or none where none or two remain. */
325
+ function closest(alternatives, value) {
326
+ const typed = alternatives.filter((each) => {
327
+ const types = typesOf(each);
328
+ return types.length === 0 || types.some((one) => hasType(value, one));
329
+ });
330
+ if (typed.length === 1 || !isRecord(value)) {
331
+ return typed.length === 1 ? typed[0] : undefined;
332
+ }
333
+ let best = [];
334
+ let most = -1;
335
+ let fewest = 0;
336
+ for (const alternative of typed) {
337
+ const properties = isRecord(alternative["properties"]) ? alternative["properties"] : {};
338
+ const named = Object.keys(value).filter((name) => Object.hasOwn(properties, name)).length;
339
+ const declared = Object.keys(properties).length;
340
+ if (named > most || (named === most && declared < fewest)) {
341
+ [best, most, fewest] = [[alternative], named, declared];
351
342
  }
352
- if (ch === 0x2c) {
353
- cursor.at += 1;
354
- continue;
343
+ else if (named === most && declared === fewest) {
344
+ best.push(alternative);
355
345
  }
356
- walkValue(cursor, `${at}[${index}]`, entry, label);
357
- index += 1;
358
346
  }
347
+ return best.length === 1 ? best[0] : undefined;
359
348
  }
360
349
  /**
361
- * Walks one document's text against the closed key list, refusing a member the
362
- * key list does not declare and a member one object writes twice, each naming its
363
- * dotted path. The document is already known to parse.
350
+ * A validator over one set of schema documents, each named as a `$ref` names it, rooted
351
+ * at one of them: what it refuses in a value, none for an instance.
364
352
  */
365
- export function checkDocument(text, node, label) {
366
- const cursor = { text, at: 0 };
367
- walkValue(cursor, "", node, label);
353
+ export function schemaRefusals(documents, root) {
354
+ const checker = new Checker(documents);
355
+ const top = documents[root];
356
+ if (top === undefined) {
357
+ throw new Error(`the schema set holds no document ${root}`);
358
+ }
359
+ return (value) => {
360
+ const found = [];
361
+ checker.check(root, top, value, "", found);
362
+ return found;
363
+ };
368
364
  }
369
365
  /**
370
- * The flag document, whose keys are dotted setting paths, rewritten as the nested
371
- * object the closed key list declares, so one decoder reads every source. A key
372
- * naming no setting is refused.
366
+ * The refusal of `value` a reader fixes first under one schema, none for an instance. A
367
+ * `$ref` the schema holds names a place in the schema itself.
373
368
  */
374
- export function nestFlags(flat, label) {
375
- const nested = {};
376
- for (const path of Object.keys(flat).sort()) {
377
- if (!declaresSetting(path)) {
378
- throw unimplementedKey(label, path);
379
- }
380
- const segments = path.split(".");
381
- let into = nested;
382
- for (const segment of segments.slice(0, -1)) {
383
- const child = into[segment] ?? {};
384
- if (typeof child !== "object" || Array.isArray(child)) {
385
- throw malformed(label, path, `the flag document sets ${JSON.stringify(segment)} twice`);
386
- }
387
- into[segment] = child;
388
- into = child;
389
- }
390
- const last = segments[segments.length - 1] ?? "";
391
- into[last] = flat[path];
392
- }
393
- return nested;
369
+ export function firstRefusal(schema, value) {
370
+ return new Checker({ "": schema }).first("", schema, value, "");
394
371
  }