quicktype 18.0.6 → 19.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (174) hide show
  1. package/README.md +1 -1
  2. package/dist/{cli/CompressedJSONFromStream.d.ts → CompressedJSONFromStream.d.ts} +1 -1
  3. package/dist/{cli/CompressedJSONFromStream.js → CompressedJSONFromStream.js} +2 -2
  4. package/dist/{cli/GraphQLIntrospection.d.ts → GraphQLIntrospection.d.ts} +0 -0
  5. package/dist/{cli/GraphQLIntrospection.js → GraphQLIntrospection.js} +1 -1
  6. package/dist/{cli/TypeSource.d.ts → TypeSource.d.ts} +2 -2
  7. package/dist/{cli/TypeSource.js → TypeSource.js} +0 -0
  8. package/dist/{cli/URLGrammar.d.ts → URLGrammar.d.ts} +0 -0
  9. package/dist/{cli/URLGrammar.js → URLGrammar.js} +1 -1
  10. package/dist/{cli/index.d.ts → index.d.ts} +1 -1
  11. package/dist/{cli/index.js → index.js} +4 -5
  12. package/package.json +61 -77
  13. package/dist/quicktype-core/Annotation.d.ts +0 -8
  14. package/dist/quicktype-core/Annotation.js +0 -16
  15. package/dist/quicktype-core/ConvenienceRenderer.d.ts +0 -138
  16. package/dist/quicktype-core/ConvenienceRenderer.js +0 -668
  17. package/dist/quicktype-core/DateTime.d.ts +0 -10
  18. package/dist/quicktype-core/DateTime.js +0 -57
  19. package/dist/quicktype-core/DeclarationIR.d.ts +0 -14
  20. package/dist/quicktype-core/DeclarationIR.js +0 -167
  21. package/dist/quicktype-core/EncodedMarkovChain.d.ts +0 -1
  22. package/dist/quicktype-core/EncodedMarkovChain.js +0 -4
  23. package/dist/quicktype-core/GatherNames.d.ts +0 -2
  24. package/dist/quicktype-core/GatherNames.js +0 -333
  25. package/dist/quicktype-core/Graph.d.ts +0 -12
  26. package/dist/quicktype-core/Graph.js +0 -220
  27. package/dist/quicktype-core/GraphRewriting.d.ts +0 -87
  28. package/dist/quicktype-core/GraphRewriting.js +0 -421
  29. package/dist/quicktype-core/MakeTransformations.d.ts +0 -4
  30. package/dist/quicktype-core/MakeTransformations.js +0 -193
  31. package/dist/quicktype-core/MarkovChain.d.ts +0 -15
  32. package/dist/quicktype-core/MarkovChain.js +0 -154
  33. package/dist/quicktype-core/Messages.d.ts +0 -294
  34. package/dist/quicktype-core/Messages.js +0 -105
  35. package/dist/quicktype-core/Naming.d.ts +0 -64
  36. package/dist/quicktype-core/Naming.js +0 -356
  37. package/dist/quicktype-core/Renderer.d.ts +0 -50
  38. package/dist/quicktype-core/Renderer.js +0 -274
  39. package/dist/quicktype-core/RendererOptions.d.ts +0 -71
  40. package/dist/quicktype-core/RendererOptions.js +0 -141
  41. package/dist/quicktype-core/Run.d.ts +0 -174
  42. package/dist/quicktype-core/Run.js +0 -393
  43. package/dist/quicktype-core/Source.d.ts +0 -65
  44. package/dist/quicktype-core/Source.js +0 -204
  45. package/dist/quicktype-core/TargetLanguage.d.ts +0 -34
  46. package/dist/quicktype-core/TargetLanguage.js +0 -66
  47. package/dist/quicktype-core/Transformers.d.ts +0 -209
  48. package/dist/quicktype-core/Transformers.js +0 -836
  49. package/dist/quicktype-core/Type.d.ts +0 -206
  50. package/dist/quicktype-core/Type.js +0 -716
  51. package/dist/quicktype-core/TypeBuilder.d.ts +0 -61
  52. package/dist/quicktype-core/TypeBuilder.js +0 -324
  53. package/dist/quicktype-core/TypeGraph.d.ts +0 -75
  54. package/dist/quicktype-core/TypeGraph.js +0 -420
  55. package/dist/quicktype-core/TypeUtils.d.ts +0 -33
  56. package/dist/quicktype-core/TypeUtils.js +0 -230
  57. package/dist/quicktype-core/UnifyClasses.d.ts +0 -16
  58. package/dist/quicktype-core/UnifyClasses.js +0 -159
  59. package/dist/quicktype-core/UnionBuilder.d.ts +0 -49
  60. package/dist/quicktype-core/UnionBuilder.js +0 -282
  61. package/dist/quicktype-core/attributes/AccessorNames.d.ts +0 -18
  62. package/dist/quicktype-core/attributes/AccessorNames.js +0 -182
  63. package/dist/quicktype-core/attributes/Constraints.d.ts +0 -38
  64. package/dist/quicktype-core/attributes/Constraints.js +0 -172
  65. package/dist/quicktype-core/attributes/Description.d.ts +0 -9
  66. package/dist/quicktype-core/attributes/Description.js +0 -97
  67. package/dist/quicktype-core/attributes/EnumValues.d.ts +0 -8
  68. package/dist/quicktype-core/attributes/EnumValues.js +0 -31
  69. package/dist/quicktype-core/attributes/StringTypes.d.ts +0 -28
  70. package/dist/quicktype-core/attributes/StringTypes.js +0 -189
  71. package/dist/quicktype-core/attributes/TypeAttributes.d.ts +0 -34
  72. package/dist/quicktype-core/attributes/TypeAttributes.js +0 -119
  73. package/dist/quicktype-core/attributes/TypeNames.d.ts +0 -46
  74. package/dist/quicktype-core/attributes/TypeNames.js +0 -274
  75. package/dist/quicktype-core/attributes/URIAttributes.d.ts +0 -8
  76. package/dist/quicktype-core/attributes/URIAttributes.js +0 -85
  77. package/dist/quicktype-core/index.d.ts +0 -48
  78. package/dist/quicktype-core/index.js +0 -180
  79. package/dist/quicktype-core/input/CompressedJSON.d.ts +0 -69
  80. package/dist/quicktype-core/input/CompressedJSON.js +0 -276
  81. package/dist/quicktype-core/input/FetchingJSONSchemaStore.d.ts +0 -6
  82. package/dist/quicktype-core/input/FetchingJSONSchemaStore.js +0 -18
  83. package/dist/quicktype-core/input/Inference.d.ts +0 -22
  84. package/dist/quicktype-core/input/Inference.js +0 -240
  85. package/dist/quicktype-core/input/Inputs.d.ts +0 -48
  86. package/dist/quicktype-core/input/Inputs.js +0 -145
  87. package/dist/quicktype-core/input/JSONSchemaInput.d.ts +0 -91
  88. package/dist/quicktype-core/input/JSONSchemaInput.js +0 -1041
  89. package/dist/quicktype-core/input/JSONSchemaStore.d.ts +0 -8
  90. package/dist/quicktype-core/input/JSONSchemaStore.js +0 -36
  91. package/dist/quicktype-core/input/PostmanCollection.d.ts +0 -5
  92. package/dist/quicktype-core/input/PostmanCollection.js +0 -60
  93. package/dist/quicktype-core/input/io/NodeIO.d.ts +0 -3
  94. package/dist/quicktype-core/input/io/NodeIO.js +0 -87
  95. package/dist/quicktype-core/input/io/get-stream/buffer-stream.d.ts +0 -2
  96. package/dist/quicktype-core/input/io/get-stream/buffer-stream.js +0 -45
  97. package/dist/quicktype-core/input/io/get-stream/index.d.ts +0 -9
  98. package/dist/quicktype-core/input/io/get-stream/index.js +0 -52
  99. package/dist/quicktype-core/language/All.d.ts +0 -3
  100. package/dist/quicktype-core/language/All.js +0 -57
  101. package/dist/quicktype-core/language/CPlusPlus.d.ts +0 -241
  102. package/dist/quicktype-core/language/CPlusPlus.js +0 -1847
  103. package/dist/quicktype-core/language/CSharp.d.ts +0 -201
  104. package/dist/quicktype-core/language/CSharp.js +0 -1850
  105. package/dist/quicktype-core/language/Crystal.d.ts +0 -37
  106. package/dist/quicktype-core/language/Crystal.js +0 -337
  107. package/dist/quicktype-core/language/Dart.d.ts +0 -66
  108. package/dist/quicktype-core/language/Dart.js +0 -576
  109. package/dist/quicktype-core/language/Elm.d.ts +0 -58
  110. package/dist/quicktype-core/language/Elm.js +0 -522
  111. package/dist/quicktype-core/language/Golang.d.ts +0 -51
  112. package/dist/quicktype-core/language/Golang.js +0 -460
  113. package/dist/quicktype-core/language/Haskell.d.ts +0 -56
  114. package/dist/quicktype-core/language/Haskell.js +0 -411
  115. package/dist/quicktype-core/language/JSONSchema.d.ts +0 -31
  116. package/dist/quicktype-core/language/JSONSchema.js +0 -169
  117. package/dist/quicktype-core/language/Java.d.ts +0 -125
  118. package/dist/quicktype-core/language/Java.js +0 -1081
  119. package/dist/quicktype-core/language/JavaScript.d.ts +0 -68
  120. package/dist/quicktype-core/language/JavaScript.js +0 -435
  121. package/dist/quicktype-core/language/JavaScriptPropTypes.d.ts +0 -40
  122. package/dist/quicktype-core/language/JavaScriptPropTypes.js +0 -213
  123. package/dist/quicktype-core/language/JavaScriptUnicodeMaps.d.ts +0 -2
  124. package/dist/quicktype-core/language/JavaScriptUnicodeMaps.js +0 -134
  125. package/dist/quicktype-core/language/Kotlin.d.ts +0 -109
  126. package/dist/quicktype-core/language/Kotlin.js +0 -832
  127. package/dist/quicktype-core/language/Objective-C.d.ts +0 -79
  128. package/dist/quicktype-core/language/Objective-C.js +0 -777
  129. package/dist/quicktype-core/language/Php.d.ts +0 -80
  130. package/dist/quicktype-core/language/Php.js +0 -702
  131. package/dist/quicktype-core/language/Pike.d.ts +0 -37
  132. package/dist/quicktype-core/language/Pike.js +0 -276
  133. package/dist/quicktype-core/language/Python.d.ts +0 -107
  134. package/dist/quicktype-core/language/Python.js +0 -969
  135. package/dist/quicktype-core/language/Rust.d.ts +0 -56
  136. package/dist/quicktype-core/language/Rust.js +0 -309
  137. package/dist/quicktype-core/language/Swift.d.ts +0 -96
  138. package/dist/quicktype-core/language/Swift.js +0 -1211
  139. package/dist/quicktype-core/language/TypeScriptFlow.d.ts +0 -77
  140. package/dist/quicktype-core/language/TypeScriptFlow.js +0 -286
  141. package/dist/quicktype-core/language/ruby/index.d.ts +0 -52
  142. package/dist/quicktype-core/language/ruby/index.js +0 -557
  143. package/dist/quicktype-core/language/ruby/keywords.d.ts +0 -3
  144. package/dist/quicktype-core/language/ruby/keywords.js +0 -358
  145. package/dist/quicktype-core/rewrites/CombineClasses.d.ts +0 -3
  146. package/dist/quicktype-core/rewrites/CombineClasses.js +0 -125
  147. package/dist/quicktype-core/rewrites/ExpandStrings.d.ts +0 -4
  148. package/dist/quicktype-core/rewrites/ExpandStrings.js +0 -143
  149. package/dist/quicktype-core/rewrites/FlattenStrings.d.ts +0 -3
  150. package/dist/quicktype-core/rewrites/FlattenStrings.js +0 -45
  151. package/dist/quicktype-core/rewrites/FlattenUnions.d.ts +0 -3
  152. package/dist/quicktype-core/rewrites/FlattenUnions.js +0 -47
  153. package/dist/quicktype-core/rewrites/InferMaps.d.ts +0 -3
  154. package/dist/quicktype-core/rewrites/InferMaps.js +0 -117
  155. package/dist/quicktype-core/rewrites/ReplaceObjectType.d.ts +0 -3
  156. package/dist/quicktype-core/rewrites/ReplaceObjectType.js +0 -60
  157. package/dist/quicktype-core/rewrites/ResolveIntersections.d.ts +0 -3
  158. package/dist/quicktype-core/rewrites/ResolveIntersections.js +0 -244
  159. package/dist/quicktype-core/support/Acronyms.d.ts +0 -10
  160. package/dist/quicktype-core/support/Acronyms.js +0 -1128
  161. package/dist/quicktype-core/support/Chance.d.ts +0 -38
  162. package/dist/quicktype-core/support/Chance.js +0 -2146
  163. package/dist/quicktype-core/support/Converters.d.ts +0 -6
  164. package/dist/quicktype-core/support/Converters.js +0 -16
  165. package/dist/quicktype-core/support/Strings.d.ts +0 -44
  166. package/dist/quicktype-core/support/Strings.js +0 -525
  167. package/dist/quicktype-core/support/Support.d.ts +0 -29
  168. package/dist/quicktype-core/support/Support.js +0 -162
  169. package/dist/quicktype-graphql-input/GraphQLSchema.d.ts +0 -645
  170. package/dist/quicktype-graphql-input/GraphQLSchema.js +0 -39
  171. package/dist/quicktype-graphql-input/index.d.ts +0 -17
  172. package/dist/quicktype-graphql-input/index.js +0 -407
  173. package/dist/quicktype-typescript-input/index.d.ts +0 -2
  174. package/dist/quicktype-typescript-input/index.js +0 -98
