Generated-output differences

quicktype output changed between the PR base and tested PR merge revisions.
← Back to the pull request
2test cases
36files differ
1modified
35new
0deleted
2,946changed lines
+2,941 −5insertions / deletions
Base a49b94e8f6f1b319a4da9fb15d57ef13ba316ddc · PR merge 26c50142f2d5349397191c2838effe9d0c36f1fc · Head 517556e63893ac067be4ab7c9c3379b7f717e412 · raw patch
Test case

test/inputs/schema/description-unification.schema

35 generated files · +2,936 −0
Aschema-cplusplusdefault / quicktype.hpp+126 −0
@@ -0,0 +1,126 @@
1+// To parse this JSON data, first install
2+//
3+// json.hpp https://github.com/nlohmann/json
4+//
5+// Then include this file, and then do
6+//
7+// TopLevel data = nlohmann::json::parse(jsonString);
8+
9+#pragma once
10+
11+#include "json.hpp"
12+
13+#include <optional>
14+#include <stdexcept>
15+#include <regex>
16+
17+namespace quicktype {
18+ using nlohmann::json;
19+
20+ #ifndef NLOHMANN_UNTYPED_quicktype_HELPER
21+ #define NLOHMANN_UNTYPED_quicktype_HELPER
22+ inline json get_untyped(const json & j, const char * property) {
23+ if (j.find(property) != j.end()) {
24+ return j.at(property).get<json>();
25+ }
26+ return json();
27+ }
28+
29+ inline json get_untyped(const json & j, std::string property) {
30+ return get_untyped(j, property.data());
31+ }
32+ #endif
33+
34+ class Allow {
35+ public:
36+ Allow() = default;
37+ virtual ~Allow() = default;
38+
39+ private:
40+ std::map<std::string, std::string> labels;
41+
42+ public:
43+ /**
44+ * The labels to apply to the policy
45+ */
46+ const std::map<std::string, std::string> & get_labels() const { return labels; }
47+ std::map<std::string, std::string> & get_mutable_labels() { return labels; }
48+ void set_labels(const std::map<std::string, std::string> & value) { this->labels = value; }
49+ };
50+
51+ class Metadata {
52+ public:
53+ Metadata() = default;
54+ virtual ~Metadata() = default;
55+
56+ private:
57+ std::map<std::string, std::string> annotations;
58+
59+ public:
60+ /**
61+ * Additional annotations for the generated resource
62+ */
63+ const std::map<std::string, std::string> & get_annotations() const { return annotations; }
64+ std::map<std::string, std::string> & get_mutable_annotations() { return annotations; }
65+ void set_annotations(const std::map<std::string, std::string> & value) { this->annotations = value; }
66+ };
67+
68+ class TopLevel {
69+ public:
70+ TopLevel() = default;
71+ virtual ~TopLevel() = default;
72+
73+ private:
74+ Allow allow;
75+ Metadata metadata;
76+
77+ public:
78+ const Allow & get_allow() const { return allow; }
79+ Allow & get_mutable_allow() { return allow; }
80+ void set_allow(const Allow & value) { this->allow = value; }
81+
82+ const Metadata & get_metadata() const { return metadata; }
83+ Metadata & get_mutable_metadata() { return metadata; }
84+ void set_metadata(const Metadata & value) { this->metadata = value; }
85+ };
86+}
87+
88+namespace quicktype {
89+ void from_json(const json & j, Allow & x);
90+ void to_json(json & j, const Allow & x);
91+
92+ void from_json(const json & j, Metadata & x);
93+ void to_json(json & j, const Metadata & x);
94+
95+ void from_json(const json & j, TopLevel & x);
96+ void to_json(json & j, const TopLevel & x);
97+
98+ inline void from_json(const json & j, Allow& x) {
99+ x.set_labels(j.at("labels").get<std::map<std::string, std::string>>());
100+ }
101+
102+ inline void to_json(json & j, const Allow & x) {
103+ j = json::object();
104+ j["labels"] = x.get_labels();
105+ }
106+
107+ inline void from_json(const json & j, Metadata& x) {
108+ x.set_annotations(j.at("annotations").get<std::map<std::string, std::string>>());
109+ }
110+
111+ inline void to_json(json & j, const Metadata & x) {
112+ j = json::object();
113+ j["annotations"] = x.get_annotations();
114+ }
115+
116+ inline void from_json(const json & j, TopLevel& x) {
117+ x.set_allow(j.at("allow").get<Allow>());
118+ x.set_metadata(j.at("metadata").get<Metadata>());
119+ }
120+
121+ inline void to_json(json & j, const TopLevel & x) {
122+ j = json::object();
123+ j["allow"] = x.get_allow();
124+ j["metadata"] = x.get_metadata();
125+ }
126+}
Aschema-csharp-recordsdefault / QuickType.cs+82 −0
@@ -0,0 +1,82 @@
1+// <auto-generated />
2+//
3+// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
4+//
5+// using QuickType;
6+//
7+// var topLevel = TopLevel.FromJson(jsonString);
8+#nullable enable
9+#pragma warning disable CS8618
10+#pragma warning disable CS8601
11+#pragma warning disable CS8602
12+#pragma warning disable CS8603
13+#pragma warning disable CS8604
14+#pragma warning disable CS8625
15+#pragma warning disable CS8765
16+
17+namespace QuickType
18+{
19+ using System;
20+ using System.Collections.Generic;
21+
22+ using System.Globalization;
23+ using Newtonsoft.Json;
24+ using Newtonsoft.Json.Converters;
25+
26+ public partial record TopLevel
27+ {
28+ [JsonProperty("allow", Required = Required.Always)]
29+ public Allow Allow { get; set; }
30+
31+ [JsonProperty("metadata", Required = Required.Always)]
32+ public Metadata Metadata { get; set; }
33+ }
34+
35+ public partial record Allow
36+ {
37+ /// <summary>
38+ /// The labels to apply to the policy
39+ /// </summary>
40+ [JsonProperty("labels", Required = Required.Always)]
41+ public Dictionary<string, string> Labels { get; set; }
42+ }
43+
44+ public partial record Metadata
45+ {
46+ /// <summary>
47+ /// Additional annotations for the generated resource
48+ /// </summary>
49+ [JsonProperty("annotations", Required = Required.Always)]
50+ public Dictionary<string, string> Annotations { get; set; }
51+ }
52+
53+ public partial record TopLevel
54+ {
55+ public static TopLevel FromJson(string json) => JsonConvert.DeserializeObject<TopLevel>(json, QuickType.Converter.Settings);
56+ }
57+
58+ public static partial class Serialize
59+ {
60+ public static string ToJson(this TopLevel self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
61+ }
62+
63+ internal static partial class Converter
64+ {
65+ public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
66+ {
67+ MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
68+ DateParseHandling = DateParseHandling.None,
69+ Converters =
70+ {
71+ new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
72+ },
73+ };
74+ }
75+}
76+#pragma warning restore CS8618
77+#pragma warning restore CS8601
78+#pragma warning restore CS8602
79+#pragma warning restore CS8603
80+#pragma warning restore CS8604
81+#pragma warning restore CS8625
82+#pragma warning restore CS8765
Aschema-csharp-SystemTextJsondefault / QuickType.cs+190 −0
@@ -0,0 +1,190 @@
1+// <auto-generated />
2+//
3+// To parse this JSON data, add NuGet 'System.Text.Json' then do:
4+//
5+// using QuickType;
6+//
7+// var topLevel = TopLevel.FromJson(jsonString);
8+#nullable enable
9+#pragma warning disable CS8618
10+#pragma warning disable CS8601
11+#pragma warning disable CS8602
12+#pragma warning disable CS8603
13+
14+namespace QuickType
15+{
16+ using System;
17+ using System.Collections.Generic;
18+
19+ using System.Text.Json;
20+ using System.Text.Json.Serialization;
21+ using System.Globalization;
22+
23+ public partial class TopLevel
24+ {
25+ [JsonRequired]
26+ [JsonPropertyName("allow")]
27+ public Allow Allow { get; set; }
28+
29+ [JsonRequired]
30+ [JsonPropertyName("metadata")]
31+ public Metadata Metadata { get; set; }
32+ }
33+
34+ public partial class Allow
35+ {
36+ /// <summary>
37+ /// The labels to apply to the policy
38+ /// </summary>
39+ [JsonRequired]
40+ [JsonPropertyName("labels")]
41+ public Dictionary<string, string> Labels { get; set; }
42+ }
43+
44+ public partial class Metadata
45+ {
46+ /// <summary>
47+ /// Additional annotations for the generated resource
48+ /// </summary>
49+ [JsonRequired]
50+ [JsonPropertyName("annotations")]
51+ public Dictionary<string, string> Annotations { get; set; }
52+ }
53+
54+ public partial class TopLevel
55+ {
56+ public static TopLevel FromJson(string json) => JsonSerializer.Deserialize<TopLevel>(json, QuickType.Converter.Settings);
57+ }
58+
59+ public static partial class Serialize
60+ {
61+ public static string ToJson(this TopLevel self) => JsonSerializer.Serialize(self, QuickType.Converter.Settings);
62+ }
63+
64+ internal static partial class Converter
65+ {
66+ public static readonly JsonSerializerOptions Settings = new(JsonSerializerDefaults.General)
67+ {
68+ Converters =
69+ {
70+ new DateOnlyConverter(),
71+ new TimeOnlyConverter(),
72+ IsoDateTimeOffsetConverter.Singleton
73+ },
74+ };
75+ }
76+
77+ public class DateOnlyConverter : JsonConverter<DateOnly>
78+ {
79+ private readonly string serializationFormat;
80+ public DateOnlyConverter() : this(null) { }
81+
82+ public DateOnlyConverter(string? serializationFormat)
83+ {
84+ this.serializationFormat = serializationFormat ?? "yyyy-MM-dd";
85+ }
86+
87+ public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
88+ {
89+ var value = reader.GetString();
90+ return DateOnly.Parse(value!);
91+ }
92+
93+ public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options)
94+ => writer.WriteStringValue(value.ToString(serializationFormat));
95+ }
96+
97+ public class TimeOnlyConverter : JsonConverter<TimeOnly>
98+ {
99+ private readonly string serializationFormat;
100+
101+ public TimeOnlyConverter() : this(null) { }
102+
103+ public TimeOnlyConverter(string? serializationFormat)
104+ {
105+ this.serializationFormat = serializationFormat ?? "HH:mm:ss.fff";
106+ }
107+
108+ public override TimeOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
109+ {
110+ var value = reader.GetString();
111+ return TimeOnly.Parse(value!);
112+ }
113+
114+ public override void Write(Utf8JsonWriter writer, TimeOnly value, JsonSerializerOptions options)
115+ => writer.WriteStringValue(value.ToString(serializationFormat));
116+ }
117+
118+ internal class IsoDateTimeOffsetConverter : JsonConverter<DateTimeOffset>
119+ {
120+ public override bool CanConvert(Type t) => t == typeof(DateTimeOffset);
121+
122+ private const string DefaultDateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";
123+
124+ private DateTimeStyles _dateTimeStyles = DateTimeStyles.RoundtripKind;
125+ private string? _dateTimeFormat;
126+ private CultureInfo? _culture;
127+
128+ public DateTimeStyles DateTimeStyles
129+ {
130+ get => _dateTimeStyles;
131+ set => _dateTimeStyles = value;
132+ }
133+
134+ public string? DateTimeFormat
135+ {
136+ get => _dateTimeFormat ?? string.Empty;
137+ set => _dateTimeFormat = (string.IsNullOrEmpty(value)) ? null : value;
138+ }
139+
140+ public CultureInfo Culture
141+ {
142+ get => _culture ?? CultureInfo.CurrentCulture;
143+ set => _culture = value;
144+ }
145+
146+ public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options)
147+ {
148+ string text;
149+
150+
151+ if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
152+ || (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
153+ {
154+ value = value.ToUniversalTime();
155+ }
156+
157+ text = value.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture);
158+
159+ writer.WriteStringValue(text);
160+ }
161+
162+ public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
163+ {
164+ string? dateText = reader.GetString();
165+
166+ if (string.IsNullOrEmpty(dateText) == false)
167+ {
168+ if (!string.IsNullOrEmpty(_dateTimeFormat))
169+ {
170+ return DateTimeOffset.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles);
171+ }
172+ else
173+ {
174+ return DateTimeOffset.Parse(dateText, Culture, _dateTimeStyles);
175+ }
176+ }
177+ else
178+ {
179+ return default(DateTimeOffset);
180+ }
181+ }
182+
183+
184+ public static readonly IsoDateTimeOffsetConverter Singleton = new IsoDateTimeOffsetConverter();
185+ }
186+}
187+#pragma warning restore CS8618
188+#pragma warning restore CS8601
189+#pragma warning restore CS8602
190+#pragma warning restore CS8603
Aschema-csharpdefault / QuickType.cs+82 −0
@@ -0,0 +1,82 @@
1+// <auto-generated />
2+//
3+// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
4+//
5+// using QuickType;
6+//
7+// var topLevel = TopLevel.FromJson(jsonString);
8+#nullable enable
9+#pragma warning disable CS8618
10+#pragma warning disable CS8601
11+#pragma warning disable CS8602
12+#pragma warning disable CS8603
13+#pragma warning disable CS8604
14+#pragma warning disable CS8625
15+#pragma warning disable CS8765
16+
17+namespace QuickType
18+{
19+ using System;
20+ using System.Collections.Generic;
21+
22+ using System.Globalization;
23+ using Newtonsoft.Json;
24+ using Newtonsoft.Json.Converters;
25+
26+ public partial class TopLevel
27+ {
28+ [JsonProperty("allow", Required = Required.Always)]
29+ public Allow Allow { get; set; }
30+
31+ [JsonProperty("metadata", Required = Required.Always)]
32+ public Metadata Metadata { get; set; }
33+ }
34+
35+ public partial class Allow
36+ {
37+ /// <summary>
38+ /// The labels to apply to the policy
39+ /// </summary>
40+ [JsonProperty("labels", Required = Required.Always)]
41+ public Dictionary<string, string> Labels { get; set; }
42+ }
43+
44+ public partial class Metadata
45+ {
46+ /// <summary>
47+ /// Additional annotations for the generated resource
48+ /// </summary>
49+ [JsonProperty("annotations", Required = Required.Always)]
50+ public Dictionary<string, string> Annotations { get; set; }
51+ }
52+
53+ public partial class TopLevel
54+ {
55+ public static TopLevel FromJson(string json) => JsonConvert.DeserializeObject<TopLevel>(json, QuickType.Converter.Settings);
56+ }
57+
58+ public static partial class Serialize
59+ {
60+ public static string ToJson(this TopLevel self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
61+ }
62+
63+ internal static partial class Converter
64+ {
65+ public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
66+ {
67+ MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
68+ DateParseHandling = DateParseHandling.None,
69+ Converters =
70+ {
71+ new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
72+ },
73+ };
74+ }
75+}
76+#pragma warning restore CS8618
77+#pragma warning restore CS8601
78+#pragma warning restore CS8602
79+#pragma warning restore CS8603
80+#pragma warning restore CS8604
81+#pragma warning restore CS8625
82+#pragma warning restore CS8765
Aschema-dartdefault / TopLevel.dart+65 −0
@@ -0,0 +1,65 @@
1+// To parse this JSON data, do
2+//
3+// final topLevel = topLevelFromJson(jsonString);
4+
5+import 'dart:convert';
6+
7+TopLevel topLevelFromJson(String str) => TopLevel.fromJson(json.decode(str));
8+
9+String topLevelToJson(TopLevel data) => json.encode(data.toJson());
10+
11+class TopLevel {
12+ final Allow allow;
13+ final Metadata metadata;
14+
15+ TopLevel({
16+ required this.allow,
17+ required this.metadata,
18+ });
19+
20+ factory TopLevel.fromJson(Map<String, dynamic> json) => TopLevel(
21+ allow: Allow.fromJson(json["allow"]),
22+ metadata: Metadata.fromJson(json["metadata"]),
23+ );
24+
25+ Map<String, dynamic> toJson() => {
26+ "allow": allow.toJson(),
27+ "metadata": metadata.toJson(),
28+ };
29+}
30+
31+class Allow {
32+
33+ ///The labels to apply to the policy
34+ final Map<String, String> labels;
35+
36+ Allow({
37+ required this.labels,
38+ });
39+
40+ factory Allow.fromJson(Map<String, dynamic> json) => Allow(
41+ labels: Map.from(json["labels"]).map((k, v) => MapEntry<String, String>(k, v)),
42+ );
43+
44+ Map<String, dynamic> toJson() => {
45+ "labels": Map.from(labels).map((k, v) => MapEntry<String, dynamic>(k, v)),
46+ };
47+}
48+
49+class Metadata {
50+
51+ ///Additional annotations for the generated resource
52+ final Map<String, String> annotations;
53+
54+ Metadata({
55+ required this.annotations,
56+ });
57+
58+ factory Metadata.fromJson(Map<String, dynamic> json) => Metadata(
59+ annotations: Map.from(json["annotations"]).map((k, v) => MapEntry<String, String>(k, v)),
60+ );
61+
62+ Map<String, dynamic> toJson() => {
63+ "annotations": Map.from(annotations).map((k, v) => MapEntry<String, dynamic>(k, v)),
64+ };
65+}
Aschema-elmdefault / QuickType.elm+92 −0
@@ -0,0 +1,92 @@
1+-- To decode the JSON data, add this file to your project, run
2+--
3+-- elm install NoRedInk/elm-json-decode-pipeline
4+--
5+-- add these imports
6+--
7+-- import Json.Decode exposing (decodeString)
8+-- import QuickType exposing (quickType)
9+--
10+-- and you're off to the races with
11+--
12+-- decodeString quickType myJsonString
13+
14+module QuickType exposing
15+ ( QuickType
16+ , quickTypeToString
17+ , quickType
18+ , Allow
19+ , Metadata
20+ )
21+
22+import Json.Decode as Jdec
23+import Json.Decode.Pipeline as Jpipe
24+import Json.Encode as Jenc
25+import Dict exposing (Dict)
26+
27+type alias QuickType =
28+ { allow : Allow
29+ , metadata : Metadata
30+ }
31+
32+{-| labels:
33+The labels to apply to the policy
34+-}
35+type alias Allow =
36+ { labels : Dict String String
37+ }
38+
39+{-| annotations:
40+Additional annotations for the generated resource
41+-}
42+type alias Metadata =
43+ { annotations : Dict String String
44+ }
45+
46+-- decoders and encoders
47+
48+quickTypeToString : QuickType -> String
49+quickTypeToString r = Jenc.encode 0 (encodeQuickType r)
50+
51+quickType : Jdec.Decoder QuickType
52+quickType =
53+ Jdec.succeed QuickType
54+ |> Jpipe.required "allow" allow
55+ |> Jpipe.required "metadata" metadata
56+
57+encodeQuickType : QuickType -> Jenc.Value
58+encodeQuickType x =
59+ Jenc.object
60+ [ ("allow", encodeAllow x.allow)
61+ , ("metadata", encodeMetadata x.metadata)
62+ ]
63+
64+allow : Jdec.Decoder Allow
65+allow =
66+ Jdec.succeed Allow
67+ |> Jpipe.required "labels" (Jdec.dict Jdec.string)
68+
69+encodeAllow : Allow -> Jenc.Value
70+encodeAllow x =
71+ Jenc.object
72+ [ ("labels", Jenc.dict identity Jenc.string x.labels)
73+ ]
74+
75+metadata : Jdec.Decoder Metadata
76+metadata =
77+ Jdec.succeed Metadata
78+ |> Jpipe.required "annotations" (Jdec.dict Jdec.string)
79+
80+encodeMetadata : Metadata -> Jenc.Value
81+encodeMetadata x =
82+ Jenc.object
83+ [ ("annotations", Jenc.dict identity Jenc.string x.annotations)
84+ ]
85+
86+--- encoder helpers
87+
88+makeNullableEncoder : (a -> Jenc.Value) -> Maybe a -> Jenc.Value
89+makeNullableEncoder f m =
90+ case m of
91+ Just x -> f x
92+ Nothing -> Jenc.null
Aschema-flowdefault / TopLevel.js+213 −0
@@ -0,0 +1,213 @@
1+// @flow
2+
3+// To parse this data:
4+//
5+// const Convert = require("./TopLevel");
6+//
7+// const topLevel = Convert.toTopLevel(json);
8+//
9+// These functions will throw an error if the JSON doesn't
10+// match the expected interface, even if the JSON is valid.
11+
12+export type TopLevel = {
13+ allow: Allow;
14+ metadata: Metadata;
15+ [property: string]: mixed;
16+};
17+
18+export type Allow = {
19+ /**
20+ * The labels to apply to the policy
21+ */
22+ labels: { [key: string]: string };
23+ [property: string]: mixed;
24+};
25+
26+export type Metadata = {
27+ /**
28+ * Additional annotations for the generated resource
29+ */
30+ annotations: { [key: string]: string };
31+ [property: string]: mixed;
32+};
33+
34+// Converts JSON strings to/from your types
35+// and asserts the results of JSON.parse at runtime
36+function toTopLevel(json: string): TopLevel {
37+ return cast(JSON.parse(json), r("TopLevel"));
38+}
39+
40+function topLevelToJson(value: TopLevel): string {
41+ return JSON.stringify(uncast(value, r("TopLevel")), null, 2);
42+}
43+
44+function invalidValue(typ: any, val: any, key: any, parent: any = '') {
45+ const prettyTyp = prettyTypeName(typ);
46+ const parentText = parent ? ` on ${parent}` : '';
47+ const keyText = key ? ` for key "${key}"` : '';
48+ throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`);
49+}
50+
51+function prettyTypeName(typ: any): string {
52+ if (Array.isArray(typ)) {
53+ if (typ.length === 2 && typ[0] === undefined) {
54+ return `an optional ${prettyTypeName(typ[1])}`;
55+ } else {
56+ return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`;
57+ }
58+ } else if (typeof typ === "object" && typ.literal !== undefined) {
59+ return typ.literal;
60+ } else {
61+ return typeof typ;
62+ }
63+}
64+
65+function jsonToJSProps(typ: any): any {
66+ if (typ.jsonToJS === undefined) {
67+ const map: any = {};
68+ typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ });
69+ typ.jsonToJS = map;
70+ }
71+ return typ.jsonToJS;
72+}
73+
74+function jsToJSONProps(typ: any): any {
75+ if (typ.jsToJSON === undefined) {
76+ const map: any = {};
77+ typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ });
78+ typ.jsToJSON = map;
79+ }
80+ return typ.jsToJSON;
81+}
82+
83+function transform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any {
84+ function transformPrimitive(typ: string, val: any): any {
85+ if (typeof typ === typeof val) return val;
86+ return invalidValue(typ, val, key, parent);
87+ }
88+
89+ function transformUnion(typs: any[], val: any): any {
90+ // val must validate against one typ in typs
91+ const l = typs.length;
92+ for (let i = 0; i < l; i++) {
93+ const typ = typs[i];
94+ try {
95+ return transform(val, typ, getProps);
96+ } catch (_) {}
97+ }
98+ return invalidValue(typs, val, key, parent);
99+ }
100+
101+ function transformEnum(cases: string[], val: any): any {
102+ if (cases.indexOf(val) !== -1) return val;
103+ return invalidValue(cases.map(a => { return l(a); }), val, key, parent);
104+ }
105+
106+ function transformArray(typ: any, val: any): any {
107+ // val must be an array with no invalid elements
108+ if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent);
109+ return val.map(el => transform(el, typ, getProps));
110+ }
111+
112+ function transformDate(val: any): any {
113+ if (val === null) {
114+ return null;
115+ }
116+ const d = new Date(val);
117+ if (isNaN(d.valueOf())) {
118+ return invalidValue(l("Date"), val, key, parent);
119+ }
120+ return d;
121+ }
122+
123+ function transformObject(props: { [k: string]: any }, additional: any, val: any): any {
124+ if (val === null || typeof val !== "object" || Array.isArray(val)) {
125+ return invalidValue(l(ref || "object"), val, key, parent);
126+ }
127+ const result: any = {};
128+ Object.getOwnPropertyNames(props).forEach(key => {
129+ const prop = props[key];
130+ const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined;
131+ result[prop.key] = transform(v, prop.typ, getProps, key, ref);
132+ });
133+ Object.getOwnPropertyNames(val).forEach(key => {
134+ if (!Object.prototype.hasOwnProperty.call(props, key)) {
135+ result[key] = transform(val[key], additional, getProps, key, ref);
136+ }
137+ });
138+ return result;
139+ }
140+
141+ if (typ === "any") return val;
142+ if (typ === null) {
143+ if (val === null) return val;
144+ return invalidValue(typ, val, key, parent);
145+ }
146+ if (typ === false) return invalidValue(typ, val, key, parent);
147+ let ref: any = undefined;
148+ while (typeof typ === "object" && typ.ref !== undefined) {
149+ ref = typ.ref;
150+ typ = typeMap[typ.ref];
151+ }
152+ if (Array.isArray(typ)) return transformEnum(typ, val);
153+ if (typeof typ === "object") {
154+ return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val)
155+ : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val)
156+ : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val)
157+ : invalidValue(typ, val, key, parent);
158+ }
159+ // Numbers can be parsed by Date but shouldn't be.
160+ if (typ === Date && typeof val !== "number") return transformDate(val);
161+ return transformPrimitive(typ, val);
162+}
163+
164+function cast<T>(val: any, typ: any): T {
165+ return transform(val, typ, jsonToJSProps);
166+}
167+
168+function uncast<T>(val: T, typ: any): any {
169+ return transform(val, typ, jsToJSONProps);
170+}
171+
172+function l(typ: any) {
173+ return { literal: typ };
174+}
175+
176+function a(typ: any) {
177+ return { arrayItems: typ };
178+}
179+
180+function u(...typs: any[]) {
181+ return { unionMembers: typs };
182+}
183+
184+function o(props: any[], additional: any) {
185+ return { props, additional };
186+}
187+
188+function m(additional: any) {
189+ const props: any[] = [];
190+ return { props, additional };
191+}
192+
193+function r(name: string) {
194+ return { ref: name };
195+}
196+
197+const typeMap: any = {
198+ "TopLevel": o([
199+ { json: "allow", js: "allow", typ: r("Allow") },
200+ { json: "metadata", js: "metadata", typ: r("Metadata") },
201+ ], "any"),
202+ "Allow": o([
203+ { json: "labels", js: "labels", typ: m("") },
204+ ], "any"),
205+ "Metadata": o([
206+ { json: "annotations", js: "annotations", typ: m("") },
207+ ], "any"),
208+};
209+
210+module.exports = {
211+ "topLevelToJson": topLevelToJson,
212+ "toTopLevel": toTopLevel,
213+};
Aschema-golangdefault / quicktype.go+34 −0
@@ -0,0 +1,34 @@
1+// Code generated from JSON Schema using quicktype. DO NOT EDIT.
2+// To parse and unparse this JSON data, add this code to your project and do:
3+//
4+// topLevel, err := UnmarshalTopLevel(bytes)
5+// bytes, err = topLevel.Marshal()
6+
7+package main
8+
9+import "encoding/json"
10+
11+func UnmarshalTopLevel(data []byte) (TopLevel, error) {
12+ var r TopLevel
13+ err := json.Unmarshal(data, &r)
14+ return r, err
15+}
16+
17+func (r *TopLevel) Marshal() ([]byte, error) {
18+ return json.Marshal(r)
19+}
20+
21+type TopLevel struct {
22+ Allow Allow `json:"allow"`
23+ Metadata Metadata `json:"metadata"`
24+}
25+
26+type Allow struct {
27+ // The labels to apply to the policy
28+ Labels map[string]string `json:"labels"`
29+}
30+
31+type Metadata struct {
32+ // Additional annotations for the generated resource
33+ Annotations map[string]string `json:"annotations"`
34+}
Aschema-java-datetime-legacydefault / src / main / java / io / quicktype / Allow.java+16 −0
@@ -0,0 +1,16 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+import java.util.Map;
5+
6+public class Allow {
7+ private Map<String, String> labels;
8+
9+ /**
10+ * The labels to apply to the policy
11+ */
12+ @JsonProperty("labels")
13+ public Map<String, String> getLabels() { return labels; }
14+ @JsonProperty("labels")
15+ public void setLabels(Map<String, String> value) { this.labels = value; }
16+}
Aschema-java-datetime-legacydefault / src / main / java / io / quicktype / Converter.java+121 −0
@@ -0,0 +1,121 @@
1+// To use this code, add the following Maven dependency to your project:
2+//
3+//
4+// com.fasterxml.jackson.core : jackson-databind : 2.9.0
5+//
6+//
7+// Import this package:
8+//
9+// import io.quicktype.Converter;
10+//
11+// Then you can deserialize a JSON string with
12+//
13+// TopLevel data = Converter.fromJsonString(jsonString);
14+
15+package io.quicktype;
16+
17+import java.io.IOException;
18+import com.fasterxml.jackson.databind.*;
19+import com.fasterxml.jackson.databind.module.SimpleModule;
20+import com.fasterxml.jackson.core.JsonParser;
21+import com.fasterxml.jackson.core.JsonProcessingException;
22+import java.util.*;
23+import java.util.Date;
24+import java.text.SimpleDateFormat;
25+
26+public class Converter {
27+ // Date-time helpers
28+
29+ private static final String[] DATE_TIME_FORMATS = {
30+ "yyyy-MM-dd'T'HH:mm:ss.SX",
31+ "yyyy-MM-dd'T'HH:mm:ss.S",
32+ "yyyy-MM-dd'T'HH:mm:ssX",
33+ "yyyy-MM-dd'T'HH:mm:ss",
34+ "yyyy-MM-dd HH:mm:ss.SX",
35+ "yyyy-MM-dd HH:mm:ss.S",
36+ "yyyy-MM-dd HH:mm:ssX",
37+ "yyyy-MM-dd HH:mm:ss",
38+ "HH:mm:ss.SZ",
39+ "HH:mm:ss.S",
40+ "HH:mm:ssZ",
41+ "HH:mm:ss",
42+ "yyyy-MM-dd",
43+ };
44+
45+ public static Date parseAllDateTimeString(String str) {
46+ for (String format : DATE_TIME_FORMATS) {
47+ try {
48+ return new SimpleDateFormat(format).parse(str);
49+ } catch (Exception ex) {
50+ // Ignored
51+ }
52+ }
53+ return null;
54+ }
55+
56+ public static String serializeDateTime(Date datetime) {
57+ return new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ").format(datetime);
58+ }
59+
60+ public static String serializeDate(Date datetime) {
61+ return new SimpleDateFormat("yyyy-MM-dd").format(datetime);
62+ }
63+
64+ public static String serializeTime(Date datetime) {
65+ return new SimpleDateFormat("hh:mm:ssZ").format(datetime);
66+ }
67+ // Serialize/deserialize helpers
68+
69+ public static TopLevel fromJsonString(String json) throws IOException {
70+ return getObjectReader().readValue(json);
71+ }
72+
73+ public static String toJsonString(TopLevel obj) throws JsonProcessingException {
74+ return getObjectWriter().writeValueAsString(obj);
75+ }
76+
77+ private static ObjectReader reader;
78+ private static ObjectWriter writer;
79+
80+ private static void instantiateMapper() {
81+ ObjectMapper mapper = new ObjectMapper();
82+ mapper.findAndRegisterModules();
83+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
84+ mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
85+ SimpleModule module = new SimpleModule();
86+ module.addDeserializer(Date.class, new JsonDeserializer<Date>() {
87+ @Override
88+ public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
89+ String value = jsonParser.getText();
90+ return Converter.parseAllDateTimeString(value);
91+ }
92+ });
93+ module.addDeserializer(Date.class, new JsonDeserializer<Date>() {
94+ @Override
95+ public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
96+ String value = jsonParser.getText();
97+ return Converter.parseAllDateTimeString(value);
98+ }
99+ });
100+ module.addDeserializer(Date.class, new JsonDeserializer<Date>() {
101+ @Override
102+ public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
103+ String value = jsonParser.getText();
104+ return Converter.parseAllDateTimeString(value);
105+ }
106+ });
107+ mapper.registerModule(module);
108+ reader = mapper.readerFor(TopLevel.class);
109+ writer = mapper.writerFor(TopLevel.class);
110+ }
111+
112+ private static ObjectReader getObjectReader() {
113+ if (reader == null) instantiateMapper();
114+ return reader;
115+ }
116+
117+ private static ObjectWriter getObjectWriter() {
118+ if (writer == null) instantiateMapper();
119+ return writer;
120+ }
121+}
Aschema-java-datetime-legacydefault / src / main / java / io / quicktype / Metadata.java+16 −0
@@ -0,0 +1,16 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+import java.util.Map;
5+
6+public class Metadata {
7+ private Map<String, String> annotations;
8+
9+ /**
10+ * Additional annotations for the generated resource
11+ */
12+ @JsonProperty("annotations")
13+ public Map<String, String> getAnnotations() { return annotations; }
14+ @JsonProperty("annotations")
15+ public void setAnnotations(Map<String, String> value) { this.annotations = value; }
16+}
Aschema-java-datetime-legacydefault / src / main / java / io / quicktype / TopLevel.java+18 −0
@@ -0,0 +1,18 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+
5+public class TopLevel {
6+ private Allow allow;
7+ private Metadata metadata;
8+
9+ @JsonProperty("allow")
10+ public Allow getAllow() { return allow; }
11+ @JsonProperty("allow")
12+ public void setAllow(Allow value) { this.allow = value; }
13+
14+ @JsonProperty("metadata")
15+ public Metadata getMetadata() { return metadata; }
16+ @JsonProperty("metadata")
17+ public void setMetadata(Metadata value) { this.metadata = value; }
18+}
Aschema-java-lombokdefault / src / main / java / io / quicktype / Allow.java+16 −0
@@ -0,0 +1,16 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+import java.util.Map;
5+
6+public class Allow {
7+ private Map<String, String> labels;
8+
9+ /**
10+ * The labels to apply to the policy
11+ */
12+ @JsonProperty("labels")
13+ public Map<String, String> getLabels() { return labels; }
14+ @JsonProperty("labels")
15+ public void setLabels(Map<String, String> value) { this.labels = value; }
16+}
Aschema-java-lombokdefault / src / main / java / io / quicktype / Converter.java+101 −0
@@ -0,0 +1,101 @@
1+// To use this code, add the following Maven dependency to your project:
2+//
3+//
4+// com.fasterxml.jackson.core : jackson-databind : 2.9.0
5+// com.fasterxml.jackson.datatype : jackson-datatype-jsr310 : 2.9.0
6+//
7+// Import this package:
8+//
9+// import io.quicktype.Converter;
10+//
11+// Then you can deserialize a JSON string with
12+//
13+// TopLevel data = Converter.fromJsonString(jsonString);
14+
15+package io.quicktype;
16+
17+import java.io.IOException;
18+import com.fasterxml.jackson.databind.*;
19+import com.fasterxml.jackson.databind.module.SimpleModule;
20+import com.fasterxml.jackson.core.JsonParser;
21+import com.fasterxml.jackson.core.JsonProcessingException;
22+import java.util.*;
23+import java.time.LocalDate;
24+import java.time.OffsetDateTime;
25+import java.time.OffsetTime;
26+import java.time.ZoneOffset;
27+import java.time.ZonedDateTime;
28+import java.time.format.DateTimeFormatter;
29+import java.time.format.DateTimeFormatterBuilder;
30+import java.time.temporal.ChronoField;
31+
32+public class Converter {
33+ // Date-time helpers
34+
35+ private static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder()
36+ .appendOptional(DateTimeFormatter.ISO_DATE_TIME)
37+ .appendOptional(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
38+ .appendOptional(DateTimeFormatter.ISO_INSTANT)
39+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SX"))
40+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssX"))
41+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
42+ .toFormatter()
43+ .withZone(ZoneOffset.UTC);
44+
45+ public static OffsetDateTime parseDateTimeString(String str) {
46+ return ZonedDateTime.from(Converter.DATE_TIME_FORMATTER.parse(str)).toOffsetDateTime();
47+ }
48+
49+ private static final DateTimeFormatter TIME_FORMATTER = new DateTimeFormatterBuilder()
50+ .appendOptional(DateTimeFormatter.ISO_TIME)
51+ .appendOptional(DateTimeFormatter.ISO_OFFSET_TIME)
52+ .parseDefaulting(ChronoField.YEAR, 2020)
53+ .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
54+ .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
55+ .toFormatter()
56+ .withZone(ZoneOffset.UTC);
57+
58+ public static OffsetTime parseTimeString(String str) {
59+ return ZonedDateTime.from(Converter.TIME_FORMATTER.parse(str)).toOffsetDateTime().toOffsetTime();
60+ }
61+ // Serialize/deserialize helpers
62+
63+ public static TopLevel fromJsonString(String json) throws IOException {
64+ return getObjectReader().readValue(json);
65+ }
66+
67+ public static String toJsonString(TopLevel obj) throws JsonProcessingException {
68+ return getObjectWriter().writeValueAsString(obj);
69+ }
70+
71+ private static ObjectReader reader;
72+ private static ObjectWriter writer;
73+
74+ private static void instantiateMapper() {
75+ ObjectMapper mapper = new ObjectMapper();
76+ mapper.findAndRegisterModules();
77+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
78+ mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
79+ SimpleModule module = new SimpleModule();
80+ module.addDeserializer(OffsetDateTime.class, new JsonDeserializer<OffsetDateTime>() {
81+ @Override
82+ public OffsetDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
83+ String value = jsonParser.getText();
84+ return Converter.parseDateTimeString(value);
85+ }
86+ });
87+ mapper.registerModule(module);
88+ reader = mapper.readerFor(TopLevel.class);
89+ writer = mapper.writerFor(TopLevel.class);
90+ }
91+
92+ private static ObjectReader getObjectReader() {
93+ if (reader == null) instantiateMapper();
94+ return reader;
95+ }
96+
97+ private static ObjectWriter getObjectWriter() {
98+ if (writer == null) instantiateMapper();
99+ return writer;
100+ }
101+}
Aschema-java-lombokdefault / src / main / java / io / quicktype / Metadata.java+16 −0
@@ -0,0 +1,16 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+import java.util.Map;
5+
6+public class Metadata {
7+ private Map<String, String> annotations;
8+
9+ /**
10+ * Additional annotations for the generated resource
11+ */
12+ @JsonProperty("annotations")
13+ public Map<String, String> getAnnotations() { return annotations; }
14+ @JsonProperty("annotations")
15+ public void setAnnotations(Map<String, String> value) { this.annotations = value; }
16+}
Aschema-java-lombokdefault / src / main / java / io / quicktype / TopLevel.java+18 −0
@@ -0,0 +1,18 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+
5+public class TopLevel {
6+ private Allow allow;
7+ private Metadata metadata;
8+
9+ @JsonProperty("allow")
10+ public Allow getAllow() { return allow; }
11+ @JsonProperty("allow")
12+ public void setAllow(Allow value) { this.allow = value; }
13+
14+ @JsonProperty("metadata")
15+ public Metadata getMetadata() { return metadata; }
16+ @JsonProperty("metadata")
17+ public void setMetadata(Metadata value) { this.metadata = value; }
18+}
Aschema-javadefault / src / main / java / io / quicktype / Allow.java+16 −0
@@ -0,0 +1,16 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+import java.util.Map;
5+
6+public class Allow {
7+ private Map<String, String> labels;
8+
9+ /**
10+ * The labels to apply to the policy
11+ */
12+ @JsonProperty("labels")
13+ public Map<String, String> getLabels() { return labels; }
14+ @JsonProperty("labels")
15+ public void setLabels(Map<String, String> value) { this.labels = value; }
16+}
Aschema-javadefault / src / main / java / io / quicktype / Converter.java+101 −0
@@ -0,0 +1,101 @@
1+// To use this code, add the following Maven dependency to your project:
2+//
3+//
4+// com.fasterxml.jackson.core : jackson-databind : 2.9.0
5+// com.fasterxml.jackson.datatype : jackson-datatype-jsr310 : 2.9.0
6+//
7+// Import this package:
8+//
9+// import io.quicktype.Converter;
10+//
11+// Then you can deserialize a JSON string with
12+//
13+// TopLevel data = Converter.fromJsonString(jsonString);
14+
15+package io.quicktype;
16+
17+import java.io.IOException;
18+import com.fasterxml.jackson.databind.*;
19+import com.fasterxml.jackson.databind.module.SimpleModule;
20+import com.fasterxml.jackson.core.JsonParser;
21+import com.fasterxml.jackson.core.JsonProcessingException;
22+import java.util.*;
23+import java.time.LocalDate;
24+import java.time.OffsetDateTime;
25+import java.time.OffsetTime;
26+import java.time.ZoneOffset;
27+import java.time.ZonedDateTime;
28+import java.time.format.DateTimeFormatter;
29+import java.time.format.DateTimeFormatterBuilder;
30+import java.time.temporal.ChronoField;
31+
32+public class Converter {
33+ // Date-time helpers
34+
35+ private static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder()
36+ .appendOptional(DateTimeFormatter.ISO_DATE_TIME)
37+ .appendOptional(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
38+ .appendOptional(DateTimeFormatter.ISO_INSTANT)
39+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SX"))
40+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssX"))
41+ .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
42+ .toFormatter()
43+ .withZone(ZoneOffset.UTC);
44+
45+ public static OffsetDateTime parseDateTimeString(String str) {
46+ return ZonedDateTime.from(Converter.DATE_TIME_FORMATTER.parse(str)).toOffsetDateTime();
47+ }
48+
49+ private static final DateTimeFormatter TIME_FORMATTER = new DateTimeFormatterBuilder()
50+ .appendOptional(DateTimeFormatter.ISO_TIME)
51+ .appendOptional(DateTimeFormatter.ISO_OFFSET_TIME)
52+ .parseDefaulting(ChronoField.YEAR, 2020)
53+ .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
54+ .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
55+ .toFormatter()
56+ .withZone(ZoneOffset.UTC);
57+
58+ public static OffsetTime parseTimeString(String str) {
59+ return ZonedDateTime.from(Converter.TIME_FORMATTER.parse(str)).toOffsetDateTime().toOffsetTime();
60+ }
61+ // Serialize/deserialize helpers
62+
63+ public static TopLevel fromJsonString(String json) throws IOException {
64+ return getObjectReader().readValue(json);
65+ }
66+
67+ public static String toJsonString(TopLevel obj) throws JsonProcessingException {
68+ return getObjectWriter().writeValueAsString(obj);
69+ }
70+
71+ private static ObjectReader reader;
72+ private static ObjectWriter writer;
73+
74+ private static void instantiateMapper() {
75+ ObjectMapper mapper = new ObjectMapper();
76+ mapper.findAndRegisterModules();
77+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
78+ mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
79+ SimpleModule module = new SimpleModule();
80+ module.addDeserializer(OffsetDateTime.class, new JsonDeserializer<OffsetDateTime>() {
81+ @Override
82+ public OffsetDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
83+ String value = jsonParser.getText();
84+ return Converter.parseDateTimeString(value);
85+ }
86+ });
87+ mapper.registerModule(module);
88+ reader = mapper.readerFor(TopLevel.class);
89+ writer = mapper.writerFor(TopLevel.class);
90+ }
91+
92+ private static ObjectReader getObjectReader() {
93+ if (reader == null) instantiateMapper();
94+ return reader;
95+ }
96+
97+ private static ObjectWriter getObjectWriter() {
98+ if (writer == null) instantiateMapper();
99+ return writer;
100+ }
101+}
Aschema-javadefault / src / main / java / io / quicktype / Metadata.java+16 −0
@@ -0,0 +1,16 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+import java.util.Map;
5+
6+public class Metadata {
7+ private Map<String, String> annotations;
8+
9+ /**
10+ * Additional annotations for the generated resource
11+ */
12+ @JsonProperty("annotations")
13+ public Map<String, String> getAnnotations() { return annotations; }
14+ @JsonProperty("annotations")
15+ public void setAnnotations(Map<String, String> value) { this.annotations = value; }
16+}
Aschema-javadefault / src / main / java / io / quicktype / TopLevel.java+18 −0
@@ -0,0 +1,18 @@
1+package io.quicktype;
2+
3+import com.fasterxml.jackson.annotation.*;
4+
5+public class TopLevel {
6+ private Allow allow;
7+ private Metadata metadata;
8+
9+ @JsonProperty("allow")
10+ public Allow getAllow() { return allow; }
11+ @JsonProperty("allow")
12+ public void setAllow(Allow value) { this.allow = value; }
13+
14+ @JsonProperty("metadata")
15+ public Metadata getMetadata() { return metadata; }
16+ @JsonProperty("metadata")
17+ public void setMetadata(Metadata value) { this.metadata = value; }
18+}
Aschema-javascriptdefault / TopLevel.js+189 −0
@@ -0,0 +1,189 @@
1+// To parse this data:
2+//
3+// const Convert = require("./TopLevel");
4+//
5+// const topLevel = Convert.toTopLevel(json);
6+//
7+// These functions will throw an error if the JSON doesn't
8+// match the expected interface, even if the JSON is valid.
9+
10+// Converts JSON strings to/from your types
11+// and asserts the results of JSON.parse at runtime
12+function toTopLevel(json) {
13+ return cast(JSON.parse(json), r("TopLevel"));
14+}
15+
16+function topLevelToJson(value) {
17+ return JSON.stringify(uncast(value, r("TopLevel")), null, 2);
18+}
19+
20+function invalidValue(typ, val, key, parent = '') {
21+ const prettyTyp = prettyTypeName(typ);
22+ const parentText = parent ? ` on ${parent}` : '';
23+ const keyText = key ? ` for key "${key}"` : '';
24+ throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`);
25+}
26+
27+function prettyTypeName(typ) {
28+ if (Array.isArray(typ)) {
29+ if (typ.length === 2 && typ[0] === undefined) {
30+ return `an optional ${prettyTypeName(typ[1])}`;
31+ } else {
32+ return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`;
33+ }
34+ } else if (typeof typ === "object" && typ.literal !== undefined) {
35+ return typ.literal;
36+ } else {
37+ return typeof typ;
38+ }
39+}
40+
41+function jsonToJSProps(typ) {
42+ if (typ.jsonToJS === undefined) {
43+ const map = {};
44+ typ.props.forEach((p) => map[p.json] = { key: p.js, typ: p.typ });
45+ typ.jsonToJS = map;
46+ }
47+ return typ.jsonToJS;
48+}
49+
50+function jsToJSONProps(typ) {
51+ if (typ.jsToJSON === undefined) {
52+ const map = {};
53+ typ.props.forEach((p) => map[p.js] = { key: p.json, typ: p.typ });
54+ typ.jsToJSON = map;
55+ }
56+ return typ.jsToJSON;
57+}
58+
59+function transform(val, typ, getProps, key = '', parent = '') {
60+ function transformPrimitive(typ, val) {
61+ if (typeof typ === typeof val) return val;
62+ return invalidValue(typ, val, key, parent);
63+ }
64+
65+ function transformUnion(typs, val) {
66+ // val must validate against one typ in typs
67+ const l = typs.length;
68+ for (let i = 0; i < l; i++) {
69+ const typ = typs[i];
70+ try {
71+ return transform(val, typ, getProps);
72+ } catch (_) {}
73+ }
74+ return invalidValue(typs, val, key, parent);
75+ }
76+
77+ function transformEnum(cases, val) {
78+ if (cases.indexOf(val) !== -1) return val;
79+ return invalidValue(cases.map(a => { return l(a); }), val, key, parent);
80+ }
81+
82+ function transformArray(typ, val) {
83+ // val must be an array with no invalid elements
84+ if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent);
85+ return val.map(el => transform(el, typ, getProps));
86+ }
87+
88+ function transformDate(val) {
89+ if (val === null) {
90+ return null;
91+ }
92+ const d = new Date(val);
93+ if (isNaN(d.valueOf())) {
94+ return invalidValue(l("Date"), val, key, parent);
95+ }
96+ return d;
97+ }
98+
99+ function transformObject(props, additional, val) {
100+ if (val === null || typeof val !== "object" || Array.isArray(val)) {
101+ return invalidValue(l(ref || "object"), val, key, parent);
102+ }
103+ const result = {};
104+ Object.getOwnPropertyNames(props).forEach(key => {
105+ const prop = props[key];
106+ const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined;
107+ result[prop.key] = transform(v, prop.typ, getProps, key, ref);
108+ });
109+ Object.getOwnPropertyNames(val).forEach(key => {
110+ if (!Object.prototype.hasOwnProperty.call(props, key)) {
111+ result[key] = transform(val[key], additional, getProps, key, ref);
112+ }
113+ });
114+ return result;
115+ }
116+
117+ if (typ === "any") return val;
118+ if (typ === null) {
119+ if (val === null) return val;
120+ return invalidValue(typ, val, key, parent);
121+ }
122+ if (typ === false) return invalidValue(typ, val, key, parent);
123+ let ref = undefined;
124+ while (typeof typ === "object" && typ.ref !== undefined) {
125+ ref = typ.ref;
126+ typ = typeMap[typ.ref];
127+ }
128+ if (Array.isArray(typ)) return transformEnum(typ, val);
129+ if (typeof typ === "object") {
130+ return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val)
131+ : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val)
132+ : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val)
133+ : invalidValue(typ, val, key, parent);
134+ }
135+ // Numbers can be parsed by Date but shouldn't be.
136+ if (typ === Date && typeof val !== "number") return transformDate(val);
137+ return transformPrimitive(typ, val);
138+}
139+
140+function cast(val, typ) {
141+ return transform(val, typ, jsonToJSProps);
142+}
143+
144+function uncast(val, typ) {
145+ return transform(val, typ, jsToJSONProps);
146+}
147+
148+function l(typ) {
149+ return { literal: typ };
150+}
151+
152+function a(typ) {
153+ return { arrayItems: typ };
154+}
155+
156+function u(...typs) {
157+ return { unionMembers: typs };
158+}
159+
160+function o(props, additional) {
161+ return { props, additional };
162+}
163+
164+function m(additional) {
165+ const props = [];
166+ return { props, additional };
167+}
168+
169+function r(name) {
170+ return { ref: name };
171+}
172+
173+const typeMap = {
174+ "TopLevel": o([
175+ { json: "allow", js: "allow", typ: r("Allow") },
176+ { json: "metadata", js: "metadata", typ: r("Metadata") },
177+ ], "any"),
178+ "Allow": o([
179+ { json: "labels", js: "labels", typ: m("") },
180+ ], "any"),
181+ "Metadata": o([
182+ { json: "annotations", js: "annotations", typ: m("") },
183+ ], "any"),
184+};
185+
186+module.exports = {
187+ "topLevelToJson": topLevelToJson,
188+ "toTopLevel": toTopLevel,
189+};
Aschema-kotlin-jacksondefault / TopLevel.kt+49 −0
@@ -0,0 +1,49 @@
1+// To parse the JSON, install jackson-module-kotlin and do:
2+//
3+// val topLevel = TopLevel.fromJson(jsonString)
4+
5+package quicktype
6+
7+import com.fasterxml.jackson.annotation.*
8+import com.fasterxml.jackson.core.*
9+import com.fasterxml.jackson.databind.*
10+import com.fasterxml.jackson.databind.deser.std.StdDeserializer
11+import com.fasterxml.jackson.databind.module.SimpleModule
12+import com.fasterxml.jackson.databind.node.*
13+import com.fasterxml.jackson.databind.ser.std.StdSerializer
14+import com.fasterxml.jackson.module.kotlin.*
15+
16+val mapper = jacksonObjectMapper().apply {
17+ propertyNamingStrategy = PropertyNamingStrategy.LOWER_CAMEL_CASE
18+ setSerializationInclusion(JsonInclude.Include.NON_NULL)
19+}
20+
21+data class TopLevel (
22+ @get:JsonProperty(required=true)@field:JsonProperty(required=true)
23+ val allow: Allow,
24+
25+ @get:JsonProperty(required=true)@field:JsonProperty(required=true)
26+ val metadata: Metadata
27+) {
28+ fun toJson() = mapper.writeValueAsString(this)
29+
30+ companion object {
31+ fun fromJson(json: String) = mapper.readValue<TopLevel>(json)
32+ }
33+}
34+
35+data class Allow (
36+ /**
37+ * The labels to apply to the policy
38+ */
39+ @get:JsonProperty(required=true)@field:JsonProperty(required=true)
40+ val labels: Map<String, String>
41+)
42+
43+data class Metadata (
44+ /**
45+ * Additional annotations for the generated resource
46+ */
47+ @get:JsonProperty(required=true)@field:JsonProperty(required=true)
48+ val annotations: Map<String, String>
49+)
Aschema-kotlindefault / TopLevel.kt+34 −0
@@ -0,0 +1,34 @@
1+// To parse the JSON, install Klaxon and do:
2+//
3+// val topLevel = TopLevel.fromJson(jsonString)
4+
5+package quicktype
6+
7+import com.beust.klaxon.*
8+
9+private val klaxon = Klaxon()
10+
11+data class TopLevel (
12+ val allow: Allow,
13+ val metadata: Metadata
14+) {
15+ public fun toJson() = klaxon.toJsonString(this)
16+
17+ companion object {
18+ public fun fromJson(json: String) = klaxon.parse<TopLevel>(json)
19+ }
20+}
21+
22+data class Allow (
23+ /**
24+ * The labels to apply to the policy
25+ */
26+ val labels: Map<String, String>
27+)
28+
29+data class Metadata (
30+ /**
31+ * Additional annotations for the generated resource
32+ */
33+ val annotations: Map<String, String>
34+)
Aschema-kotlinxdefault / TopLevel.kt+33 −0
@@ -0,0 +1,33 @@
1+// To parse the JSON, install kotlin's serialization plugin and do:
2+//
3+// val json = Json { allowStructuredMapKeys = true }
4+// val topLevel = json.parse(TopLevel.serializer(), jsonString)
5+
6+package quicktype
7+
8+import kotlinx.serialization.*
9+import kotlinx.serialization.json.*
10+import kotlinx.serialization.descriptors.*
11+import kotlinx.serialization.encoding.*
12+
13+@Serializable
14+data class TopLevel (
15+ val allow: Allow,
16+ val metadata: Metadata
17+)
18+
19+@Serializable
20+data class Allow (
21+ /**
22+ * The labels to apply to the policy
23+ */
24+ val labels: Map<String, String>
25+)
26+
27+@Serializable
28+data class Metadata (
29+ /**
30+ * Additional annotations for the generated resource
31+ */
32+ val annotations: Map<String, String>
33+)
Aschema-phpdefault / TopLevel.php+406 −0
@@ -0,0 +1,406 @@
1+<?php
2+declare(strict_types=1);
3+
4+// This is an autogenerated file:TopLevel
5+
6+class TopLevel {
7+ private Allow $allow; // json:allow Required
8+ private Metadata $metadata; // json:metadata Required
9+
10+ /**
11+ * @param Allow $allow
12+ * @param Metadata $metadata
13+ */
14+ public function __construct(Allow $allow, Metadata $metadata) {
15+ $this->allow = $allow;
16+ $this->metadata = $metadata;
17+ }
18+
19+ /**
20+ * @param stdClass $value
21+ * @throws Exception
22+ * @return Allow
23+ */
24+ public static function fromAllow(stdClass $value): Allow {
25+ return Allow::from($value); /*class*/
26+ }
27+
28+ /**
29+ * @throws Exception
30+ * @return stdClass
31+ */
32+ public function toAllow(): stdClass {
33+ if (TopLevel::validateAllow($this->allow)) {
34+ return $this->allow->to(); /*class*/
35+ }
36+ throw new Exception('never get to this TopLevel::allow');
37+ }
38+
39+ /**
40+ * @param Allow
41+ * @return bool
42+ * @throws Exception
43+ */
44+ public static function validateAllow(Allow $value): bool {
45+ $value->validate();
46+ return true;
47+ }
48+
49+ /**
50+ * @throws Exception
51+ * @return Allow
52+ */
53+ public function getAllow(): Allow {
54+ if (TopLevel::validateAllow($this->allow)) {
55+ return $this->allow;
56+ }
57+ throw new Exception('never get to getAllow TopLevel::allow');
58+ }
59+
60+ /**
61+ * @return Allow
62+ */
63+ public static function sampleAllow(): Allow {
64+ return Allow::sample(); /*31:allow*/
65+ }
66+
67+ /**
68+ * @param stdClass $value
69+ * @throws Exception
70+ * @return Metadata
71+ */
72+ public static function fromMetadata(stdClass $value): Metadata {
73+ return Metadata::from($value); /*class*/
74+ }
75+
76+ /**
77+ * @throws Exception
78+ * @return stdClass
79+ */
80+ public function toMetadata(): stdClass {
81+ if (TopLevel::validateMetadata($this->metadata)) {
82+ return $this->metadata->to(); /*class*/
83+ }
84+ throw new Exception('never get to this TopLevel::metadata');
85+ }
86+
87+ /**
88+ * @param Metadata
89+ * @return bool
90+ * @throws Exception
91+ */
92+ public static function validateMetadata(Metadata $value): bool {
93+ $value->validate();
94+ return true;
95+ }
96+
97+ /**
98+ * @throws Exception
99+ * @return Metadata
100+ */
101+ public function getMetadata(): Metadata {
102+ if (TopLevel::validateMetadata($this->metadata)) {
103+ return $this->metadata;
104+ }
105+ throw new Exception('never get to getMetadata TopLevel::metadata');
106+ }
107+
108+ /**
109+ * @return Metadata
110+ */
111+ public static function sampleMetadata(): Metadata {
112+ return Metadata::sample(); /*32:metadata*/
113+ }
114+
115+ /**
116+ * @throws Exception
117+ * @return bool
118+ */
119+ public function validate(): bool {
120+ return TopLevel::validateAllow($this->allow)
121+ || TopLevel::validateMetadata($this->metadata);
122+ }
123+
124+ /**
125+ * @return stdClass
126+ * @throws Exception
127+ */
128+ public function to(): stdClass {
129+ $out = new stdClass();
130+ $out->{'allow'} = $this->toAllow();
131+ $out->{'metadata'} = $this->toMetadata();
132+ return $out;
133+ }
134+
135+ /**
136+ * @param stdClass $obj
137+ * @return TopLevel
138+ * @throws Exception
139+ */
140+ public static function from(stdClass $obj): TopLevel {
141+ return new TopLevel(
142+ TopLevel::fromAllow($obj->{'allow'})
143+ ,TopLevel::fromMetadata($obj->{'metadata'})
144+ );
145+ }
146+
147+ /**
148+ * @return TopLevel
149+ */
150+ public static function sample(): TopLevel {
151+ return new TopLevel(
152+ TopLevel::sampleAllow()
153+ ,TopLevel::sampleMetadata()
154+ );
155+ }
156+}
157+
158+// This is an autogenerated file:Allow
159+
160+class Allow {
161+ private stdClass $labels; // json:labels Required
162+
163+ /**
164+ * @param stdClass $labels
165+ */
166+ public function __construct(stdClass $labels) {
167+ $this->labels = $labels;
168+ }
169+
170+ /**
171+ * The labels to apply to the policy
172+ *
173+ * @param stdClass $value
174+ * @throws Exception
175+ * @return stdClass
176+ */
177+ public static function fromLabels(stdClass $value): stdClass {
178+ $out = new stdClass();
179+ foreach ($value as $k => $v) {
180+ $out->$k = $v; /*string*/
181+ }
182+ return $out;
183+ }
184+
185+ /**
186+ * The labels to apply to the policy
187+ *
188+ * @throws Exception
189+ * @return stdClass
190+ */
191+ public function toLabels(): stdClass {
192+ if (Allow::validateLabels($this->labels)) {
193+ $out = new stdClass();
194+ foreach ($this->labels as $k => $v) {
195+ $out->$k = $v; /*string*/
196+ }
197+ return $out;
198+ }
199+ throw new Exception('never get to this Allow::labels');
200+ }
201+
202+ /**
203+ * The labels to apply to the policy
204+ *
205+ * @param stdClass
206+ * @return bool
207+ * @throws Exception
208+ */
209+ public static function validateLabels(stdClass $value): bool {
210+ foreach ($value as $k => $v) {
211+ if (!is_string($v)) {
212+ throw new Exception("Attribute Error:Allow::labels");
213+ }
214+ }
215+ return true;
216+ }
217+
218+ /**
219+ * The labels to apply to the policy
220+ *
221+ * @throws Exception
222+ * @return stdClass
223+ */
224+ public function getLabels(): stdClass {
225+ if (Allow::validateLabels($this->labels)) {
226+ return $this->labels;
227+ }
228+ throw new Exception('never get to getLabels Allow::labels');
229+ }
230+
231+ /**
232+ * The labels to apply to the policy
233+ *
234+ * @return stdClass
235+ */
236+ public static function sampleLabels(): stdClass {
237+ return (function () {
238+ $out = new stdClass();
239+ $out->{'Allow'} = 'Allow::labels::31'; /*31:labels*/
240+ return $out;
241+ })(); /* 31:labels*/
242+ }
243+
244+ /**
245+ * @throws Exception
246+ * @return bool
247+ */
248+ public function validate(): bool {
249+ return Allow::validateLabels($this->labels);
250+ }
251+
252+ /**
253+ * @return stdClass
254+ * @throws Exception
255+ */
256+ public function to(): stdClass {
257+ $out = new stdClass();
258+ $out->{'labels'} = $this->toLabels();
259+ return $out;
260+ }
261+
262+ /**
263+ * @param stdClass $obj
264+ * @return Allow
265+ * @throws Exception
266+ */
267+ public static function from(stdClass $obj): Allow {
268+ return new Allow(
269+ Allow::fromLabels($obj->{'labels'})
270+ );
271+ }
272+
273+ /**
274+ * @return Allow
275+ */
276+ public static function sample(): Allow {
277+ return new Allow(
278+ Allow::sampleLabels()
279+ );
280+ }
281+}
282+
283+// This is an autogenerated file:Metadata
284+
285+class Metadata {
286+ private stdClass $annotations; // json:annotations Required
287+
288+ /**
289+ * @param stdClass $annotations
290+ */
291+ public function __construct(stdClass $annotations) {
292+ $this->annotations = $annotations;
293+ }
294+
295+ /**
296+ * Additional annotations for the generated resource
297+ *
298+ * @param stdClass $value
299+ * @throws Exception
300+ * @return stdClass
301+ */
302+ public static function fromAnnotations(stdClass $value): stdClass {
303+ $out = new stdClass();
304+ foreach ($value as $k => $v) {
305+ $out->$k = $v; /*string*/
306+ }
307+ return $out;
308+ }
309+
310+ /**
311+ * Additional annotations for the generated resource
312+ *
313+ * @throws Exception
314+ * @return stdClass
315+ */
316+ public function toAnnotations(): stdClass {
317+ if (Metadata::validateAnnotations($this->annotations)) {
318+ $out = new stdClass();
319+ foreach ($this->annotations as $k => $v) {
320+ $out->$k = $v; /*string*/
321+ }
322+ return $out;
323+ }
324+ throw new Exception('never get to this Metadata::annotations');
325+ }
326+
327+ /**
328+ * Additional annotations for the generated resource
329+ *
330+ * @param stdClass
331+ * @return bool
332+ * @throws Exception
333+ */
334+ public static function validateAnnotations(stdClass $value): bool {
335+ foreach ($value as $k => $v) {
336+ if (!is_string($v)) {
337+ throw new Exception("Attribute Error:Metadata::annotations");
338+ }
339+ }
340+ return true;
341+ }
342+
343+ /**
344+ * Additional annotations for the generated resource
345+ *
346+ * @throws Exception
347+ * @return stdClass
348+ */
349+ public function getAnnotations(): stdClass {
350+ if (Metadata::validateAnnotations($this->annotations)) {
351+ return $this->annotations;
352+ }
353+ throw new Exception('never get to getAnnotations Metadata::annotations');
354+ }
355+
356+ /**
357+ * Additional annotations for the generated resource
358+ *
359+ * @return stdClass
360+ */
361+ public static function sampleAnnotations(): stdClass {
362+ return (function () {
363+ $out = new stdClass();
364+ $out->{'Metadata'} = 'Metadata::annotations::31'; /*31:annotations*/
365+ return $out;
366+ })(); /* 31:annotations*/
367+ }
368+
369+ /**
370+ * @throws Exception
371+ * @return bool
372+ */
373+ public function validate(): bool {
374+ return Metadata::validateAnnotations($this->annotations);
375+ }
376+
377+ /**
378+ * @return stdClass
379+ * @throws Exception
380+ */
381+ public function to(): stdClass {
382+ $out = new stdClass();
383+ $out->{'annotations'} = $this->toAnnotations();
384+ return $out;
385+ }
386+
387+ /**
388+ * @param stdClass $obj
389+ * @return Metadata
390+ * @throws Exception
391+ */
392+ public static function from(stdClass $obj): Metadata {
393+ return new Metadata(
394+ Metadata::fromAnnotations($obj->{'annotations'})
395+ );
396+ }
397+
398+ /**
399+ * @return Metadata
400+ */
401+ public static function sample(): Metadata {
402+ return new Metadata(
403+ Metadata::sampleAnnotations()
404+ );
405+ }
406+}
Aschema-pikedefault / TopLevel.pmod+76 −0
@@ -0,0 +1,76 @@
1+// This source has been automatically generated by quicktype.
2+// ( https://github.com/quicktype/quicktype )
3+//
4+// To use this code, simply import it into your project as a Pike module.
5+// To JSON-encode your object, you can pass it to `Standards.JSON.encode`
6+// or call `encode_json` on it.
7+//
8+// To decode a JSON string, first pass it to `Standards.JSON.decode`,
9+// and then pass the result to `<YourClass>_from_JSON`.
10+// It will return an instance of <YourClass>.
11+// Bear in mind that these functions have unexpected behavior,
12+// and will likely throw an error, if the JSON string does not
13+// match the expected interface, even if the JSON itself is valid.
14+
15+class TopLevel {
16+ Allow allow; // json: "allow"
17+ Metadata metadata; // json: "metadata"
18+
19+ string encode_json() {
20+ mapping(string:mixed) json = ([
21+ "allow" : allow,
22+ "metadata" : metadata,
23+ ]);
24+
25+ return Standards.JSON.encode(json);
26+ }
27+}
28+
29+TopLevel TopLevel_from_JSON(mixed json) {
30+ TopLevel retval = TopLevel();
31+
32+ retval.allow = json["allow"];
33+ retval.metadata = json["metadata"];
34+
35+ return retval;
36+}
37+
38+class Allow {
39+ mapping(string:string) labels; // json: "labels"
40+
41+ string encode_json() {
42+ mapping(string:mixed) json = ([
43+ "labels" : labels,
44+ ]);
45+
46+ return Standards.JSON.encode(json);
47+ }
48+}
49+
50+Allow Allow_from_JSON(mixed json) {
51+ Allow retval = Allow();
52+
53+ retval.labels = json["labels"];
54+
55+ return retval;
56+}
57+
58+class Metadata {
59+ mapping(string:string) annotations; // json: "annotations"
60+
61+ string encode_json() {
62+ mapping(string:mixed) json = ([
63+ "annotations" : annotations,
64+ ]);
65+
66+ return Standards.JSON.encode(json);
67+ }
68+}
69+
70+Metadata Metadata_from_JSON(mixed json) {
71+ Metadata retval = Metadata();
72+
73+ retval.annotations = json["annotations"];
74+
75+ return retval;
76+}
Aschema-pythondefault / quicktype.py+81 −0
@@ -0,0 +1,81 @@
1+from dataclasses import dataclass
2+from typing import Any, TypeVar, Callable, Type, cast
3+
4+
5+T = TypeVar("T")
6+
7+
8+def from_dict(f: Callable[[Any], T], x: Any) -> dict[str, T]:
9+ assert isinstance(x, dict)
10+ return { k: f(v) for (k, v) in x.items() }
11+
12+
13+def from_str(x: Any) -> str:
14+ assert isinstance(x, str)
15+ return x
16+
17+
18+def to_class(c: Type[T], x: Any) -> dict:
19+ assert isinstance(x, c)
20+ return cast(Any, x).to_dict()
21+
22+
23+@dataclass
24+class Allow:
25+ labels: dict[str, str]
26+ """The labels to apply to the policy"""
27+
28+ @staticmethod
29+ def from_dict(obj: Any) -> 'Allow':
30+ assert isinstance(obj, dict)
31+ labels = from_dict(from_str, obj.get("labels"))
32+ return Allow(labels)
33+
34+ def to_dict(self) -> dict:
35+ result: dict = {}
36+ result["labels"] = from_dict(from_str, self.labels)
37+ return result
38+
39+
40+@dataclass
41+class Metadata:
42+ annotations: dict[str, str]
43+ """Additional annotations for the generated resource"""
44+
45+ @staticmethod
46+ def from_dict(obj: Any) -> 'Metadata':
47+ assert isinstance(obj, dict)
48+ annotations = from_dict(from_str, obj.get("annotations"))
49+ return Metadata(annotations)
50+
51+ def to_dict(self) -> dict:
52+ result: dict = {}
53+ result["annotations"] = from_dict(from_str, self.annotations)
54+ return result
55+
56+
57+@dataclass
58+class TopLevel:
59+ allow: Allow
60+ metadata: Metadata
61+
62+ @staticmethod
63+ def from_dict(obj: Any) -> 'TopLevel':
64+ assert isinstance(obj, dict)
65+ allow = Allow.from_dict(obj.get("allow"))
66+ metadata = Metadata.from_dict(obj.get("metadata"))
67+ return TopLevel(allow, metadata)
68+
69+ def to_dict(self) -> dict:
70+ result: dict = {}
71+ result["allow"] = to_class(Allow, self.allow)
72+ result["metadata"] = to_class(Metadata, self.metadata)
73+ return result
74+
75+
76+def top_level_from_dict(s: Any) -> TopLevel:
77+ return TopLevel.from_dict(s)
78+
79+
80+def top_level_to_dict(x: TopLevel) -> Any:
81+ return to_class(TopLevel, x)
Aschema-rubydefault / TopLevel.rb+102 −0
@@ -0,0 +1,102 @@
1+# This code may look unusually verbose for Ruby (and it is), but
2+# it performs some subtle and complex validation of JSON data.
3+#
4+# To parse this JSON, add 'dry-struct' and 'dry-types' gems, then do:
5+#
6+# top_level = TopLevel.from_json! "{…}"
7+# puts top_level.metadata.annotations["…"]
8+#
9+# If from_json! succeeds, the value returned matches the schema.
10+
11+require 'json'
12+require 'dry-types'
13+require 'dry-struct'
14+
15+module Types
16+ include Dry.Types(default: :nominal)
17+
18+ Hash = Strict::Hash
19+ String = Strict::String
20+end
21+
22+class Allow < Dry::Struct
23+
24+ # The labels to apply to the policy
25+ attribute :labels, Types::Hash.meta(of: Types::String)
26+
27+ def self.from_dynamic!(d)
28+ d = Types::Hash[d]
29+ new(
30+ labels: Types::Hash[d.fetch("labels")].map { |k, v| [k, Types::String[v]] }.to_h,
31+ )
32+ end
33+
34+ def self.from_json!(json)
35+ from_dynamic!(JSON.parse(json))
36+ end
37+
38+ def to_dynamic
39+ {
40+ "labels" => labels,
41+ }
42+ end
43+
44+ def to_json(options = nil)
45+ JSON.generate(to_dynamic, options)
46+ end
47+end
48+
49+class Metadata < Dry::Struct
50+
51+ # Additional annotations for the generated resource
52+ attribute :annotations, Types::Hash.meta(of: Types::String)
53+
54+ def self.from_dynamic!(d)
55+ d = Types::Hash[d]
56+ new(
57+ annotations: Types::Hash[d.fetch("annotations")].map { |k, v| [k, Types::String[v]] }.to_h,
58+ )
59+ end
60+
61+ def self.from_json!(json)
62+ from_dynamic!(JSON.parse(json))
63+ end
64+
65+ def to_dynamic
66+ {
67+ "annotations" => annotations,
68+ }
69+ end
70+
71+ def to_json(options = nil)
72+ JSON.generate(to_dynamic, options)
73+ end
74+end
75+
76+class TopLevel < Dry::Struct
77+ attribute :allow, Allow
78+ attribute :metadata, Metadata
79+
80+ def self.from_dynamic!(d)
81+ d = Types::Hash[d]
82+ new(
83+ allow: Allow.from_dynamic!(d.fetch("allow")),
84+ metadata: Metadata.from_dynamic!(d.fetch("metadata")),
85+ )
86+ end
87+
88+ def self.from_json!(json)
89+ from_dynamic!(JSON.parse(json))
90+ end
91+
92+ def to_dynamic
93+ {
94+ "allow" => allow.to_dynamic,
95+ "metadata" => metadata.to_dynamic,
96+ }
97+ end
98+
99+ def to_json(options = nil)
100+ JSON.generate(to_dynamic, options)
101+ end
102+end
Aschema-rustdefault / module_under_test.rs+34 −0
@@ -0,0 +1,34 @@
1+// Example code that deserializes and serializes the model.
2+// extern crate serde;
3+// #[macro_use]
4+// extern crate serde_derive;
5+// extern crate serde_json;
6+//
7+// use generated_module::TopLevel;
8+//
9+// fn main() {
10+// let json = r#"{"answer": 42}"#;
11+// let model: TopLevel = serde_json::from_str(&json).unwrap();
12+// }
13+
14+use serde::{Serialize, Deserialize};
15+use std::collections::HashMap;
16+
17+#[derive(Debug, Clone, Serialize, Deserialize)]
18+pub struct TopLevel {
19+ pub allow: Allow,
20+
21+ pub metadata: Metadata,
22+}
23+
24+#[derive(Debug, Clone, Serialize, Deserialize)]
25+pub struct Allow {
26+ /// The labels to apply to the policy
27+ pub labels: HashMap<String, String>,
28+}
29+
30+#[derive(Debug, Clone, Serialize, Deserialize)]
31+pub struct Metadata {
32+ /// Additional annotations for the generated resource
33+ pub annotations: HashMap<String, String>,
34+}
Aschema-scala3-upickledefault / TopLevel.scala+85 −0
@@ -0,0 +1,85 @@
1+package quicktype
2+
3+// Custom pickler so that missing keys and JSON nulls both read as None,
4+// and None is left out when writing (upickle's default for Option is a
5+// JSON array).
6+object OptionPickler extends upickle.AttributeTagged:
7+ import upickle.default.Writer
8+ import upickle.default.Reader
9+ override implicit def OptionWriter[T: Writer]: Writer[Option[T]] =
10+ implicitly[Writer[T]].comap[Option[T]] {
11+ case None => null.asInstanceOf[T]
12+ case Some(x) => x
13+ }
14+
15+ override implicit def OptionReader[T: Reader]: Reader[Option[T]] = {
16+ new Reader.Delegate[Any, Option[T]](implicitly[Reader[T]].map(Some(_))){
17+ override def visitNull(index: Int) = None
18+ }
19+ }
20+end OptionPickler
21+
22+// If a union has a null in, then we'll need this too...
23+type NullValue = None.type
24+given OptionPickler.ReadWriter[NullValue] = OptionPickler.readwriter[ujson.Value].bimap[NullValue](
25+ _ => ujson.Null,
26+ json => if json.isNull then None else throw new upickle.core.Abort("not null")
27+)
28+
29+object JsonExt:
30+ val valueReader = OptionPickler.readwriter[ujson.Value]
31+
32+ // upickle's built-in primitive readers are lenient -- the numeric and
33+ // boolean readers accept strings, and the string reader accepts
34+ // numbers and booleans -- so untagged unions need strict readers to
35+ // pick the right member.
36+ val strictString: OptionPickler.Reader[String] = valueReader.map {
37+ case ujson.Str(s) => s
38+ case json => throw new upickle.core.Abort("expected string, got " + json)
39+ }
40+ val strictLong: OptionPickler.Reader[Long] = valueReader.map {
41+ case ujson.Num(n) if n.isWhole => n.toLong
42+ case json => throw new upickle.core.Abort("expected integer, got " + json)
43+ }
44+ val strictDouble: OptionPickler.Reader[Double] = valueReader.map {
45+ case ujson.Num(n) => n
46+ case json => throw new upickle.core.Abort("expected number, got " + json)
47+ }
48+ val strictBoolean: OptionPickler.Reader[Boolean] = valueReader.map {
49+ case ujson.Bool(b) => b
50+ case json => throw new upickle.core.Abort("expected boolean, got " + json)
51+ }
52+
53+ def badMerge[T](r1: => OptionPickler.Reader[?], rest: OptionPickler.Reader[?]*): OptionPickler.Reader[T] = valueReader.map { json =>
54+ var t: T | Null = null
55+ val stack = Vector.newBuilder[Throwable]
56+ (r1 +: rest).foreach { reader =>
57+ if t == null then
58+ try
59+ t = OptionPickler.read[T](json, trace = true)(using reader.asInstanceOf[OptionPickler.Reader[T]])
60+ catch
61+ case exc => stack += exc
62+ }
63+ if t != null then t.nn else throw new Exception(json.toString(), stack.result().headOption.getOrElse(null))
64+ }
65+end JsonExt
66+
67+
68+case class TopLevel (
69+ val allow : Allow,
70+ val metadata : Metadata
71+) derives OptionPickler.ReadWriter
72+
73+case class Allow (
74+ /**
75+ * The labels to apply to the policy
76+ */
77+ val labels : Map[String, String]
78+) derives OptionPickler.ReadWriter
79+
80+case class Metadata (
81+ /**
82+ * Additional annotations for the generated resource
83+ */
84+ val annotations : Map[String, String]
85+) derives OptionPickler.ReadWriter
Aschema-scala3default / TopLevel.scala+27 −0
@@ -0,0 +1,27 @@
1+package quicktype
2+
3+import io.circe.syntax._
4+import io.circe._
5+import cats.syntax.functor._
6+
7+// If a union has a null in, then we'll need this too...
8+type NullValue = None.type
9+
10+case class TopLevel (
11+ val allow : Allow,
12+ val metadata : Metadata
13+) derives Encoder.AsObject, Decoder
14+
15+case class Allow (
16+ /**
17+ * The labels to apply to the policy
18+ */
19+ val labels : Map[String, String]
20+) derives Encoder.AsObject, Decoder
21+
22+case class Metadata (
23+ /**
24+ * Additional annotations for the generated resource
25+ */
26+ val annotations : Map[String, String]
27+) derives Encoder.AsObject, Decoder
Aschema-schemadefault / TopLevel.schema+57 −0
@@ -0,0 +1,57 @@
1+{
2+ "$schema": "http://json-schema.org/draft-06/schema#",
3+ "$ref": "#/definitions/TopLevel",
4+ "definitions": {
5+ "TopLevel": {
6+ "type": "object",
7+ "additionalProperties": {},
8+ "properties": {
9+ "allow": {
10+ "$ref": "#/definitions/Allow"
11+ },
12+ "metadata": {
13+ "$ref": "#/definitions/Metadata"
14+ }
15+ },
16+ "required": [
17+ "allow",
18+ "metadata"
19+ ],
20+ "title": "TopLevel"
21+ },
22+ "Allow": {
23+ "type": "object",
24+ "additionalProperties": {},
25+ "properties": {
26+ "labels": {
27+ "type": "object",
28+ "additionalProperties": {
29+ "type": "string"
30+ },
31+ "description": "The labels to apply to the policy"
32+ }
33+ },
34+ "required": [
35+ "labels"
36+ ],
37+ "title": "Allow"
38+ },
39+ "Metadata": {
40+ "type": "object",
41+ "additionalProperties": {},
42+ "properties": {
43+ "annotations": {
44+ "type": "object",
45+ "additionalProperties": {
46+ "type": "string"
47+ },
48+ "description": "Additional annotations for the generated resource"
49+ }
50+ },
51+ "required": [
52+ "annotations"
53+ ],
54+ "title": "Metadata"
55+ }
56+ }
57+}
Aschema-swiftdefault / quicktype.swift+180 −0
@@ -0,0 +1,180 @@
1+// This file was generated from JSON Schema using quicktype, do not modify it directly.
2+// To parse the JSON, add this file to your project and do:
3+//
4+// let topLevel = try TopLevel(json)
5+
6+import Foundation
7+
8+// MARK: - TopLevel
9+struct TopLevel: Codable {
10+ let allow: Allow
11+ let metadata: Metadata
12+
13+ enum CodingKeys: String, CodingKey {
14+ case allow = "allow"
15+ case metadata = "metadata"
16+ }
17+}
18+
19+// MARK: TopLevel convenience initializers and mutators
20+
21+extension TopLevel {
22+ init(data: Data) throws {
23+ self = try newJSONDecoder().decode(TopLevel.self, from: data)
24+ }
25+
26+ init(_ json: String, using encoding: String.Encoding = .utf8) throws {
27+ guard let data = json.data(using: encoding) else {
28+ throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
29+ }
30+ try self.init(data: data)
31+ }
32+
33+ init(fromURL url: URL) throws {
34+ try self.init(data: try Data(contentsOf: url))
35+ }
36+
37+ func with(
38+ allow: Allow? = nil,
39+ metadata: Metadata? = nil
40+ ) -> TopLevel {
41+ return TopLevel(
42+ allow: allow ?? self.allow,
43+ metadata: metadata ?? self.metadata
44+ )
45+ }
46+
47+ func jsonData() throws -> Data {
48+ return try newJSONEncoder().encode(self)
49+ }
50+
51+ func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
52+ return String(data: try self.jsonData(), encoding: encoding)
53+ }
54+}
55+
56+// MARK: - Allow
57+struct Allow: Codable {
58+ /// The labels to apply to the policy
59+ let labels: [String: String]
60+
61+ enum CodingKeys: String, CodingKey {
62+ case labels = "labels"
63+ }
64+}
65+
66+// MARK: Allow convenience initializers and mutators
67+
68+extension Allow {
69+ init(data: Data) throws {
70+ self = try newJSONDecoder().decode(Allow.self, from: data)
71+ }
72+
73+ init(_ json: String, using encoding: String.Encoding = .utf8) throws {
74+ guard let data = json.data(using: encoding) else {
75+ throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
76+ }
77+ try self.init(data: data)
78+ }
79+
80+ init(fromURL url: URL) throws {
81+ try self.init(data: try Data(contentsOf: url))
82+ }
83+
84+ func with(
85+ labels: [String: String]? = nil
86+ ) -> Allow {
87+ return Allow(
88+ labels: labels ?? self.labels
89+ )
90+ }
91+
92+ func jsonData() throws -> Data {
93+ return try newJSONEncoder().encode(self)
94+ }
95+
96+ func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
97+ return String(data: try self.jsonData(), encoding: encoding)
98+ }
99+}
100+
101+// MARK: - Metadata
102+struct Metadata: Codable {
103+ /// Additional annotations for the generated resource
104+ let annotations: [String: String]
105+
106+ enum CodingKeys: String, CodingKey {
107+ case annotations = "annotations"
108+ }
109+}
110+
111+// MARK: Metadata convenience initializers and mutators
112+
113+extension Metadata {
114+ init(data: Data) throws {
115+ self = try newJSONDecoder().decode(Metadata.self, from: data)
116+ }
117+
118+ init(_ json: String, using encoding: String.Encoding = .utf8) throws {
119+ guard let data = json.data(using: encoding) else {
120+ throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
121+ }
122+ try self.init(data: data)
123+ }
124+
125+ init(fromURL url: URL) throws {
126+ try self.init(data: try Data(contentsOf: url))
127+ }
128+
129+ func with(
130+ annotations: [String: String]? = nil
131+ ) -> Metadata {
132+ return Metadata(
133+ annotations: annotations ?? self.annotations
134+ )
135+ }
136+
137+ func jsonData() throws -> Data {
138+ return try newJSONEncoder().encode(self)
139+ }
140+
141+ func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
142+ return String(data: try self.jsonData(), encoding: encoding)
143+ }
144+}
145+
146+// MARK: - Helper functions for creating encoders and decoders
147+
148+func newJSONDecoder() -> JSONDecoder {
149+ let decoder = JSONDecoder()
150+ decoder.dateDecodingStrategy = .custom({ (decoder) -> Date in
151+ let container = try decoder.singleValueContainer()
152+ let dateStr = try container.decode(String.self)
153+
154+ let formatter = DateFormatter()
155+ formatter.calendar = Calendar(identifier: .iso8601)
156+ formatter.locale = Locale(identifier: "en_US_POSIX")
157+ formatter.timeZone = TimeZone(secondsFromGMT: 0)
158+ formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
159+ if let date = formatter.date(from: dateStr) {
160+ return date
161+ }
162+ formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX"
163+ if let date = formatter.date(from: dateStr) {
164+ return date
165+ }
166+ throw DecodingError.typeMismatch(Date.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Could not decode date"))
167+ })
168+ return decoder
169+}
170+
171+func newJSONEncoder() -> JSONEncoder {
172+ let encoder = JSONEncoder()
173+ let formatter = DateFormatter()
174+ formatter.calendar = Calendar(identifier: .iso8601)
175+ formatter.locale = Locale(identifier: "en_US_POSIX")
176+ formatter.timeZone = TimeZone(secondsFromGMT: 0)
177+ formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX"
178+ encoder.dateEncodingStrategy = .formatted(formatter)
179+ return encoder
180+}
Aschema-typescript-zoddefault / TopLevel.ts+18 −0
@@ -0,0 +1,18 @@
1+import * as z from "zod";
2+
3+
4+export const AllowSchema = z.object({
5+ "labels": z.record(z.string(), z.string()),
6+});
7+export type Allow = z.infer<typeof AllowSchema>;
8+
9+export const MetadataSchema = z.object({
10+ "annotations": z.record(z.string(), z.string()),
11+});
12+export type Metadata = z.infer<typeof MetadataSchema>;
13+
14+export const TopLevelSchema = z.object({
15+ "allow": AllowSchema,
16+ "metadata": MetadataSchema,
17+});
18+export type TopLevel = z.infer<typeof TopLevelSchema>;
Aschema-typescriptdefault / TopLevel.ts+208 −0
@@ -0,0 +1,208 @@
1+// To parse this data:
2+//
3+// import { Convert, TopLevel } from "./TopLevel";
4+//
5+// const topLevel = Convert.toTopLevel(json);
6+//
7+// These functions will throw an error if the JSON doesn't
8+// match the expected interface, even if the JSON is valid.
9+
10+export interface TopLevel {
11+ allow: Allow;
12+ metadata: Metadata;
13+ [property: string]: unknown;
14+}
15+
16+export interface Allow {
17+ /**
18+ * The labels to apply to the policy
19+ */
20+ labels: { [key: string]: string };
21+ [property: string]: unknown;
22+}
23+
24+export interface Metadata {
25+ /**
26+ * Additional annotations for the generated resource
27+ */
28+ annotations: { [key: string]: string };
29+ [property: string]: unknown;
30+}
31+
32+// Converts JSON strings to/from your types
33+// and asserts the results of JSON.parse at runtime
34+export class Convert {
35+ public static toTopLevel(json: string): TopLevel {
36+ return cast(JSON.parse(json), r("TopLevel"));
37+ }
38+
39+ public static topLevelToJson(value: TopLevel): string {
40+ return JSON.stringify(uncast(value, r("TopLevel")), null, 2);
41+ }
42+}
43+
44+function invalidValue(typ: any, val: any, key: any, parent: any = ''): never {
45+ const prettyTyp = prettyTypeName(typ);
46+ const parentText = parent ? ` on ${parent}` : '';
47+ const keyText = key ? ` for key "${key}"` : '';
48+ throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`);
49+}
50+
51+function prettyTypeName(typ: any): string {
52+ if (Array.isArray(typ)) {
53+ if (typ.length === 2 && typ[0] === undefined) {
54+ return `an optional ${prettyTypeName(typ[1])}`;
55+ } else {
56+ return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`;
57+ }
58+ } else if (typeof typ === "object" && typ.literal !== undefined) {
59+ return typ.literal;
60+ } else {
61+ return typeof typ;
62+ }
63+}
64+
65+function jsonToJSProps(typ: any): any {
66+ if (typ.jsonToJS === undefined) {
67+ const map: any = {};
68+ typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ });
69+ typ.jsonToJS = map;
70+ }
71+ return typ.jsonToJS;
72+}
73+
74+function jsToJSONProps(typ: any): any {
75+ if (typ.jsToJSON === undefined) {
76+ const map: any = {};
77+ typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ });
78+ typ.jsToJSON = map;
79+ }
80+ return typ.jsToJSON;
81+}
82+
83+function transform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any {
84+ function transformPrimitive(typ: string, val: any): any {
85+ if (typeof typ === typeof val) return val;
86+ return invalidValue(typ, val, key, parent);
87+ }
88+
89+ function transformUnion(typs: any[], val: any): any {
90+ // val must validate against one typ in typs
91+ const l = typs.length;
92+ for (let i = 0; i < l; i++) {
93+ const typ = typs[i];
94+ try {
95+ return transform(val, typ, getProps);
96+ } catch (_) {}
97+ }
98+ return invalidValue(typs, val, key, parent);
99+ }
100+
101+ function transformEnum(cases: string[], val: any): any {
102+ if (cases.indexOf(val) !== -1) return val;
103+ return invalidValue(cases.map(a => { return l(a); }), val, key, parent);
104+ }
105+
106+ function transformArray(typ: any, val: any): any {
107+ // val must be an array with no invalid elements
108+ if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent);
109+ return val.map(el => transform(el, typ, getProps));
110+ }
111+
112+ function transformDate(val: any): any {
113+ if (val === null) {
114+ return null;
115+ }
116+ const d = new Date(val);
117+ if (isNaN(d.valueOf())) {
118+ return invalidValue(l("Date"), val, key, parent);
119+ }
120+ return d;
121+ }
122+
123+ function transformObject(props: { [k: string]: any }, additional: any, val: any): any {
124+ if (val === null || typeof val !== "object" || Array.isArray(val)) {
125+ return invalidValue(l(ref || "object"), val, key, parent);
126+ }
127+ const result: any = {};
128+ Object.getOwnPropertyNames(props).forEach(key => {
129+ const prop = props[key];
130+ const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined;
131+ result[prop.key] = transform(v, prop.typ, getProps, key, ref);
132+ });
133+ Object.getOwnPropertyNames(val).forEach(key => {
134+ if (!Object.prototype.hasOwnProperty.call(props, key)) {
135+ result[key] = transform(val[key], additional, getProps, key, ref);
136+ }
137+ });
138+ return result;
139+ }
140+
141+ if (typ === "any") return val;
142+ if (typ === null) {
143+ if (val === null) return val;
144+ return invalidValue(typ, val, key, parent);
145+ }
146+ if (typ === false) return invalidValue(typ, val, key, parent);
147+ let ref: any = undefined;
148+ while (typeof typ === "object" && typ.ref !== undefined) {
149+ ref = typ.ref;
150+ typ = typeMap[typ.ref];
151+ }
152+ if (Array.isArray(typ)) return transformEnum(typ, val);
153+ if (typeof typ === "object") {
154+ return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val)
155+ : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val)
156+ : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val)
157+ : invalidValue(typ, val, key, parent);
158+ }
159+ // Numbers can be parsed by Date but shouldn't be.
160+ if (typ === Date && typeof val !== "number") return transformDate(val);
161+ return transformPrimitive(typ, val);
162+}
163+
164+function cast<T>(val: any, typ: any): T {
165+ return transform(val, typ, jsonToJSProps);
166+}
167+
168+function uncast<T>(val: T, typ: any): any {
169+ return transform(val, typ, jsToJSONProps);
170+}
171+
172+function l(typ: any) {
173+ return { literal: typ };
174+}
175+
176+function a(typ: any) {
177+ return { arrayItems: typ };
178+}
179+
180+function u(...typs: any[]) {
181+ return { unionMembers: typs };
182+}
183+
184+function o(props: any[], additional: any) {
185+ return { props, additional };
186+}
187+
188+function m(additional: any) {
189+ const props: any[] = [];
190+ return { props, additional };
191+}
192+
193+function r(name: string) {
194+ return { ref: name };
195+}
196+
197+const typeMap: any = {
198+ "TopLevel": o([
199+ { json: "allow", js: "allow", typ: r("Allow") },
200+ { json: "metadata", js: "metadata", typ: r("Metadata") },
201+ ], "any"),
202+ "Allow": o([
203+ { json: "labels", js: "labels", typ: m("") },
204+ ], "any"),
205+ "Metadata": o([
206+ { json: "annotations", js: "annotations", typ: m("") },
207+ ], "any"),
208+};
Test case

