( validator: Validator<t.Node> | undefined, nodePrefix: string )
| 4 | * Stringify a validator to its corresponding TypeScript type. |
| 5 | */ |
| 6 | export default function stringifyValidator( |
| 7 | validator: Validator<t.Node> | undefined, |
| 8 | nodePrefix: string |
| 9 | ): string { |
| 10 | if (validator === undefined) { |
| 11 | return "any"; |
| 12 | } |
| 13 | |
| 14 | if ("each" in validator) { |
| 15 | const subValidator = stringifyValidator(validator.each, nodePrefix); |
| 16 | return `${subValidator.includes("|") ? `(${subValidator})` : subValidator}[]`; |
| 17 | } |
| 18 | |
| 19 | if ("chainOf" in validator) { |
| 20 | let ret = "any"; |
| 21 | // Iterate from the end to the beginning to find the most narrow type. |
| 22 | // For example, we usually place `assertEach(assertNodeOrValueType("null", "PatternLike"))` |
| 23 | // after `assertValueType("array")` |
| 24 | for (let i = validator.chainOf.length - 1; i >= 0; i--) { |
| 25 | const chainValidator = validator.chainOf[i]; |
| 26 | ret = stringifyValidator(chainValidator, nodePrefix); |
| 27 | if (ret !== "any") { |
| 28 | break; |
| 29 | } |
| 30 | } |
| 31 | return ret; |
| 32 | } |
| 33 | |
| 34 | if ("oneOf" in validator) { |
| 35 | return validator.oneOf.map(_ => JSON.stringify(_)).join(" | "); |
| 36 | } |
| 37 | |
| 38 | if ("oneOfNodeTypes" in validator) { |
| 39 | return validator.oneOfNodeTypes.map(_ => nodePrefix + _).join(" | "); |
| 40 | } |
| 41 | |
| 42 | if ("oneOfNodeOrValueTypes" in validator) { |
| 43 | return validator.oneOfNodeOrValueTypes |
| 44 | .map(_ => { |
| 45 | return isValueType(_) ? _ : nodePrefix + _; |
| 46 | }) |
| 47 | .join(" | "); |
| 48 | } |
| 49 | |
| 50 | if ("type" in validator) { |
| 51 | return validator.type; |
| 52 | } |
| 53 | |
| 54 | if ("shapeOf" in validator) { |
| 55 | return ( |
| 56 | "{ " + |
| 57 | Object.keys(validator.shapeOf) |
| 58 | .map(shapeKey => { |
| 59 | const propertyDefinition = validator.shapeOf[shapeKey]; |
| 60 | if (propertyDefinition.validate) { |
| 61 | const isOptional = |
| 62 | propertyDefinition.optional || propertyDefinition.default != null; |
| 63 | return ( |
no test coverage detected