@@ -1,1041 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.JSONSchemaInput = exports.schemaTypeDict = exports.Ref = exports.PathElementKind = void 0;
7
- const urijs_1 = __importDefault(require("urijs"));
8
- const collection_utils_1 = require("collection-utils");
9
- const Type_1 = require("../Type");
10
- const Support_1 = require("../support/Support");
11
- const TypeNames_1 = require("../attributes/TypeNames");
12
- const TypeNames_2 = require("../attributes/TypeNames");
13
- const TypeAttributes_1 = require("../attributes/TypeAttributes");
14
- const JSONSchemaStore_1 = require("./JSONSchemaStore");
15
- const Messages_1 = require("../Messages");
16
- const StringTypes_1 = require("../attributes/StringTypes");
17
- const Description_1 = require("../attributes/Description");
18
- const AccessorNames_1 = require("../attributes/AccessorNames");
19
- const EnumValues_1 = require("../attributes/EnumValues");
20
- const Constraints_1 = require("../attributes/Constraints");
21
- const Constraints_2 = require("../attributes/Constraints");
22
- const Constraints_3 = require("../attributes/Constraints");
23
- const URIAttributes_1 = require("../attributes/URIAttributes");
24
- var PathElementKind;
25
- (function (PathElementKind) {
26
- PathElementKind[PathElementKind["Root"] = 0] = "Root";
27
- PathElementKind[PathElementKind["KeyOrIndex"] = 1] = "KeyOrIndex";
28
- PathElementKind[PathElementKind["Type"] = 2] = "Type";
29
- PathElementKind[PathElementKind["Object"] = 3] = "Object";
30
- })(PathElementKind = exports.PathElementKind || (exports.PathElementKind = {}));
31
- function keyOrIndex(pe) {
32
- if (pe.kind !== PathElementKind.KeyOrIndex)
33
- return undefined;
34
- return pe.key;
35
- }
36
- function pathElementEquals(a, b) {
37
- if (a.kind !== b.kind)
38
- return false;
39
- switch (a.kind) {
40
- case PathElementKind.Type:
41
- return a.index === b.index;
42
- case PathElementKind.KeyOrIndex:
43
- return a.key === b.key;
44
- default:
45
- return true;
46
- }
47
- }
48
- function withRef(refOrLoc, props) {
49
- const ref = typeof refOrLoc === "function" ? refOrLoc() : refOrLoc instanceof Ref ? refOrLoc : refOrLoc.canonicalRef;
50
- return Object.assign({ ref }, props === undefined ? {} : props);
51
- }
52
- function checkJSONSchemaObject(x, refOrLoc) {
53
- if (Array.isArray(x)) {
54
- return (0, Messages_1.messageError)("SchemaArrayIsInvalidSchema", withRef(refOrLoc));
55
- }
56
- if (x === null) {
57
- return (0, Messages_1.messageError)("SchemaNullIsInvalidSchema", withRef(refOrLoc));
58
- }
59
- if (typeof x !== "object") {
60
- return (0, Messages_1.messageError)("SchemaInvalidJSONSchemaType", withRef(refOrLoc, { type: typeof x }));
61
- }
62
- return x;
63
- }
64
- function checkJSONSchema(x, refOrLoc) {
65
- if (typeof x === "boolean")
66
- return x;
67
- return checkJSONSchemaObject(x, refOrLoc);
68
- }
69
- const numberRegexp = new RegExp("^[0-9]+$");
70
- function normalizeURI(uri) {
71
- // FIXME: This is overly complicated and a bit shady. The problem is
72
- // that `normalize` will URL-escape, with the result that if we want to
73
- // open the URL as a file, escaped character will thwart us. I think the
74
- // JSONSchemaStore should take a URI, not a string, and if it reads from
75
- // a file it can decode by itself.
76
- if (typeof uri === "string") {
77
- uri = new urijs_1.default(uri);
78
- }
79
- return new urijs_1.default(urijs_1.default.decode(uri.clone().normalize().toString()));
80
- }
81
- class Ref {
82
- path;
83
- static root(address) {
84
- const uri = (0, collection_utils_1.definedMap)(address, a => new urijs_1.default(a));
85
- return new Ref(uri, []);
86
- }
87
- static parsePath(path) {
88
- const elements = [];
89
- if (path.startsWith("/")) {
90
- elements.push({ kind: PathElementKind.Root });
91
- path = path.slice(1);
92
- }
93
- if (path !== "") {
94
- const parts = path.split("/");
95
- for (let i = 0; i < parts.length; i++) {
96
- elements.push({ kind: PathElementKind.KeyOrIndex, key: parts[i] });
97
- }
98
- }
99
- return elements;
100
- }
101
- static parseURI(uri, destroyURI = false) {
102
- if (!destroyURI) {
103
- uri = uri.clone();
104
- }
105
- let path = uri.fragment();
106
- uri.fragment("");
107
- if ((uri.host() !== "" || uri.filename() !== "") && path === "") {
108
- path = "/";
109
- }
110
- const elements = Ref.parsePath(path);
111
- return new Ref(uri, elements);
112
- }
113
- static parse(ref) {
114
- return Ref.parseURI(new urijs_1.default(ref), true);
115
- }
116
- addressURI;
117
- constructor(addressURI, path) {
118
- this.path = path;
119
- if (addressURI !== undefined) {
120
- (0, Support_1.assert)(addressURI.fragment() === "", `Ref URI with fragment is not allowed: ${addressURI.toString()}`);
121
- this.addressURI = normalizeURI(addressURI);
122
- }
123
- else {
124
- this.addressURI = undefined;
125
- }
126
- }
127
- get hasAddress() {
128
- return this.addressURI !== undefined;
129
- }
130
- get address() {
131
- return (0, Support_1.defined)(this.addressURI).toString();
132
- }
133
- get isRoot() {
134
- return this.path.length === 1 && this.path[0].kind === PathElementKind.Root;
135
- }
136
- pushElement(pe) {
137
- const newPath = Array.from(this.path);
138
- newPath.push(pe);
139
- return new Ref(this.addressURI, newPath);
140
- }
141
- push(...keys) {
142
- let ref = this;
143
- for (const key of keys) {
144
- ref = ref.pushElement({ kind: PathElementKind.KeyOrIndex, key });
145
- }
146
- return ref;
147
- }
148
- pushObject() {
149
- return this.pushElement({ kind: PathElementKind.Object });
150
- }
151
- pushType(index) {
152
- return this.pushElement({ kind: PathElementKind.Type, index });
153
- }
154
- resolveAgainst(base) {
155
- let addressURI = this.addressURI;
156
- if (base !== undefined && base.addressURI !== undefined) {
157
- addressURI = addressURI === undefined ? base.addressURI : addressURI.absoluteTo(base.addressURI);
158
- }
159
- return new Ref(addressURI, this.path);
160
- }
161
- get name() {
162
- const path = Array.from(this.path);
163
- for (;;) {
164
- const e = path.pop();
165
- if (e === undefined || e.kind === PathElementKind.Root) {
166
- let name = this.addressURI !== undefined ? this.addressURI.filename() : "";
167
- const suffix = this.addressURI !== undefined ? this.addressURI.suffix() : "";
168
- if (name.length > suffix.length + 1) {
169
- name = name.slice(0, name.length - suffix.length - 1);
170
- }
171
- if (name === "") {
172
- return "Something";
173
- }
174
- return name;
175
- }
176
- switch (e.kind) {
177
- case PathElementKind.KeyOrIndex:
178
- if (numberRegexp.test(e.key)) {
179
- return e.key;
180
- }
181
- break;
182
- case PathElementKind.Type:
183
- case PathElementKind.Object:
184
- return (0, Support_1.panic)("We shouldn't try to get the name of Type or Object refs");
185
- default:
186
- return (0, Support_1.assertNever)(e);
187
- }
188
- }
189
- }
190
- get definitionName() {
191
- const pe = (0, collection_utils_1.arrayGetFromEnd)(this.path, 2);
192
- if (pe === undefined)
193
- return undefined;
194
- if (keyOrIndex(pe) === "definitions")
195
- return keyOrIndex((0, Support_1.defined)((0, collection_utils_1.arrayLast)(this.path)));
196
- return undefined;
197
- }
198
- toString() {
199
- function elementToString(e) {
200
- switch (e.kind) {
201
- case PathElementKind.Root:
202
- return "";
203
- case PathElementKind.Type:
204
- return `type/${e.index.toString()}`;
205
- case PathElementKind.Object:
206
- return "object";
207
- case PathElementKind.KeyOrIndex:
208
- return e.key;
209
- default:
210
- return (0, Support_1.assertNever)(e);
211
- }
212
- }
213
- const address = this.addressURI === undefined ? "" : this.addressURI.toString();
214
- return address + "#" + this.path.map(elementToString).join("/");
215
- }
216
- lookup(local, path, root) {
217
- const refMaker = () => new Ref(this.addressURI, path);
218
- const first = path[0];
219
- if (first === undefined) {
220
- return checkJSONSchema(local, refMaker);
221
- }
222
- const rest = path.slice(1);
223
- switch (first.kind) {
224
- case PathElementKind.Root:
225
- return this.lookup(root, rest, root);
226
- case PathElementKind.KeyOrIndex:
227
- const key = first.key;
228
- if (Array.isArray(local)) {
229
- if (!/^\d+$/.test(key)) {
230
- return (0, Messages_1.messageError)("SchemaCannotIndexArrayWithNonNumber", withRef(refMaker, { actual: key }));
231
- }
232
- const index = parseInt(first.key, 10);
233
- if (index >= local.length) {
234
- return (0, Messages_1.messageError)("SchemaIndexNotInArray", withRef(refMaker, { index }));
235
- }
236
- return this.lookup(local[index], rest, root);
237
- }
238
- else {
239
- if (!(0, collection_utils_1.hasOwnProperty)(local, key)) {
240
- return (0, Messages_1.messageError)("SchemaKeyNotInObject", withRef(refMaker, { key }));
241
- }
242
- return this.lookup(checkJSONSchemaObject(local, refMaker)[first.key], rest, root);
243
- }
244
- case PathElementKind.Type:
245
- return (0, Support_1.panic)('Cannot look up path that indexes "type"');
246
- case PathElementKind.Object:
247
- return (0, Support_1.panic)('Cannot look up path that indexes "object"');
248
- default:
249
- return (0, Support_1.assertNever)(first);
250
- }
251
- }
252
- lookupRef(root) {
253
- return this.lookup(root, this.path, root);
254
- }
255
- equals(other) {
256
- if (!(other instanceof Ref))
257
- return false;
258
- if (this.addressURI !== undefined && other.addressURI !== undefined) {
259
- if (!this.addressURI.equals(other.addressURI))
260
- return false;
261
- }
262
- else {
263
- if ((this.addressURI === undefined) !== (other.addressURI === undefined))
264
- return false;
265
- }
266
- const l = this.path.length;
267
- if (l !== other.path.length)
268
- return false;
269
- for (let i = 0; i < l; i++) {
270
- if (!pathElementEquals(this.path[i], other.path[i]))
271
- return false;
272
- }
273
- return true;
274
- }
275
- hashCode() {
276
- let acc = (0, collection_utils_1.hashCodeOf)((0, collection_utils_1.definedMap)(this.addressURI, u => u.toString()));
277
- for (const pe of this.path) {
278
- acc = (0, collection_utils_1.addHashCode)(acc, pe.kind);
279
- switch (pe.kind) {
280
- case PathElementKind.Type:
281
- acc = (0, collection_utils_1.addHashCode)(acc, pe.index);
282
- break;
283
- case PathElementKind.KeyOrIndex:
284
- acc = (0, collection_utils_1.addHashCode)(acc, (0, collection_utils_1.hashString)(pe.key));
285
- break;
286
- default:
287
- break;
288
- }
289
- }
290
- return acc;
291
- }
292
- }
293
- exports.Ref = Ref;
294
- class Location {
295
- haveID;
296
- canonicalRef;
297
- virtualRef;
298
- constructor(canonicalRef, virtualRef, haveID = false) {
299
- this.haveID = haveID;
300
- this.canonicalRef = canonicalRef;
301
- this.virtualRef = virtualRef !== undefined ? virtualRef : canonicalRef;
302
- }
303
- updateWithID(id) {
304
- if (typeof id !== "string")
305
- return this;
306
- const parsed = Ref.parse(id);
307
- const virtual = this.haveID ? parsed.resolveAgainst(this.virtualRef) : parsed;
308
- if (!this.haveID) {
309
- (0, Messages_1.messageAssert)(virtual.hasAddress, "SchemaIDMustHaveAddress", withRef(this, { id }));
310
- }
311
- return new Location(this.canonicalRef, virtual, true);
312
- }
313
- push(...keys) {
314
- return new Location(this.canonicalRef.push(...keys), this.virtualRef.push(...keys), this.haveID);
315
- }
316
- pushObject() {
317
- return new Location(this.canonicalRef.pushObject(), this.virtualRef.pushObject(), this.haveID);
318
- }
319
- pushType(index) {
320
- return new Location(this.canonicalRef.pushType(index), this.virtualRef.pushType(index), this.haveID);
321
- }
322
- toString() {
323
- return `${this.virtualRef.toString()} (${this.canonicalRef.toString()})`;
324
- }
325
- }
326
- class Canonizer {
327
- _ctx;
328
- _map = new collection_utils_1.EqualityMap();
329
- _schemaAddressesAdded = new Set();
330
- constructor(_ctx) {
331
- this._ctx = _ctx;
332
- }
333
- addIDs(schema, loc) {
334
- if (schema === null)
335
- return;
336
- if (Array.isArray(schema)) {
337
- for (let i = 0; i < schema.length; i++) {
338
- this.addIDs(schema[i], loc.push(i.toString()));
339
- }
340
- return;
341
- }
342
- if (typeof schema !== "object") {
343
- return;
344
- }
345
- const locWithoutID = loc;
346
- const maybeID = schema["$id"];
347
- if (typeof maybeID === "string") {
348
- loc = loc.updateWithID(maybeID);
349
- }
350
- if (loc.haveID) {
351
- if (this._ctx.debugPrintSchemaResolving) {
352
- console.log(`adding mapping ${loc.toString()}`);
353
- }
354
- this._map.set(loc.virtualRef, locWithoutID);
355
- }
356
- for (const property of Object.getOwnPropertyNames(schema)) {
357
- this.addIDs(schema[property], loc.push(property));
358
- }
359
- }
360
- addSchema(schema, address) {
361
- if (this._schemaAddressesAdded.has(address))
362
- return false;
363
- this.addIDs(schema, new Location(Ref.root(address), Ref.root(undefined)));
364
- this._schemaAddressesAdded.add(address);
365
- return true;
366
- }
367
- // Returns: Canonical ref
368
- canonize(base, ref) {
369
- const virtual = ref.resolveAgainst(base.virtualRef);
370
- const loc = this._map.get(virtual);
371
- if (loc !== undefined) {
372
- return loc;
373
- }
374
- const canonicalRef = virtual.addressURI === undefined ? new Ref(base.canonicalRef.addressURI, virtual.path) : virtual;
375
- return new Location(canonicalRef, new Ref(undefined, virtual.path));
376
- }
377
- }
378
- function checkTypeList(typeOrTypes, loc) {
379
- let set;
380
- if (typeof typeOrTypes === "string") {
381
- set = new Set([typeOrTypes]);
382
- }
383
- else if (Array.isArray(typeOrTypes)) {
384
- const arr = [];
385
- for (const t of typeOrTypes) {
386
- if (typeof t !== "string") {
387
- return (0, Messages_1.messageError)("SchemaTypeElementMustBeString", withRef(loc, { element: t }));
388
- }
389
- arr.push(t);
390
- }
391
- set = new Set(arr);
392
- }
393
- else {
394
- return (0, Messages_1.messageError)("SchemaTypeMustBeStringOrStringArray", withRef(loc, { actual: typeOrTypes }));
395
- }
396
- (0, Messages_1.messageAssert)(set.size > 0, "SchemaNoTypeSpecified", withRef(loc));
397
- const validTypes = ["null", "boolean", "object", "array", "number", "string", "integer"];
398
- const maybeInvalid = (0, collection_utils_1.iterableFind)(set, s => validTypes.indexOf(s) < 0);
399
- if (maybeInvalid !== undefined) {
400
- return (0, Messages_1.messageError)("SchemaInvalidType", withRef(loc, { type: maybeInvalid }));
401
- }
402
- return set;
403
- }
404
- function checkRequiredArray(arr, loc) {
405
- if (!Array.isArray(arr)) {
406
- return (0, Messages_1.messageError)("SchemaRequiredMustBeStringOrStringArray", withRef(loc, { actual: arr }));
407
- }
408
- for (const e of arr) {
409
- if (typeof e !== "string") {
410
- return (0, Messages_1.messageError)("SchemaRequiredElementMustBeString", withRef(loc, { element: e }));
411
- }
412
- }
413
- return arr;
414
- }
415
- exports.schemaTypeDict = {
416
- null: true,
417
- boolean: true,
418
- string: true,
419
- integer: true,
420
- number: true,
421
- array: true,
422
- object: true
423
- };
424
- const schemaTypes = Object.getOwnPropertyNames(exports.schemaTypeDict);
425
- function typeKindForJSONSchemaFormat(format) {
426
- const target = (0, collection_utils_1.iterableFind)(Type_1.transformedStringTypeTargetTypeKindsMap, ([_, { jsonSchema }]) => jsonSchema === format);
427
- if (target === undefined)
428
- return undefined;
429
- return target[0];
430
- }
431
- function schemaFetchError(base, address) {
432
- if (base === undefined) {
433
- return (0, Messages_1.messageError)("SchemaFetchErrorTopLevel", { address });
434
- }
435
- else {
436
- return (0, Messages_1.messageError)("SchemaFetchError", { address, base: base.canonicalRef });
437
- }
438
- }
439
- class Resolver {
440
- _ctx;
441
- _store;
442
- _canonizer;
443
- constructor(_ctx, _store, _canonizer) {
444
- this._ctx = _ctx;
445
- this._store = _store;
446
- this._canonizer = _canonizer;
447
- }
448
- async tryResolveVirtualRef(fetchBase, lookupBase, virtualRef) {
449
- let didAdd = false;
450
- // If we are resolving into a schema file that we haven't seen yet then
451
- // we don't know its $id mapping yet, which means we don't know where we
452
- // will end up. What we do if we encounter a new schema is add all its
453
- // IDs first, and then try to canonize again.
454
- for (;;) {
455
- const loc = this._canonizer.canonize(fetchBase, virtualRef);
456
- const canonical = loc.canonicalRef;
457
- (0, Support_1.assert)(canonical.hasAddress, "Canonical ref can't be resolved without an address");
458
- const address = canonical.address;
459
- let schema = canonical.addressURI === undefined
460
- ? undefined
461
- : await this._store.get(address, this._ctx.debugPrintSchemaResolving);
462
- if (schema === undefined) {
463
- return [undefined, loc];
464
- }
465
- if (this._canonizer.addSchema(schema, address)) {
466
- (0, Support_1.assert)(!didAdd, "We can't add a schema twice");
467
- didAdd = true;
468
- }
469
- else {
470
- let lookupLoc = this._canonizer.canonize(lookupBase, virtualRef);
471
- if (fetchBase !== undefined) {
472
- lookupLoc = new Location(new Ref(loc.canonicalRef.addressURI, lookupLoc.canonicalRef.path), lookupLoc.virtualRef, lookupLoc.haveID);
473
- }
474
- return [lookupLoc.canonicalRef.lookupRef(schema), lookupLoc];
475
- }
476
- }
477
- }
478
- async resolveVirtualRef(base, virtualRef) {
479
- if (this._ctx.debugPrintSchemaResolving) {
480
- console.log(`resolving ${virtualRef.toString()} relative to ${base.toString()}`);
481
- }
482
- // Try with the virtual base first. If that doesn't work, use the
483
- // canonical ref's address with the virtual base's path.
484
- let result = await this.tryResolveVirtualRef(base, base, virtualRef);
485
- let schema = result[0];
486
- if (schema !== undefined) {
487
- if (this._ctx.debugPrintSchemaResolving) {
488
- console.log(`resolved to ${result[1].toString()}`);
489
- }
490
- return [schema, result[1]];
491
- }
492
- const altBase = new Location(base.canonicalRef, new Ref(base.canonicalRef.addressURI, base.virtualRef.path), base.haveID);
493
- result = await this.tryResolveVirtualRef(altBase, base, virtualRef);
494
- schema = result[0];
495
- if (schema !== undefined) {
496
- if (this._ctx.debugPrintSchemaResolving) {
497
- console.log(`resolved to ${result[1].toString()}`);
498
- }
499
- return [schema, result[1]];
500
- }
501
- return schemaFetchError(base, virtualRef.address);
502
- }
503
- async resolveTopLevelRef(ref) {
504
- return await this.resolveVirtualRef(new Location(new Ref(ref.addressURI, [])), new Ref(undefined, ref.path));
505
- }
506
- }
507
- async function addTypesInSchema(resolver, typeBuilder, references, attributeProducers) {
508
- let typeForCanonicalRef = new collection_utils_1.EqualityMap();
509
- function setTypeForLocation(loc, t) {
510
- const maybeRef = typeForCanonicalRef.get(loc.canonicalRef);
511
- if (maybeRef !== undefined) {
512
- (0, Support_1.assert)(maybeRef === t, "Trying to set path again to different type");
513
- }
514
- typeForCanonicalRef.set(loc.canonicalRef, t);
515
- }
516
- async function makeObject(loc, attributes, properties, requiredArray, additionalProperties, sortKey = (k) => k.toLowerCase()) {
517
- const required = new Set(requiredArray);
518
- const propertiesMap = (0, collection_utils_1.mapSortBy)((0, collection_utils_1.mapFromObject)(properties), (_, k) => sortKey(k));
519
- const props = await (0, collection_utils_1.mapMapSync)(propertiesMap, async (propSchema, propName) => {
520
- const propLoc = loc.push("properties", propName);
521
- const t = await toType(checkJSONSchema(propSchema, propLoc.canonicalRef), propLoc, (0, TypeNames_2.makeNamesTypeAttributes)(propName, true));
522
- const isOptional = !required.has(propName);
523
- return typeBuilder.makeClassProperty(t, isOptional);
524
- });
525
- let additionalPropertiesType;
526
- if (additionalProperties === undefined || additionalProperties === true) {
527
- additionalPropertiesType = typeBuilder.getPrimitiveType("any");
528
- }
529
- else if (additionalProperties === false) {
530
- additionalPropertiesType = undefined;
531
- }
532
- else {
533
- const additionalLoc = loc.push("additionalProperties");
534
- additionalPropertiesType = await toType(checkJSONSchema(additionalProperties, additionalLoc.canonicalRef), additionalLoc, (0, TypeNames_2.singularizeTypeNames)(attributes));
535
- }
536
- const additionalRequired = (0, collection_utils_1.setSubtract)(required, props.keys());
537
- if (additionalRequired.size > 0) {
538
- const t = additionalPropertiesType;
539
- if (t === undefined) {
540
- return (0, Messages_1.messageError)("SchemaAdditionalTypesForbidRequired", withRef(loc));
541
- }
542
- const additionalProps = (0, collection_utils_1.mapFromIterable)(additionalRequired, _name => typeBuilder.makeClassProperty(t, false));
543
- (0, collection_utils_1.mapMergeInto)(props, additionalProps);
544
- }
545
- return typeBuilder.getUniqueObjectType(attributes, props, additionalPropertiesType);
546
- }
547
- async function convertToType(schema, loc, typeAttributes) {
548
- const enumArray = Array.isArray(schema.enum) ? schema.enum : undefined;
549
- const typeSet = (0, collection_utils_1.definedMap)(schema.type, t => checkTypeList(t, loc));
550
- function isTypeIncluded(name) {
551
- if (typeSet !== undefined && !typeSet.has(name)) {
552
- return false;
553
- }
554
- if (enumArray !== undefined) {
555
- let predicate;
556
- switch (name) {
557
- case "null":
558
- predicate = (x) => x === null;
559
- break;
560
- case "integer":
561
- predicate = (x) => typeof x === "number" && x === Math.floor(x);
562
- break;
563
- default:
564
- predicate = (x) => typeof x === name;
565
- break;
566
- }
567
- return enumArray.find(predicate) !== undefined;
568
- }
569
- return true;
570
- }
571
- const includedTypes = (0, collection_utils_1.setFilter)(schemaTypes, isTypeIncluded);
572
- let producedAttributesForNoCases = undefined;
573
- function forEachProducedAttribute(cases, f) {
574
- let attributes;
575
- if (cases === undefined && producedAttributesForNoCases !== undefined) {
576
- attributes = producedAttributesForNoCases;
577
- }
578
- else {
579
- attributes = [];
580
- for (const producer of attributeProducers) {
581
- const newAttributes = producer(schema, loc.canonicalRef, includedTypes, cases);
582
- if (newAttributes === undefined)
583
- continue;
584
- attributes.push(newAttributes);
585
- }
586
- if (cases === undefined) {
587
- producedAttributesForNoCases = attributes;
588
- }
589
- }
590
- for (const a of attributes) {
591
- f(a);
592
- }
593
- }
594
- function combineProducedAttributes(f) {
595
- let result = TypeAttributes_1.emptyTypeAttributes;
596
- forEachProducedAttribute(undefined, attr => {
597
- const maybeAttributes = f(attr);
598
- if (maybeAttributes === undefined)
599
- return;
600
- result = (0, TypeAttributes_1.combineTypeAttributes)("union", result, maybeAttributes);
601
- });
602
- return result;
603
- }
604
- function makeAttributes(attributes) {
605
- if (schema.oneOf === undefined) {
606
- attributes = (0, TypeAttributes_1.combineTypeAttributes)("union", attributes, combineProducedAttributes(({ forType, forUnion, forCases }) => {
607
- (0, Support_1.assert)(forUnion === undefined && forCases === undefined, "We can't have attributes for unions and cases if we don't have a union");
608
- return forType;
609
- }));
610
- }
611
- return (0, TypeNames_2.modifyTypeNames)(attributes, maybeTypeNames => {
612
- const typeNames = (0, Support_1.defined)(maybeTypeNames);
613
- if (!typeNames.areInferred) {
614
- return typeNames;
615
- }
616
- let title = schema.title;
617
- if (typeof title !== "string") {
618
- title = loc.canonicalRef.definitionName;
619
- }
620
- if (typeof title === "string") {
621
- return TypeNames_1.TypeNames.make(new Set([title]), new Set(), schema.$ref !== undefined);
622
- }
623
- else {
624
- return typeNames.makeInferred();
625
- }
626
- });
627
- }
628
- typeAttributes = makeAttributes(typeAttributes);
629
- const inferredAttributes = (0, TypeAttributes_1.makeTypeAttributesInferred)(typeAttributes);
630
- function makeStringType(attributes) {
631
- const kind = typeKindForJSONSchemaFormat(schema.format);
632
- if (kind === undefined) {
633
- return typeBuilder.getStringType(attributes, StringTypes_1.StringTypes.unrestricted);
634
- }
635
- else {
636
- return typeBuilder.getPrimitiveType(kind, attributes);
637
- }
638
- }
639
- async function makeArrayType() {
640
- const singularAttributes = (0, TypeNames_2.singularizeTypeNames)(typeAttributes);
641
- const items = schema.items;
642
- let itemType;
643
- if (Array.isArray(items)) {
644
- const itemsLoc = loc.push("items");
645
- const itemTypes = await (0, collection_utils_1.arrayMapSync)(items, async (item, i) => {
646
- const itemLoc = itemsLoc.push(i.toString());
647
- return await toType(checkJSONSchema(item, itemLoc.canonicalRef), itemLoc, singularAttributes);
648
- });
649
- itemType = typeBuilder.getUnionType(TypeAttributes_1.emptyTypeAttributes, new Set(itemTypes));
650
- }
651
- else if (typeof items === "object") {
652
- const itemsLoc = loc.push("items");
653
- itemType = await toType(checkJSONSchema(items, itemsLoc.canonicalRef), itemsLoc, singularAttributes);
654
- }
655
- else if (items !== undefined) {
656
- return (0, Messages_1.messageError)("SchemaArrayItemsMustBeStringOrArray", withRef(loc, { actual: items }));
657
- }
658
- else {
659
- itemType = typeBuilder.getPrimitiveType("any");
660
- }
661
- typeBuilder.addAttributes(itemType, singularAttributes);
662
- return typeBuilder.getArrayType(TypeAttributes_1.emptyTypeAttributes, itemType);
663
- }
664
- async function makeObjectType() {
665
- let required;
666
- if (schema.required === undefined || typeof schema.required === "boolean") {
667
- required = [];
668
- }
669
- else {
670
- required = Array.from(checkRequiredArray(schema.required, loc));
671
- }
672
- let properties;
673
- if (schema.properties === undefined) {
674
- properties = {};
675
- }
676
- else {
677
- properties = checkJSONSchemaObject(schema.properties, loc.canonicalRef);
678
- }
679
- // In Schema Draft 3, `required` is `true` on a property that's required.
680
- for (const p of Object.getOwnPropertyNames(properties)) {
681
- if (properties[p].required === true && required.indexOf(p) < 0) {
682
- required.push(p);
683
- }
684
- }
685
- let additionalProperties = schema.additionalProperties;
686
- // This is an incorrect hack to fix an issue with a Go->Schema generator:
687
- // https://github.com/quicktype/quicktype/issues/976
688
- if (additionalProperties === undefined &&
689
- typeof schema.patternProperties === "object" &&
690
- (0, collection_utils_1.hasOwnProperty)(schema.patternProperties, ".*")) {
691
- additionalProperties = schema.patternProperties[".*"];
692
- }
693
- const objectAttributes = (0, TypeAttributes_1.combineTypeAttributes)("union", inferredAttributes, combineProducedAttributes(({ forObject }) => forObject));
694
- const order = schema.quicktypePropertyOrder ? schema.quicktypePropertyOrder : [];
695
- const orderKey = (propertyName) => {
696
- // use the index of the order array
697
- const index = order.indexOf(propertyName);
698
- // if no index then use the property name
699
- return index !== -1 ? index : propertyName.toLowerCase();
700
- };
701
- return await makeObject(loc, objectAttributes, properties, required, additionalProperties, orderKey);
702
- }
703
- async function makeTypesFromCases(cases, kind) {
704
- const kindLoc = loc.push(kind);
705
- if (!Array.isArray(cases)) {
706
- return (0, Messages_1.messageError)("SchemaSetOperationCasesIsNotArray", withRef(kindLoc, { operation: kind, cases }));
707
- }
708
- // FIXME: This cast shouldn't be necessary, but TypeScript forces our hand.
709
- return await (0, collection_utils_1.arrayMapSync)(cases, async (t, index) => {
710
- const caseLoc = kindLoc.push(index.toString());
711
- return await toType(checkJSONSchema(t, caseLoc.canonicalRef), caseLoc, (0, TypeAttributes_1.makeTypeAttributesInferred)(typeAttributes));
712
- });
713
- }
714
- const intersectionType = typeBuilder.getUniqueIntersectionType(typeAttributes, undefined);
715
- setTypeForLocation(loc, intersectionType);
716
- async function convertOneOrAnyOf(cases, kind) {
717
- const typeRefs = await makeTypesFromCases(cases, kind);
718
- let unionAttributes = (0, TypeAttributes_1.makeTypeAttributesInferred)(typeAttributes);
719
- if (kind === "oneOf") {
720
- forEachProducedAttribute(cases, ({ forType, forUnion, forCases }) => {
721
- if (forType !== undefined) {
722
- typeBuilder.addAttributes(intersectionType, forType);
723
- }
724
- if (forUnion !== undefined) {
725
- unionAttributes = (0, TypeAttributes_1.combineTypeAttributes)("union", unionAttributes, forUnion);
726
- }
727
- if (forCases !== undefined) {
728
- (0, Support_1.assert)(forCases.length === typeRefs.length, "Number of case attributes doesn't match number of cases");
729
- for (let i = 0; i < typeRefs.length; i++) {
730
- typeBuilder.addAttributes(typeRefs[i], forCases[i]);
731
- }
732
- }
733
- });
734
- }
735
- const unionType = typeBuilder.getUniqueUnionType(unionAttributes, undefined);
736
- typeBuilder.setSetOperationMembers(unionType, new Set(typeRefs));
737
- return unionType;
738
- }
739
- const includeObject = enumArray === undefined && (typeSet === undefined || typeSet.has("object"));
740
- const includeArray = enumArray === undefined && (typeSet === undefined || typeSet.has("array"));
741
- const needStringEnum = includedTypes.has("string") &&
742
- enumArray !== undefined &&
743
- enumArray.find((x) => typeof x === "string") !== undefined;
744
- const needUnion = typeSet !== undefined ||
745
- schema.properties !== undefined ||
746
- schema.additionalProperties !== undefined ||
747
- schema.items !== undefined ||
748
- schema.required !== undefined ||
749
- enumArray !== undefined;
750
- const types = [];
751
- if (needUnion) {
752
- const unionTypes = [];
753
- const numberAttributes = combineProducedAttributes(({ forNumber }) => forNumber);
754
- for (const [name, kind] of [
755
- ["null", "null"],
756
- ["number", "double"],
757
- ["integer", "integer"],
758
- ["boolean", "bool"]
759
- ]) {
760
- if (!includedTypes.has(name))
761
- continue;
762
- const attributes = (0, Type_1.isNumberTypeKind)(kind) ? numberAttributes : undefined;
763
- unionTypes.push(typeBuilder.getPrimitiveType(kind, attributes));
764
- }
765
- const stringAttributes = (0, TypeAttributes_1.combineTypeAttributes)("union", inferredAttributes, combineProducedAttributes(({ forString }) => forString));
766
- if (needStringEnum) {
767
- const cases = enumArray.filter(x => typeof x === "string");
768
- unionTypes.push(typeBuilder.getStringType(stringAttributes, StringTypes_1.StringTypes.fromCases(cases)));
769
- }
770
- else if (includedTypes.has("string")) {
771
- unionTypes.push(makeStringType(stringAttributes));
772
- }
773
- if (includeArray) {
774
- unionTypes.push(await makeArrayType());
775
- }
776
- if (includeObject) {
777
- unionTypes.push(await makeObjectType());
778
- }
779
- types.push(typeBuilder.getUniqueUnionType(inferredAttributes, new Set(unionTypes)));
780
- }
781
- if (schema.$ref !== undefined) {
782
- if (typeof schema.$ref !== "string") {
783
- return (0, Messages_1.messageError)("SchemaRefMustBeString", withRef(loc, { actual: typeof schema.$ref }));
784
- }
785
- const virtualRef = Ref.parse(schema.$ref);
786
- const [target, newLoc] = await resolver.resolveVirtualRef(loc, virtualRef);
787
- const attributes = (0, TypeNames_2.modifyTypeNames)(typeAttributes, tn => {
788
- if (!(0, Support_1.defined)(tn).areInferred)
789
- return tn;
790
- return TypeNames_1.TypeNames.make(new Set([newLoc.canonicalRef.name]), new Set(), true);
791
- });
792
- types.push(await toType(target, newLoc, attributes));
793
- }
794
- if (schema.allOf !== undefined) {
795
- types.push(...(await makeTypesFromCases(schema.allOf, "allOf")));
796
- }
797
- if (schema.oneOf !== undefined) {
798
- types.push(await convertOneOrAnyOf(schema.oneOf, "oneOf"));
799
- }
800
- if (schema.anyOf !== undefined) {
801
- types.push(await convertOneOrAnyOf(schema.anyOf, "anyOf"));
802
- }
803
- typeBuilder.setSetOperationMembers(intersectionType, new Set(types));
804
- return intersectionType;
805
- }
806
- async function toType(schema, loc, typeAttributes) {
807
- const maybeType = typeForCanonicalRef.get(loc.canonicalRef);
808
- if (maybeType !== undefined) {
809
- return maybeType;
810
- }
811
- let result;
812
- if (typeof schema === "boolean") {
813
- // FIXME: Empty union. We'd have to check that it's supported everywhere,
814
- // in particular in union flattening.
815
- (0, Messages_1.messageAssert)(schema === true, "SchemaFalseNotSupported", withRef(loc));
816
- result = typeBuilder.getPrimitiveType("any");
817
- }
818
- else {
819
- loc = loc.updateWithID(schema["$id"]);
820
- result = await convertToType(schema, loc, typeAttributes);
821
- }
822
- setTypeForLocation(loc, result);
823
- return result;
824
- }
825
- for (const [topLevelName, topLevelRef] of references) {
826
- const [target, loc] = await resolver.resolveTopLevelRef(topLevelRef);
827
- const t = await toType(target, loc, (0, TypeNames_2.makeNamesTypeAttributes)(topLevelName, false));
828
- typeBuilder.addTopLevel(topLevelName, t);
829
- }
830
- }
831
- function removeExtension(fn) {
832
- const lower = fn.toLowerCase();
833
- const extensions = [".json", ".schema"];
834
- for (const ext of extensions) {
835
- if (lower.endsWith(ext)) {
836
- const base = fn.slice(0, fn.length - ext.length);
837
- if (base.length > 0) {
838
- return base;
839
- }
840
- }
841
- }
842
- return fn;
843
- }
844
- function nameFromURI(uri) {
845
- const fragment = uri.fragment();
846
- if (fragment !== "") {
847
- const components = fragment.split("/");
848
- const len = components.length;
849
- if (components[len - 1] !== "") {
850
- return removeExtension(components[len - 1]);
851
- }
852
- if (len > 1 && components[len - 2] !== "") {
853
- return removeExtension(components[len - 2]);
854
- }
855
- }
856
- const filename = uri.filename();
857
- if (filename !== "") {
858
- return removeExtension(filename);
859
- }
860
- return (0, Messages_1.messageError)("DriverCannotInferNameForSchema", { uri: uri.toString() });
861
- }
862
- async function refsInSchemaForURI(resolver, uri, defaultName) {
863
- const fragment = uri.fragment();
864
- let propertiesAreTypes = fragment.endsWith("/");
865
- if (propertiesAreTypes) {
866
- uri = uri.clone().fragment(fragment.slice(0, -1));
867
- }
868
- const ref = Ref.parseURI(uri);
869
- if (ref.isRoot) {
870
- propertiesAreTypes = false;
871
- }
872
- const schema = (await resolver.resolveTopLevelRef(ref))[0];
873
- if (propertiesAreTypes) {
874
- if (typeof schema !== "object") {
875
- return (0, Messages_1.messageError)("SchemaCannotGetTypesFromBoolean", { ref: ref.toString() });
876
- }
877
- return (0, collection_utils_1.mapMap)((0, collection_utils_1.mapFromObject)(schema), (_, name) => ref.push(name));
878
- }
879
- else {
880
- let name;
881
- if (typeof schema === "object" && typeof schema.title === "string") {
882
- name = schema.title;
883
- }
884
- else {
885
- const maybeName = nameFromURI(uri);
886
- name = maybeName !== undefined ? maybeName : defaultName;
887
- }
888
- return [name, ref];
889
- }
890
- }
891
- class InputJSONSchemaStore extends JSONSchemaStore_1.JSONSchemaStore {
892
- _inputs;
893
- _delegate;
894
- constructor(_inputs, _delegate) {
895
- super();
896
- this._inputs = _inputs;
897
- this._delegate = _delegate;
898
- }
899
- async fetch(address) {
900
- const maybeInput = this._inputs.get(address);
901
- if (maybeInput !== undefined) {
902
- return checkJSONSchema((0, Support_1.parseJSON)(maybeInput, "JSON Schema", address), () => Ref.root(address));
903
- }
904
- if (this._delegate === undefined) {
905
- return (0, Support_1.panic)(`Schema URI ${address} requested, but no store given`);
906
- }
907
- return await this._delegate.fetch(address);
908
- }
909
- }
910
- class JSONSchemaInput {
911
- _schemaStore;
912
- _additionalSchemaAddresses;
913
- kind = "schema";
914
- needSchemaProcessing = true;
915
- _attributeProducers;
916
- _schemaInputs = new Map();
917
- _schemaSources = [];
918
- _topLevels = new Map();
919
- _needIR = false;
920
- constructor(_schemaStore, additionalAttributeProducers = [], _additionalSchemaAddresses = []) {
921
- this._schemaStore = _schemaStore;
922
- this._additionalSchemaAddresses = _additionalSchemaAddresses;
923
- this._attributeProducers = [
924
- Description_1.descriptionAttributeProducer,
925
- AccessorNames_1.accessorNamesAttributeProducer,
926
- EnumValues_1.enumValuesAttributeProducer,
927
- URIAttributes_1.uriSchemaAttributesProducer,
928
- Constraints_1.minMaxAttributeProducer,
929
- Constraints_2.minMaxLengthAttributeProducer,
930
- Constraints_3.patternAttributeProducer
931
- ].concat(additionalAttributeProducers);
932
- }
933
- get needIR() {
934
- return this._needIR;
935
- }
936
- addTopLevel(name, ref) {
937
- this._topLevels.set(name, ref);
938
- }
939
- async addTypes(ctx, typeBuilder) {
940
- if (this._schemaSources.length === 0)
941
- return;
942
- let maybeSchemaStore = this._schemaStore;
943
- if (this._schemaInputs.size === 0) {
944
- if (maybeSchemaStore === undefined) {
945
- return (0, Support_1.panic)("Must have a schema store to process JSON Schema");
946
- }
947
- }
948
- else {
949
- maybeSchemaStore = this._schemaStore = new InputJSONSchemaStore(this._schemaInputs, maybeSchemaStore);
950
- }
951
- const schemaStore = maybeSchemaStore;
952
- const canonizer = new Canonizer(ctx);
953
- for (const address of this._additionalSchemaAddresses) {
954
- const schema = await schemaStore.get(address, ctx.debugPrintSchemaResolving);
955
- if (schema === undefined) {
956
- return (0, Messages_1.messageError)("SchemaFetchErrorAdditional", { address });
957
- }
958
- canonizer.addSchema(schema, address);
959
- }
960
- const resolver = new Resolver(ctx, (0, Support_1.defined)(this._schemaStore), canonizer);
961
- for (const [normalizedURI, source] of this._schemaSources) {
962
- const givenName = source.name;
963
- const refs = await refsInSchemaForURI(resolver, normalizedURI, givenName);
964
- if (Array.isArray(refs)) {
965
- let name;
966
- if (this._schemaSources.length === 1) {
967
- name = givenName;
968
- }
969
- else {
970
- name = refs[0];
971
- }
972
- this.addTopLevel(name, refs[1]);
973
- }
974
- else {
975
- for (const [refName, ref] of refs) {
976
- this.addTopLevel(refName, ref);
977
- }
978
- }
979
- }
980
- await addTypesInSchema(resolver, typeBuilder, this._topLevels, this._attributeProducers);
981
- }
982
- addTypesSync() {
983
- return (0, Support_1.panic)("addTypesSync not supported in JSONSchemaInput");
984
- }
985
- async addSource(schemaSource) {
986
- return this.addSourceSync(schemaSource);
987
- }
988
- addSourceSync(schemaSource) {
989
- const { name, uris, schema, isConverted } = schemaSource;
990
- if (isConverted !== true) {
991
- this._needIR = true;
992
- }
993
- let normalizedURIs;
994
- if (uris === undefined) {
995
- normalizedURIs = [new urijs_1.default(name)];
996
- }
997
- else {
998
- normalizedURIs = uris.map(uri => {
999
- const normalizedURI = normalizeURI(uri);
1000
- if (normalizedURI.clone().hash("").toString() === "") {
1001
- normalizedURI.path(name);
1002
- }
1003
- return normalizedURI;
1004
- });
1005
- }
1006
- if (schema === undefined) {
1007
- (0, Support_1.assert)(uris !== undefined, "URIs must be given if schema source is not specified");
1008
- }
1009
- else {
1010
- for (let i = 0; i < normalizedURIs.length; i++) {
1011
- const normalizedURI = normalizedURIs[i];
1012
- const uri = normalizedURI.clone().hash("");
1013
- const path = uri.path();
1014
- let suffix = 0;
1015
- do {
1016
- if (suffix > 0) {
1017
- uri.path(`${path}-${suffix}`);
1018
- }
1019
- suffix++;
1020
- } while (this._schemaInputs.has(uri.toString()));
1021
- this._schemaInputs.set(uri.toString(), schema);
1022
- normalizedURIs[i] = uri.hash(normalizedURI.hash());
1023
- }
1024
- }
1025
- // FIXME: Why do we need both _schemaSources and _schemaInputs?
1026
- for (const normalizedURI of normalizedURIs) {
1027
- this._schemaSources.push([normalizedURI, schemaSource]);
1028
- }
1029
- }
1030
- singleStringSchemaSource() {
1031
- if (!this._schemaSources.every(([_, { schema }]) => typeof schema === "string")) {
1032
- return undefined;
1033
- }
1034
- const set = new Set(this._schemaSources.map(([_, { schema }]) => schema));
1035
- if (set.size === 1) {
1036
- return (0, Support_1.defined)((0, collection_utils_1.iterableFirst)(set));
1037
- }
1038
- return undefined;
1039
- }
1040
- }
1041
- exports.JSONSchemaInput = JSONSchemaInput;