Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add assertShape to validate templateElement #10198

Merged
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 13 additions & 0 deletions packages/babel-types/scripts/utils/stringifyValidator.js
Expand Up @@ -31,6 +31,19 @@ module.exports = function stringifyValidator(validator, nodePrefix) {
return validator.type;
}

if (validator.shapeOf) {
return (
"{" +
Object.keys(validator.shapeOf)
.map(
shapeKey =>
shapeKey + ":" + stringifyValidator(validator.shapeOf[shapeKey])
)
.join(", ") +
"}"
);
}

return ["any"];
};

Expand Down
6 changes: 5 additions & 1 deletion packages/babel-types/src/definitions/es2015.js
@@ -1,5 +1,6 @@
// @flow
import defineType, {
assertShape,
assertNodeType,
assertValueType,
chain,
Expand Down Expand Up @@ -537,7 +538,10 @@ defineType("TemplateElement", {
builder: ["value", "tail"],
fields: {
value: {
// todo: flatten `raw` into main node
validate: assertShape({
raw: assertValueType("string"),
cooked: assertValueType("string"),
jridgewell marked this conversation as resolved.
Show resolved Hide resolved
}),
},
tail: {
validate: assertValueType("boolean"),
Expand Down
29 changes: 29 additions & 0 deletions packages/babel-types/src/definitions/utils.js
Expand Up @@ -161,6 +161,35 @@ export function assertValueType(type: string): Validator {
return validate;
}

export function assertShape(shape: { [string]: Validator }): Validator {
function validate(node, key, val) {
const errors = [];
for (const property of Object.keys(shape)) {
try {
const validator = shape[property];
validator(node, property, val[property]);
} catch (error) {
if (error instanceof TypeError) {
errors.push(error.message);
continue;
}
throw error;
}
}
if (errors.length) {
throw new TypeError(
`Property ${key} of ${
node.type
} expected to have the following:\n${errors.join("\n")}`,
);
}
}

validate.shapeOf = shape;

return validate;
}

export function chain(...fns: Array<Validator>): Validator {
function validate(...args) {
for (const fn of fns) {
Expand Down