yamlctl 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +223 -0
- package/bin/yamlctl.js +4 -0
- package/package.json +44 -0
- package/src/cli.js +388 -0
- package/src/document.js +43 -0
- package/src/explain.js +61 -0
- package/src/resources.js +107 -0
- package/src/rules.js +102 -0
- package/src/schema.js +364 -0
- package/src/store.js +173 -0
package/src/schema.js
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
// The JSON Schema a data file is checked against: where it is, what its entries look like, and how a value typed on a command line becomes the value the schema expects.
|
|
2
|
+
//
|
|
3
|
+
// Nothing here knows what the data means.
|
|
4
|
+
// Every rule beyond the schema's own keywords comes from `x-yamlctl`, documented in docs/schema-extensions.md, so the tool stays the same whatever the files describe.
|
|
5
|
+
//
|
|
6
|
+
// Every location is an absolute URI with a JSON pointer fragment, `file:///.../project.schema.json#/definitions/project` or `https://.../schema.json#/$defs/x`.
|
|
7
|
+
// That is what lets a `$ref` lead into another file or onto the network and back with nothing treated as a special case.
|
|
8
|
+
import { existsSync } from 'node:fs';
|
|
9
|
+
import { basename, dirname, isAbsolute, join } from 'node:path';
|
|
10
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
11
|
+
import { createRequire } from 'node:module';
|
|
12
|
+
import { baseOf, documentAt, hasDocument, isRemote, referencedDocuments } from './store.js';
|
|
13
|
+
|
|
14
|
+
const require = createRequire(import.meta.url);
|
|
15
|
+
const Ajv = require('ajv').default;
|
|
16
|
+
const Ajv2019 = require('ajv/dist/2019').default;
|
|
17
|
+
const Ajv2020 = require('ajv/dist/2020').default;
|
|
18
|
+
|
|
19
|
+
export const EXTENSION = 'x-yamlctl';
|
|
20
|
+
|
|
21
|
+
// The comment the YAML language server reads, so an editor and yamlctl always check a file against the same schema.
|
|
22
|
+
export const SCHEMA_LINE = /^#\s*yaml-language-server:\s*\$schema=(\S+)/m;
|
|
23
|
+
|
|
24
|
+
// The schema a file names on its own, else the usual places beside it: a schemas folder, then the file's own directory.
|
|
25
|
+
// The answer is a URI, `file:` or `https:`, and `named` says whether the file asked for it, which decides whether its absence is an error.
|
|
26
|
+
export function findSchema(file, text) {
|
|
27
|
+
const named = text.match(SCHEMA_LINE)?.[1];
|
|
28
|
+
if (named) {
|
|
29
|
+
if (isRemote(named)) return { uri: named, named: true };
|
|
30
|
+
if (/^[a-z][a-z0-9+.-]*:/i.test(named) && !named.startsWith('file:')) return { uri: named, named: true, unsupported: true };
|
|
31
|
+
if (named.startsWith('file:')) return { uri: named, named: true };
|
|
32
|
+
return { uri: pathToFileURL(isAbsolute(named) ? named : join(dirname(file), named)).href, named: true };
|
|
33
|
+
}
|
|
34
|
+
const name = `${basename(file).replace(/\.ya?ml$/, '')}.schema.json`;
|
|
35
|
+
const found = [join(dirname(file), 'schemas', name), join(dirname(file), name)].find((path) => existsSync(path));
|
|
36
|
+
return { uri: found ? pathToFileURL(found).href : null, named: false };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// A schema file on disk, for a caller holding a path rather than a URI.
|
|
40
|
+
export function loadSchema(pathOrUri) {
|
|
41
|
+
const uri = /^(file|https?):/i.test(pathOrUri) ? pathOrUri : pathToFileURL(pathOrUri).href;
|
|
42
|
+
return new Schema(documentAt(uri), uri);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// How a schema's location is shown: a path for a file, the address for anything else.
|
|
46
|
+
export const displayUri = (uri) => (uri?.startsWith('file:') ? fileURLToPath(uri) : uri);
|
|
47
|
+
|
|
48
|
+
function splitPointer(pointer) {
|
|
49
|
+
const at = pointer.indexOf('#');
|
|
50
|
+
return at === -1 ? [pointer, ''] : [pointer.slice(0, at), pointer.slice(at + 1)];
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// A JSON pointer fragment, `/definitions/project`, as the path of keys it walks.
|
|
54
|
+
// A plain name, `#thing`, is an `$anchor`, which is left to the validator rather than followed here.
|
|
55
|
+
function pointerKeys(fragment, pointer) {
|
|
56
|
+
if (fragment && !fragment.startsWith('/')) throw new Error(`${pointer} names an anchor, which is not followed`);
|
|
57
|
+
return fragment
|
|
58
|
+
.split('/')
|
|
59
|
+
.filter(Boolean)
|
|
60
|
+
.map((key) => decodeURIComponent(key).replace(/~1/g, '/').replace(/~0/g, '~'));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const isNull = (schema) => schema?.type === 'null' || (Array.isArray(schema?.type) && schema.type.length === 1 && schema.type[0] === 'null');
|
|
64
|
+
|
|
65
|
+
export class Schema {
|
|
66
|
+
// `uri` defaults to an address of its own for a schema built in memory, which resolves a fragment reference and nothing else.
|
|
67
|
+
constructor(root, uri = 'urn:yamlctl:inline') {
|
|
68
|
+
this.root = root;
|
|
69
|
+
this.uri = uri;
|
|
70
|
+
this.path = displayUri(uri);
|
|
71
|
+
this.documents = new Map([[uri, root]]);
|
|
72
|
+
this.bases = new Map([[uri, baseOf(root, uri)]]);
|
|
73
|
+
this.missing = [];
|
|
74
|
+
const draft = String(root.$schema ?? '');
|
|
75
|
+
const Validator = draft.includes('2020-12') ? Ajv2020 : draft.includes('2019-09') ? Ajv2019 : Ajv;
|
|
76
|
+
// Unknown formats and keywords are tolerated rather than refused, since a schema written for an editor carries both and they say nothing about validity.
|
|
77
|
+
this.ajv = new Validator({ allErrors: true, strict: false, validateFormats: false });
|
|
78
|
+
this.ajv.addKeyword(EXTENSION);
|
|
79
|
+
this.ajv.addSchema(root, uri);
|
|
80
|
+
|
|
81
|
+
// Every document a reference can reach is given to the validator up front, since it compiles synchronously and cannot go looking for one halfway through.
|
|
82
|
+
const added = new Set([root]);
|
|
83
|
+
const queue = referencedDocuments(root, this.bases.get(uri));
|
|
84
|
+
while (queue.length) {
|
|
85
|
+
const next = queue.shift();
|
|
86
|
+
if (this.documents.has(next)) continue;
|
|
87
|
+
if (!hasDocument(next)) {
|
|
88
|
+
this.missing.push(next);
|
|
89
|
+
this.documents.set(next, null);
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
const document = documentAt(next);
|
|
93
|
+
this.documents.set(next, document);
|
|
94
|
+
this.bases.set(next, baseOf(document, next));
|
|
95
|
+
if (!added.has(document)) {
|
|
96
|
+
added.add(document);
|
|
97
|
+
this.ajv.addSchema(document, next);
|
|
98
|
+
}
|
|
99
|
+
queue.push(...referencedDocuments(document, this.bases.get(next)));
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// A pointer relative to the root, `#/definitions/project`, or absolute, `<uri>#/definitions/project`.
|
|
104
|
+
absolute(pointer) {
|
|
105
|
+
return pointer.startsWith('#') ? `${this.uri}${pointer}` : pointer;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
at(pointer) {
|
|
109
|
+
const full = this.absolute(pointer);
|
|
110
|
+
const [uri, fragment] = splitPointer(full);
|
|
111
|
+
let node = this.documents.get(uri);
|
|
112
|
+
if (!node) throw new Error(this.missing.includes(uri) ? `${displayUri(uri)} is referenced by the schema and could not be loaded` : `${displayUri(uri)} is not a document this schema reaches`);
|
|
113
|
+
for (const key of pointerKeys(fragment, full)) {
|
|
114
|
+
node = node?.[key];
|
|
115
|
+
if (node === undefined) throw new Error(`${displayUri(uri)} has nothing at #${fragment}`);
|
|
116
|
+
}
|
|
117
|
+
return { schema: node, pointer: full };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// A schema with its reference followed and a nullable wrapper taken off, as the pointer ajv can compile and the object a walk can read.
|
|
121
|
+
// `anyOf: [{$ref}, {type: null}]` is how a value that may be left empty is usually written, and the empty branch says nothing about the value's shape.
|
|
122
|
+
unwrap(pointer, depth = 0) {
|
|
123
|
+
if (depth > 32) throw new Error(`${pointer} references itself too deeply to follow`);
|
|
124
|
+
const { schema, pointer: full } = this.at(pointer);
|
|
125
|
+
if (schema?.$ref) {
|
|
126
|
+
const [uri] = splitPointer(full);
|
|
127
|
+
let target;
|
|
128
|
+
try {
|
|
129
|
+
target = new URL(schema.$ref, this.bases.get(uri) ?? uri).href;
|
|
130
|
+
} catch {
|
|
131
|
+
throw new Error(`${schema.$ref} is not a reference that can be followed`);
|
|
132
|
+
}
|
|
133
|
+
return this.unwrap(target.includes('#') ? target : `${target}#`, depth + 1);
|
|
134
|
+
}
|
|
135
|
+
for (const keyword of ['anyOf', 'oneOf']) {
|
|
136
|
+
const options = schema?.[keyword];
|
|
137
|
+
if (!Array.isArray(options)) continue;
|
|
138
|
+
const kept = options.map((option, i) => ({ option, i })).filter(({ option }) => !isNull(option));
|
|
139
|
+
if (kept.length === 1) return this.unwrap(`${full}/${keyword}/${kept[0].i}`, depth + 1);
|
|
140
|
+
}
|
|
141
|
+
return { schema, pointer: full };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
child(pointer, key) {
|
|
145
|
+
const { schema, pointer: here } = this.unwrap(pointer);
|
|
146
|
+
if (schema?.properties && Object.hasOwn(schema.properties, key)) return this.unwrap(`${here}/properties/${escapeKey(key)}`);
|
|
147
|
+
if (schema?.patternProperties) {
|
|
148
|
+
for (const pattern of Object.keys(schema.patternProperties)) {
|
|
149
|
+
if (new RegExp(pattern, 'u').test(key)) return this.unwrap(`${here}/patternProperties/${escapeKey(pattern)}`);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
if (schema?.additionalProperties && typeof schema.additionalProperties === 'object') return this.unwrap(`${here}/additionalProperties`);
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// The top-level properties holding a map of entries: an object whose values all follow one schema, rather than an object with fields of its own.
|
|
157
|
+
// That shape is all it takes, so a schema needs nothing added for yamlctl to find its entries.
|
|
158
|
+
entryMaps() {
|
|
159
|
+
const properties = this.root.properties ?? {};
|
|
160
|
+
return Object.keys(properties).filter((name) => {
|
|
161
|
+
if (properties[name]?.[EXTENSION]?.entries === false) return false;
|
|
162
|
+
const { schema, pointer } = this.unwrap(`#/properties/${escapeKey(name)}`);
|
|
163
|
+
if (!types(schema).includes('object') || schema.properties || !schema.additionalProperties || typeof schema.additionalProperties !== 'object') return false;
|
|
164
|
+
// A map of strings, labels or tags, has values rather than entries, and an entry is something with fields.
|
|
165
|
+
const entry = types(this.unwrap(`${pointer}/additionalProperties`).schema);
|
|
166
|
+
return !entry.length || entry.includes('object');
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// What the map itself declares for yamlctl: which sibling holds its defaults, which field names an entry.
|
|
171
|
+
mapOptions(name) {
|
|
172
|
+
return this.root.properties?.[name]?.[EXTENSION] ?? {};
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
entryPointer(map) {
|
|
176
|
+
return this.unwrap(`#/properties/${escapeKey(map)}/additionalProperties`).pointer;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// The schema a field path leads to, or null for a path naming no field.
|
|
180
|
+
// `throughLists` lets a path go into the items of a list, `account_links.account`, which explaining a field needs and setting one does not, since a list is set whole.
|
|
181
|
+
// `crossed` says whether it did, so a caller setting a value can refuse a path it cannot write.
|
|
182
|
+
field(pointer, segments, { throughLists = false } = {}) {
|
|
183
|
+
let here = this.unwrap(pointer);
|
|
184
|
+
let crossed = false;
|
|
185
|
+
for (const segment of segments) {
|
|
186
|
+
let next = this.child(here.pointer, segment);
|
|
187
|
+
if (!next && throughLists && here.schema?.items && typeof here.schema.items === 'object' && !Array.isArray(here.schema.items)) {
|
|
188
|
+
crossed = true;
|
|
189
|
+
next = this.child(this.unwrap(`${here.pointer}/items`).pointer, segment);
|
|
190
|
+
}
|
|
191
|
+
if (!next) return null;
|
|
192
|
+
here = next;
|
|
193
|
+
}
|
|
194
|
+
return { ...here, crossed };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// Every problem in one value, each with the path it was found at.
|
|
198
|
+
// A failing `anyOf` or `oneOf` is reported through the branch closest to the value, found by validating the value against each branch on its own.
|
|
199
|
+
// ajv reports every branch, which reads as contradictions: a job told both to add `uses` and to drop `steps`.
|
|
200
|
+
validate(pointer, value, prefix, depth = 0) {
|
|
201
|
+
const full = this.absolute(pointer).replace(/#$/, '');
|
|
202
|
+
let check;
|
|
203
|
+
try {
|
|
204
|
+
check = this.ajv.getSchema(full);
|
|
205
|
+
} catch (e) {
|
|
206
|
+
const reason = e instanceof Error ? e.message : String(e);
|
|
207
|
+
throw new Error(this.missing.length ? `the schema cannot be applied, ${this.missing.map(displayUri).join(', ')} could not be loaded (${reason})` : `the schema cannot be applied: ${reason}`);
|
|
208
|
+
}
|
|
209
|
+
if (!check) throw new Error(`cannot compile the schema at ${full}`);
|
|
210
|
+
if (check(value)) return [];
|
|
211
|
+
// A branch allowing null never explains anything, since the value is not null.
|
|
212
|
+
let errors = (check.errors ?? []).filter((error) => !(error.keyword === 'type' && [].concat(error.params.type).join() === 'null'));
|
|
213
|
+
const closest = [];
|
|
214
|
+
const handled = [];
|
|
215
|
+
const alternatives = errors.filter((error) => error.keyword === 'anyOf' || error.keyword === 'oneOf').sort((x, y) => x.instancePath.length - y.instancePath.length);
|
|
216
|
+
for (const alternative of alternatives) {
|
|
217
|
+
if (handled.some((path) => within(alternative.instancePath, path))) continue;
|
|
218
|
+
const branches = depth < 8 ? this.branches(full.includes('#') ? full : `${full}#`, alternative, value) : null;
|
|
219
|
+
if (!branches) continue;
|
|
220
|
+
const here = `${prefix}${dotted(alternative.instancePath)}`;
|
|
221
|
+
const results = branches.map((branch) => this.validate(branch.pointer, branch.value, here, depth + 1));
|
|
222
|
+
// A oneOf failing because two branches pass is not a problem any branch can explain, so its own message is kept.
|
|
223
|
+
if (results.some((result) => !result.length)) continue;
|
|
224
|
+
// The closest branch is the one the value's own fields agree with most, so problems on the value itself count first, since a problem deeper down means the shape matched.
|
|
225
|
+
// The total only breaks a tie, the way established validators rank their best match.
|
|
226
|
+
// A branch of another type altogether, a string where the value is an object, is the furthest of all, whatever its count.
|
|
227
|
+
const ranks = results.map((result, i) => [this.typeMatches(branches[i].pointer, branches[i].value) ? 0 : 1, result.filter((message) => message.startsWith(`${here}: `)).length, result.length]);
|
|
228
|
+
const before = (x, y) => x[0] - y[0] || x[1] - y[1] || x[2] - y[2];
|
|
229
|
+
const best = [...ranks].sort(before)[0];
|
|
230
|
+
closest.push(...results.filter((_, i) => before(ranks[i], best) === 0).flat());
|
|
231
|
+
handled.push(alternative.instancePath);
|
|
232
|
+
}
|
|
233
|
+
errors = errors.filter((error) => !handled.some((path) => within(error.instancePath, path)));
|
|
234
|
+
return [...new Set([...formatErrors(errors, prefix), ...closest])];
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// The branches of the alternative an error reports, each as the pointer to validate and the value it applies to, or null when the alternative cannot be located.
|
|
238
|
+
branches(pointer, error, value) {
|
|
239
|
+
const segments = error.instancePath.split('/').slice(1).map((key) => key.replace(/~1/g, '/').replace(/~0/g, '~'));
|
|
240
|
+
let here = this.unwrapRef(pointer);
|
|
241
|
+
let data = value;
|
|
242
|
+
for (const segment of segments) {
|
|
243
|
+
const { schema } = this.at(here);
|
|
244
|
+
if (Array.isArray(data)) {
|
|
245
|
+
const index = Number(segment);
|
|
246
|
+
if (Array.isArray(schema.prefixItems) && schema.prefixItems[index]) here = this.unwrapRef(`${here}/prefixItems/${index}`);
|
|
247
|
+
else if (schema.items && typeof schema.items === 'object' && !Array.isArray(schema.items)) here = this.unwrapRef(`${here}/items`);
|
|
248
|
+
else return null;
|
|
249
|
+
data = data[index];
|
|
250
|
+
continue;
|
|
251
|
+
}
|
|
252
|
+
const next = this.childRef(here, segment);
|
|
253
|
+
if (!next) return null;
|
|
254
|
+
here = next;
|
|
255
|
+
data = data?.[segment];
|
|
256
|
+
}
|
|
257
|
+
const options = this.at(here).schema?.[error.keyword];
|
|
258
|
+
if (!Array.isArray(options)) return null;
|
|
259
|
+
return options.flatMap((option, i) => (isNull(option) ? [] : [{ pointer: `${here}/${error.keyword}/${i}`, value: data }]));
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// Whether a value is of a type the schema at a pointer allows, an integer counting as a number, and a schema naming no type allowing any.
|
|
263
|
+
typeMatches(pointer, value) {
|
|
264
|
+
const allowed = types(this.unwrap(pointer).schema);
|
|
265
|
+
if (!allowed.length) return true;
|
|
266
|
+
const actual = value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value;
|
|
267
|
+
if (actual === 'number') return allowed.includes('number') || (allowed.includes('integer') && Number.isInteger(value));
|
|
268
|
+
return allowed.includes(actual);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// A reference followed, and nothing else, so an alternative a node holds is still there to see.
|
|
272
|
+
unwrapRef(pointer, depth = 0) {
|
|
273
|
+
if (depth > 32) throw new Error(`${pointer} references itself too deeply to follow`);
|
|
274
|
+
const { schema, pointer: full } = this.at(pointer);
|
|
275
|
+
if (!schema?.$ref) return full;
|
|
276
|
+
const [uri] = splitPointer(full);
|
|
277
|
+
const target = new URL(schema.$ref, this.bases.get(uri) ?? uri).href;
|
|
278
|
+
return this.unwrapRef(target.includes('#') ? target : `${target}#`, depth + 1);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
childRef(pointer, key) {
|
|
282
|
+
const { schema } = this.at(pointer);
|
|
283
|
+
if (schema?.properties && Object.hasOwn(schema.properties, key)) return this.unwrapRef(`${pointer}/properties/${escapeKey(key)}`);
|
|
284
|
+
for (const pattern of Object.keys(schema?.patternProperties ?? {})) {
|
|
285
|
+
if (new RegExp(pattern, 'u').test(key)) return this.unwrapRef(`${pointer}/patternProperties/${escapeKey(pattern)}`);
|
|
286
|
+
}
|
|
287
|
+
if (schema?.additionalProperties && typeof schema.additionalProperties === 'object') return this.unwrapRef(`${pointer}/additionalProperties`);
|
|
288
|
+
return null;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// A key as one segment of a JSON pointer, escaped the way RFC 6901 and a URI fragment both require.
|
|
293
|
+
export const escapeKey = (key) => encodeURIComponent(String(key).replace(/~/g, '~0').replace(/\//g, '~1'));
|
|
294
|
+
|
|
295
|
+
export function types(schema) {
|
|
296
|
+
if (!schema) return [];
|
|
297
|
+
if (schema.type) return [].concat(schema.type);
|
|
298
|
+
if (schema.properties || schema.additionalProperties !== undefined) return ['object'];
|
|
299
|
+
if (schema.items) return ['array'];
|
|
300
|
+
return [];
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// A value from the command line, typed by what the schema says the field holds.
|
|
304
|
+
// A string field keeps the text exactly as typed: `005217217997` read as YAML would be a number without its leading zero, and `no` a boolean.
|
|
305
|
+
export function typedValue(schema, text) {
|
|
306
|
+
if (schema.const !== undefined) return fromEnum([schema.const], text);
|
|
307
|
+
if (schema.enum) return fromEnum(schema.enum, text);
|
|
308
|
+
const allowed = types(schema).filter((type) => type !== 'null');
|
|
309
|
+
if (!allowed.length || allowed.includes('string')) return text;
|
|
310
|
+
if (text === 'null' && types(schema).includes('null')) return null;
|
|
311
|
+
if (allowed.includes('boolean') && (text === 'true' || text === 'false')) return text === 'true';
|
|
312
|
+
if ((allowed.includes('integer') || allowed.includes('number')) && text.trim() !== '' && !Number.isNaN(Number(text))) {
|
|
313
|
+
const number = Number(text);
|
|
314
|
+
if (allowed.includes('number') || Number.isInteger(number)) return number;
|
|
315
|
+
}
|
|
316
|
+
if (allowed.includes('array') || allowed.includes('object')) {
|
|
317
|
+
try {
|
|
318
|
+
return JSON.parse(text);
|
|
319
|
+
} catch {
|
|
320
|
+
throw new Error(`expected ${allowed.join(' or ')} written as JSON, got ${text}`);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
throw new Error(`expected ${allowed.join(' or ')}, got ${text}`);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// An enum can hold a number or a boolean, and the text typed is matched against the value's own spelling so `3` finds `3` rather than `"3"`.
|
|
327
|
+
function fromEnum(values, text) {
|
|
328
|
+
const found = values.find((value) => value !== null && String(value) === text);
|
|
329
|
+
if (found !== undefined) return found;
|
|
330
|
+
if (text === 'null' && values.includes(null)) return null;
|
|
331
|
+
return text;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
const within = (path, root) => path === root || path.startsWith(`${root}/`);
|
|
335
|
+
const dotted = (instancePath) => instancePath.replace(/\//g, '.').replace(/~1/g, '/').replace(/~0/g, '~');
|
|
336
|
+
|
|
337
|
+
function formatErrors(errors, prefix) {
|
|
338
|
+
const seen = new Set();
|
|
339
|
+
const out = [];
|
|
340
|
+
for (const error of errors) {
|
|
341
|
+
if (error.keyword === 'if') continue;
|
|
342
|
+
const path = `${prefix}${dotted(error.instancePath)}`;
|
|
343
|
+
const message = describe(error);
|
|
344
|
+
const key = `${path} ${message}`;
|
|
345
|
+
if (seen.has(key)) continue;
|
|
346
|
+
seen.add(key);
|
|
347
|
+
out.push(`${path}: ${message}`);
|
|
348
|
+
}
|
|
349
|
+
return out;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
function describe(error) {
|
|
353
|
+
const { keyword, params } = error;
|
|
354
|
+
if (keyword === 'additionalProperties') return `no such field ${params.additionalProperty}`;
|
|
355
|
+
if (keyword === 'enum') return `must be one of ${params.allowedValues.filter((v) => v !== null).map((v) => JSON.stringify(v)).join(', ')}`;
|
|
356
|
+
if (keyword === 'const') return `must be ${JSON.stringify(params.allowedValue)}`;
|
|
357
|
+
if (keyword === 'required') return `missing required field ${params.missingProperty}`;
|
|
358
|
+
if (keyword === 'type') return `must be ${[].concat(params.type).join(' or ')}`;
|
|
359
|
+
// A pattern can hold a line break, which printed raw splits one message over two lines.
|
|
360
|
+
if (keyword === 'pattern') return `must match the pattern ${JSON.stringify(params.pattern)}`;
|
|
361
|
+
if (keyword === 'oneOf') return params.passingSchemas ? 'matches more than one of the alternatives, where exactly one is expected' : 'matches none of the alternatives';
|
|
362
|
+
if (keyword === 'anyOf') return 'matches none of the alternatives';
|
|
363
|
+
return error.message ?? keyword;
|
|
364
|
+
}
|
package/src/store.js
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
// Every schema document a command can reach, by absolute URI: the file a data file names, and every document its `$ref`s lead to, local or remote.
|
|
2
|
+
//
|
|
3
|
+
// Remote documents are fetched before a command runs, by `prefetch`, so that everything after it reads from here and stays synchronous.
|
|
4
|
+
// A local document is read when used, since reading a file needs no preparation.
|
|
5
|
+
import { createHash } from 'node:crypto';
|
|
6
|
+
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
|
|
7
|
+
import { homedir } from 'node:os';
|
|
8
|
+
import { join } from 'node:path';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
|
|
11
|
+
const documents = new Map();
|
|
12
|
+
const failures = new Map();
|
|
13
|
+
|
|
14
|
+
// A day, long enough that a pipeline running every few minutes does not download the same schema each time, short enough that a published fix arrives the next day.
|
|
15
|
+
export const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
|
|
16
|
+
const FETCH_TIMEOUT_MS = 15000;
|
|
17
|
+
|
|
18
|
+
export const isRemote = (uri) => /^https?:\/\//i.test(uri);
|
|
19
|
+
|
|
20
|
+
export function cacheDir(env = process.env) {
|
|
21
|
+
if (env.YAMLCTL_CACHE_DIR) return env.YAMLCTL_CACHE_DIR;
|
|
22
|
+
return join(env.XDG_CACHE_HOME || join(homedir(), '.cache'), 'yamlctl');
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// The document at a URI without its fragment, or an error saying why it is not there.
|
|
26
|
+
export function documentAt(uri) {
|
|
27
|
+
if (documents.has(uri)) return documents.get(uri);
|
|
28
|
+
if (uri.startsWith('file:')) {
|
|
29
|
+
const path = fileURLToPath(uri);
|
|
30
|
+
let parsed;
|
|
31
|
+
try {
|
|
32
|
+
parsed = JSON.parse(readFileSync(path, 'utf8'));
|
|
33
|
+
} catch (e) {
|
|
34
|
+
throw new Error(`${path} is not a readable JSON Schema: ${e instanceof Error ? e.message : String(e)}`);
|
|
35
|
+
}
|
|
36
|
+
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error(`${path} does not hold a JSON Schema object`);
|
|
37
|
+
// Read again every time rather than kept, since a schema file edited between two calls in one process has to be seen as edited.
|
|
38
|
+
return parsed;
|
|
39
|
+
}
|
|
40
|
+
if (failures.has(uri)) throw new Error(failures.get(uri));
|
|
41
|
+
throw new Error(`${uri} was not fetched`);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function hasDocument(uri) {
|
|
45
|
+
if (documents.has(uri)) return true;
|
|
46
|
+
if (uri.startsWith('file:')) return existsSync(fileURLToPath(uri));
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// For a test, or a caller holding a schema that is not in a file.
|
|
51
|
+
export function registerDocument(uri, document) {
|
|
52
|
+
documents.set(uri, document);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function forget() {
|
|
56
|
+
documents.clear();
|
|
57
|
+
failures.clear();
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// The URI a document's relative references resolve against: its own `$id` when it has one, as the specification says, else where it was read from.
|
|
61
|
+
// Resolving against where it was read from instead fetches the wrong document whenever a schema is published at one address and identified by another.
|
|
62
|
+
export function baseOf(document, uri) {
|
|
63
|
+
const id = document?.$id ?? document?.id;
|
|
64
|
+
if (typeof id !== 'string') return uri;
|
|
65
|
+
try {
|
|
66
|
+
return new URL(id, uri).href.replace(/#.*$/, '');
|
|
67
|
+
} catch {
|
|
68
|
+
return uri;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Every `$ref` in a document, resolved against the document it sits in, fragment dropped: the documents a validation of it can reach.
|
|
73
|
+
export function referencedDocuments(document, base) {
|
|
74
|
+
const found = new Set();
|
|
75
|
+
const visit = (node) => {
|
|
76
|
+
if (Array.isArray(node)) return node.forEach(visit);
|
|
77
|
+
if (!node || typeof node !== 'object') return;
|
|
78
|
+
for (const [key, value] of Object.entries(node)) {
|
|
79
|
+
if (key === '$ref' && typeof value === 'string' && !value.startsWith('#')) {
|
|
80
|
+
try {
|
|
81
|
+
found.add(new URL(value, base).href.replace(/#.*$/, ''));
|
|
82
|
+
} catch {
|
|
83
|
+
// A reference that is not a URL cannot be followed, and validation says so when it reaches it.
|
|
84
|
+
}
|
|
85
|
+
} else visit(value);
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
visit(document);
|
|
89
|
+
return [...found];
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Fetches every remote document reachable from the URIs given, following `$ref`s through local and remote documents alike, and keeps each one in the cache.
|
|
93
|
+
// A document the cache holds and that is younger than the TTL is not fetched again; `refresh` fetches regardless, `offline` never fetches.
|
|
94
|
+
// A fetch that fails falls back to a cached copy of any age, said in a warning.
|
|
95
|
+
// A document with no copy at all is recorded as a failure rather than thrown, so the command decides what an unavailable schema means for what it was asked to do.
|
|
96
|
+
export async function prefetch(uris, { offline = false, refresh = false, env = process.env, warn = () => {}, fetchImpl = globalThis.fetch, now = Date.now() } = {}) {
|
|
97
|
+
const queue = [...uris];
|
|
98
|
+
const seen = new Set();
|
|
99
|
+
while (queue.length) {
|
|
100
|
+
const uri = queue.shift();
|
|
101
|
+
if (seen.has(uri)) continue;
|
|
102
|
+
seen.add(uri);
|
|
103
|
+
let document = null;
|
|
104
|
+
if (isRemote(uri)) {
|
|
105
|
+
document = await remoteDocument(uri, { offline, refresh, env, warn, fetchImpl, now });
|
|
106
|
+
if (document) documents.set(uri, document);
|
|
107
|
+
} else if (uri.startsWith('file:') && hasDocument(uri)) {
|
|
108
|
+
try {
|
|
109
|
+
document = documentAt(uri);
|
|
110
|
+
} catch {
|
|
111
|
+
document = null;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
if (document) queue.push(...referencedDocuments(document, baseOf(document, uri)));
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function remoteDocument(uri, { offline, refresh, env, warn, fetchImpl, now }) {
|
|
119
|
+
const cached = readCache(uri, env);
|
|
120
|
+
if (offline) {
|
|
121
|
+
if (cached) return cached.document;
|
|
122
|
+
failures.set(uri, `${uri} is not in the cache, and --offline does not fetch it`);
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
if (cached && !refresh && now - cached.fetchedAt < CACHE_TTL_MS) return cached.document;
|
|
126
|
+
try {
|
|
127
|
+
const response = await fetchImpl(uri, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), headers: { accept: 'application/schema+json, application/json' } });
|
|
128
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
129
|
+
const document = JSON.parse(await response.text());
|
|
130
|
+
if (document === null || typeof document !== 'object' || Array.isArray(document)) throw new Error('not a JSON Schema object');
|
|
131
|
+
writeCache(uri, document, env);
|
|
132
|
+
return document;
|
|
133
|
+
} catch (e) {
|
|
134
|
+
const reason = e instanceof Error ? e.message : String(e);
|
|
135
|
+
if (cached) {
|
|
136
|
+
warn(`${uri} could not be fetched (${reason}), using the copy cached ${age(now - cached.fetchedAt)} ago`);
|
|
137
|
+
return cached.document;
|
|
138
|
+
}
|
|
139
|
+
failures.set(uri, `${uri} could not be fetched: ${reason}`);
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function cacheFile(uri, env) {
|
|
145
|
+
return join(cacheDir(env), `${createHash('sha256').update(uri).digest('hex')}.json`);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function readCache(uri, env) {
|
|
149
|
+
const file = cacheFile(uri, env);
|
|
150
|
+
if (!existsSync(file)) return null;
|
|
151
|
+
try {
|
|
152
|
+
const { url, document } = JSON.parse(readFileSync(file, 'utf8'));
|
|
153
|
+
if (url !== uri) return null;
|
|
154
|
+
return { document, fetchedAt: statSync(file).mtimeMs };
|
|
155
|
+
} catch {
|
|
156
|
+
// A cache entry that does not parse is one to fetch again, not a reason to stop.
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function writeCache(uri, document, env) {
|
|
162
|
+
try {
|
|
163
|
+
mkdirSync(cacheDir(env), { recursive: true });
|
|
164
|
+
writeFileSync(cacheFile(uri, env), JSON.stringify({ url: uri, document }));
|
|
165
|
+
} catch {
|
|
166
|
+
// A cache that cannot be written only costs a fetch next time.
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function age(ms) {
|
|
171
|
+
const hours = Math.round(ms / 3600000);
|
|
172
|
+
return hours < 48 ? `${hours} hour${hours === 1 ? '' : 's'}` : `${Math.round(hours / 24)} days`;
|
|
173
|
+
}
|