Skip to content

Commit

Permalink
Improves the way the validator displays matches with many possible va…
Browse files Browse the repository at this point in the history
…lues (markdoc#355)
  • Loading branch information
rpaul-stripe committed Apr 17, 2023
1 parent d46832b commit bfec21c
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
27 changes: 27 additions & 0 deletions src/validator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,33 @@ bar
]);
});

it('Elides excess values in matches check', () => {
const example = '{% foo jawn="cat" /%}';
const schema = {
tags: {
foo: {
attributes: {
jawn: {
type: String,
matches: Array.from('foobarbazqux'),
},
},
},
},
};

const output = validate(example, schema);
expect(output).toDeepEqualSubset([
{
type: 'tag',
error: {
id: 'attribute-value-invalid',
message: `Attribute 'jawn' must match one of ["f","o","o","b","a","r","b","a", ... 4 more]. Got 'cat' instead.`,
},
},
]);
});

// https://github.com/markdoc/markdoc/issues/122
it('should validate partial file attributes', () => {
const example = `{% partial file="non-existent.md" /%}`;
Expand Down
11 changes: 9 additions & 2 deletions src/validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,12 @@ function validateFunction(fn: Function, config: Config): ValidationError[] {
return errors;
}

function displayMatches(matches: any[], n: number) {
if (matches.length <= n) return JSON.stringify(matches);
const items = matches.slice(0, n).map((item) => JSON.stringify(item));
return `[${items.join(',')}, ... ${matches.length - n} more]`;
}

export default function validator(node: Node, config: Config) {
const schema = node.findSchema(config);
const errors: ValidationError[] = [...(node.errors || [])];
Expand Down Expand Up @@ -220,8 +226,9 @@ export default function validator(node: Node, config: Config) {
errors.push({
id: 'attribute-value-invalid',
level: errorLevel || 'error',
message: `Attribute '${key}' must match one of ${JSON.stringify(
matches
message: `Attribute '${key}' must match one of ${displayMatches(
matches,
8
)}. Got '${value}' instead.`,
});

Expand Down

0 comments on commit bfec21c

Please sign in to comment.