test/inputs/schema/vega-lite.schema

1 generated file · +5 −5
Mschema-schemadefault / TopLevel.schema+5 −5
@@ -270,7 +270,7 @@
270270 "additionalProperties": {
271271 "$ref": "#/definitions/VGMarkConfig"
272272 },
273- "description": "An object hash that defines key-value mappings to determine default properties for marks with a given [style](mark.html#mark-def). The keys represent styles names; the value are valid [mark configuration objects](mark.html#config). "
273+ "description": "An object hash that defines key-value mappings to determine default properties for marks\nwith a given [style](mark.html#mark-def). The keys represent styles names; the value are\nvalid [mark configuration objects](mark.html#config)."
274274 },
275275 "text": {
276276 "$ref": "#/definitions/TextConfig",
@@ -2871,7 +2871,7 @@
28712871 "type": "null"
28722872 }
28732873 ],
2874- "description": "The sort order. One of `\"ascending\"` (default) or `\"descending\"`.\nSort order for a facet field.\nThis can be `\"ascending\"`, `\"descending\"`."
2874+ "description": "The sort order. One of `\"ascending\"` (default) or `\"descending\"`."
28752875 }
28762876 },
28772877 "required": [
@@ -2908,7 +2908,7 @@
29082908 "type": "null"
29092909 }
29102910 ],
2911- "description": "The sort order. One of `\"ascending\"` (default) or `\"descending\"`.\nSort order for a facet field.\nThis can be `\"ascending\"`, `\"descending\"`."
2911+ "description": "Sort order for a facet field.\nThis can be `\"ascending\"`, `\"descending\"`."
29122912 },
29132913 "timeUnit": {
29142914 "$ref": "#/definitions/TimeUnit",
@@ -3087,7 +3087,7 @@
30873087 "type": "null"
30883088 }
30893089 ],
3090- "description": "The sort order. One of `\"ascending\"` (default) or `\"descending\"`.\nSort order for a facet field.\nThis can be `\"ascending\"`, `\"descending\"`."
3090+ "description": "The sort order. One of `\"ascending\"` (default) or `\"descending\"`."
30913091 },
30923092 "timeUnit": {
30933093 "$ref": "#/definitions/TimeUnit",
@@ -3231,7 +3231,7 @@
32313231 "type": "null"
32323232 }
32333233 ],
3234- "description": "Type of stacking offset if the field should be stacked.\n`stack` is only applicable for `x` and `y` channels with continuous domains.\nFor example, `stack` of `y` can be used to customize stacking for a vertical bar chart.\n\n`stack` can be one of the following values:\n\n- `\"zero\"`: stacking with baseline offset at zero value of the scale (for creating typical stacked [bar](stack.html#bar) and [area](stack.html#area) chart).\n- `\"normalize\"` - stacking with normalized domain (for creating [normalized stacked bar and area charts](stack.html#normalized). <br/>\n- `\"center\"` - stacking with center baseline (for [streamgraph](stack.html#streamgraph)).\n- `null` - No-stacking. This will produce layered [bar](stack.html#layered-bar-chart) and area chart.\n\n__Default value:__ `zero` for plots with all of the following conditions are true:\n\n1. The mark is `bar` or `area`;\n2. The stacked measure channel (x or y) has a linear scale;\n3. At least one of non-position channels mapped to an unaggregated field that is different from x and y. Otherwise, `null` by default."
3234+ "description": "Type of stacking offset if the field should be stacked.\n`stack` is only applicable for `x` and `y` channels with continuous domains.\nFor example, `stack` of `y` can be used to customize stacking for a vertical bar chart.\n\n`stack` can be one of the following values:\n\n- `\"zero\"`: stacking with baseline offset at zero value of the scale (for creating\ntypical stacked [bar](stack.html#bar) and [area](stack.html#area) chart).\n- `\"normalize\"` - stacking with normalized domain (for creating [normalized stacked bar\nand area charts](stack.html#normalized). <br/>\n- `\"center\"` - stacking with center baseline (for [streamgraph](stack.html#streamgraph)).\n- `null` - No-stacking. This will produce layered [bar](stack.html#layered-bar-chart) and\narea chart.\n\n__Default value:__ `zero` for plots with all of the following conditions are true:\n\n1. The mark is `bar` or `area`;\n2. The stacked measure channel (x or y) has a linear scale;\n3. At least one of non-position channels mapped to an unaggregated field that is\ndifferent from x and y. Otherwise, `null` by default."
32353235 },
32363236 "timeUnit": {
32373237 "$ref": "#/definitions/TimeUnit",
No generated files match these filters.