// Package validation supports this repository's contract checks. It is not a // consumer SDK: consumers may use their own conforming YAML and schema tools. package validation import ( "bytes" "encoding/json" "errors" "fmt" "math/big" "strconv" "strings" "go.yaml.in/yaml/v4" ) // Decode uses the standard JSON decoder for JSON syntax and go-yaml otherwise, // adapting both to the documented data model without losing number precision. func Decode(data []byte) (any, error) { if json.Valid(data) { d := json.NewDecoder(bytes.NewReader(data)) d.UseNumber() value, err := jsonValue(d, "") if err != nil { return nil, fmt.Errorf("decode: %w", err) } return value, nil } var document yaml.Node if err := yaml.Load(data, &document, yaml.WithUniqueKeys()); err != nil { return nil, fmt.Errorf("decode: %w", err) } d := decoder{active: make(map[*yaml.Node]bool), values: make(map[*yaml.Node]any)} value, err := d.value(&document, "") if err != nil { return nil, fmt.Errorf("decode: %w", err) } return value, nil } // jsonValue consumes library-decoded tokens so duplicate keys, including keys // with equivalent escape spellings, cannot be lost in a map unmarshalling step. // Decode has already checked that the input is one syntactically valid value. func jsonValue(d *json.Decoder, path string) (any, error) { token, err := d.Token() if err != nil { return nil, err } switch token { case json.Delim('{'): value := make(map[string]any) for d.More() { token, err := d.Token() if err != nil { return nil, err } key := token.(string) // Valid JSON objects have string keys. childPath := path + "/" + escape(key) if _, exists := value[key]; exists { return nil, fmt.Errorf("%s (byte %d): duplicate mapping key %q", pointer(childPath), d.InputOffset(), key) } value[key], err = jsonValue(d, childPath) if err != nil { return nil, err } } _, err = d.Token() // Closing brace. return value, err case json.Delim('['): value := make([]any, 0) for d.More() { child, err := jsonValue(d, fmt.Sprintf("%s/%d", path, len(value))) if err != nil { return nil, err } value = append(value, child) } _, err = d.Token() // Closing bracket. return value, err default: return token, nil } } type decoder struct { active map[*yaml.Node]bool values map[*yaml.Node]any } func (d *decoder) value(n *yaml.Node, path string) (any, error) { if n == nil { return nil, fmt.Errorf("%s: unresolved alias", pointer(path)) } if d.active[n] { return nil, nodeError(n, path, "cyclic alias") } if value, found := d.values[n]; found { return value, nil } d.active[n] = true defer delete(d.active, n) var value any var err error switch n.Kind { case yaml.DocumentNode: if len(n.Content) != 1 { return nil, nodeError(n, path, "expected one document") } value, err = d.value(n.Content[0], path) case yaml.AliasNode: value, err = d.value(n.Alias, path) case yaml.MappingNode: if n.ShortTag() != "!!map" { return nil, nodeError(n, path, "unsupported mapping tag %q", n.Tag) } mapping := make(map[string]any, len(n.Content)/2) for i := 0; i < len(n.Content); i += 2 { keyValue, keyErr := d.value(n.Content[i], path) if keyErr != nil { return nil, keyErr } key, ok := keyValue.(string) if !ok { return nil, nodeError(n.Content[i], path, "mapping key must be a string") } childPath := path + "/" + escape(key) if _, exists := mapping[key]; exists { return nil, nodeError(n.Content[i], childPath, "duplicate mapping key %q", key) } mapping[key], err = d.value(n.Content[i+1], childPath) if err != nil { return nil, err } } value = mapping case yaml.SequenceNode: if n.ShortTag() != "!!seq" { return nil, nodeError(n, path, "unsupported sequence tag %q", n.Tag) } sequence := make([]any, len(n.Content)) for i, child := range n.Content { sequence[i], err = d.value(child, fmt.Sprintf("%s/%d", path, i)) if err != nil { return nil, err } } value = sequence case yaml.ScalarNode: value, err = scalar(n) if err != nil { return nil, nodeError(n, path, "%v", err) } default: return nil, nodeError(n, path, "expected a document value") } if err == nil { d.values[n] = value } return value, err } func scalar(n *yaml.Node) (any, error) { switch n.ShortTag() { case "!!str": // go-yaml resolves decimal numbers outside machine-float range as // strings. Plain JSON numbers still retain numeric meaning in this // profile, including when the source serialization is JSON. if n.Style == 0 { if number, ok := jsonNumber(n.Value); ok { return number, nil } } return n.Value, nil case "!!timestamp": // Date-like scalars are text in the shared data model, not time.Time. return n.Value, nil case "!!bool", "!!null": var value any err := n.Decode(&value) return value, err case "!!int": text := strings.ReplaceAll(n.Value, "_", "") integer, ok := new(big.Int).SetString(text, 0) if !ok { integer, ok = new(big.Int).SetString(text, 10) } if !ok { return nil, fmt.Errorf("invalid integer %q", n.Value) } return json.Number(integer.String()), nil case "!!float": // Normalize YAML's leading '+', '.5', and '5.' spellings, retaining the // decimal digits instead of converting through float64. text := strings.TrimPrefix(strings.ReplaceAll(n.Value, "_", ""), "+") // Check syntax before supplying missing zeroes. Range errors are allowed: // the exact decimal representation need not fit in a machine float. if _, err := strconv.ParseFloat(text, 64); err != nil && !errors.Is(err, strconv.ErrRange) { return nil, fmt.Errorf("invalid float %q: %w", n.Value, err) } mantissa, exponent, hasExponent := strings.Cut(strings.ToLower(text), "e") sign := "" if strings.HasPrefix(mantissa, "-") { sign, mantissa = "-", strings.TrimPrefix(mantissa, "-") } whole, fraction, hasPoint := strings.Cut(mantissa, ".") whole = strings.TrimLeft(whole, "0") if whole == "" { whole = "0" } text = sign + whole if hasPoint { if fraction == "" { fraction = "0" } text += "." + fraction } if hasExponent { text += "e" + exponent } if number, ok := jsonNumber(text); ok { return number, nil } return nil, fmt.Errorf("number %q is not a finite JSON number", n.Value) default: return nil, fmt.Errorf("tag %q has no shared JSON representation", n.Tag) } } func jsonNumber(text string) (json.Number, bool) { if !json.Valid([]byte(text)) { return "", false } var value any decoder := json.NewDecoder(strings.NewReader(text)) decoder.UseNumber() if err := decoder.Decode(&value); err != nil { return "", false } number, ok := value.(json.Number) return number, ok } func nodeError(n *yaml.Node, path, format string, args ...any) error { return fmt.Errorf("%s (line %d, column %d): %s", pointer(path), n.Line, n.Column, fmt.Sprintf(format, args...)) } func pointer(path string) string { if path == "" { return "/" } return path } func escape(value string) string { return strings.ReplaceAll(strings.ReplaceAll(value, "~", "~0"), "/", "~1") }