quicktype 15.0.261 → 16.0.0

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.
package/README.md CHANGED
@@ -1,40 +1,35 @@
1
1
  ![](https://raw.githubusercontent.com/quicktype/quicktype/master/quicktype-logo.svg?sanitize=true)
2
2
 
3
3
  [![npm version](https://badge.fury.io/js/quicktype.svg)](https://badge.fury.io/js/quicktype)
4
- [![Build status](https://badge.buildkite.com/147309f9f492c2af1ea53df922be7140ba4035dbb31f61ee1e.svg)](https://buildkite.com/typeguard/quicktype-master)
5
- [![Join us in Slack](http://slack.quicktype.io/badge.svg)](http://slack.quicktype.io/)
4
+ ![Build status](https://github.com/quicktype/quicktype/actions/workflows/master.yaml/badge.svg)
6
5
 
7
6
  `quicktype` generates strongly-typed models and serializers from JSON, JSON Schema, TypeScript, and [GraphQL queries](https://blog.quicktype.io/graphql-with-quicktype/), making it a breeze to work with JSON type-safely in many programming languages.
8
7
 
9
- - [Try `quicktype` in your browser](https://app.quicktype.io).
10
- - Read ['A first look at quicktype'](http://blog.quicktype.io/first-look/) for more introduction.
11
- - If you have any questions, check out the [FAQ](FAQ.md) first.
8
+ - [Try `quicktype` in your browser](https://app.quicktype.io).
9
+ - Read ['A first look at quicktype'](http://blog.quicktype.io/first-look/) for more introduction.
10
+ - If you have any questions, check out the [FAQ](FAQ.md) first.
12
11
 
13
12
  ### Supported Inputs
14
13
 
15
14
  | JSON | JSON API URLs | [JSON Schema](https://app.quicktype.io/#s=coordinate) |
16
15
  | ---- | ------------- | ----------------------------------------------------- |
17
16
 
18
-
19
17
  | TypeScript | GraphQL queries |
20
18
  | ---------- | --------------- |
21
19
 
22
-
23
20
  ### Target Languages
24
21
 
25
- | [Ruby](https://app.quicktype.io/#l=ruby) | [JavaScript](https://app.quicktype.io/#l=js) | [Flow](https://app.quicktype.io/#l=flow) | [Rust](https://app.quicktype.io/#l=rust) | [Kotlin](https://app.quicktype.io/#l=kotlin) |
22
+ | [Ruby](https://app.quicktype.io/#l=ruby) | [JavaScript](https://app.quicktype.io/#l=js) | [Flow](https://app.quicktype.io/#l=flow) | [Rust](https://app.quicktype.io/#l=rust) | [Kotlin](https://app.quicktype.io/#l=kotlin) |
26
23
  | ---------------------------------------- | -------------------------------------------- | ---------------------------------------- | ---------------------------------------- | -------------------------------------------- |
27
24
 
28
-
29
- | [Dart](https://app.quicktype.io/#l=dart) | [Python](https://app.quicktype.io/#l=python) | [C#](https://app.quicktype.io/#l=cs) | [Go](https://app.quicktype.io/#l=go) | [C++](https://app.quicktype.io/#l=cpp) |
30
- | -------------------------------------------- | ------------------------------------ | ------------------------------------ | -------------------------------------- | ---------------------------------------- |
31
-
25
+ | [Dart](https://app.quicktype.io/#l=dart) | [Python](https://app.quicktype.io/#l=python) | [C#](https://app.quicktype.io/#l=cs) | [Go](https://app.quicktype.io/#l=go) | [C++](https://app.quicktype.io/#l=cpp) |
26
+ | ---------------------------------------- | -------------------------------------------- | ------------------------------------ | ------------------------------------ | -------------------------------------- |
32
27
 
33
28
  | [Java](https://app.quicktype.io/#l=java) | [TypeScript](https://app.quicktype.io/#l=ts) | [Swift](https://app.quicktype.io/#l=swift) | [Objective-C](https://app.quicktype.io/#l=objc) | [Elm](https://app.quicktype.io/#l=elm) |
34
- | ------------------------------------------ | ----------------------------------------------- | -------------------------------------- | ------------------------------------------------- | ---------------------------------------- |
29
+ | ---------------------------------------- | -------------------------------------------- | ------------------------------------------ | ----------------------------------------------- | -------------------------------------- |
35
30
 
36
- | [JSON Schema](https://app.quicktype.io/#l=schema) | [Pike](https://app.quicktype.io/#l=pike) | [Prop-Types](https://app.quicktype.io/#l=javascript-prop-types) | [Haskell](https://app.quicktype.io/#l=haskell) | |
37
- | ------------------------------------------ | ----------------------------------------------- | -------------------------------------- | ------------------------------------------------- | ---------------------------------------- |
31
+ | [JSON Schema](https://app.quicktype.io/#l=schema) | [Pike](https://app.quicktype.io/#l=pike) | [Prop-Types](https://app.quicktype.io/#l=javascript-prop-types) | [Haskell](https://app.quicktype.io/#l=haskell) | |
32
+ | ------------------------------------------------- | ---------------------------------------- | --------------------------------------------------------------- | ---------------------------------------------- | --- |
38
33
 
39
34
  _Missing your favorite language? Please implement it!_
40
35
 
@@ -50,10 +45,10 @@ npm install -g quicktype
50
45
 
51
46
  Other options:
52
47
 
53
- - [Homebrew](http://formulae.brew.sh/formula/quicktype) _(infrequently updated)_
54
- - [Xcode extension](https://itunes.apple.com/us/app/paste-json-as-code-quicktype/id1330801220?mt=12)\*
55
- - [VSCode extension](https://marketplace.visualstudio.com/items/quicktype.quicktype)\*
56
- - [Visual Studio extension](https://marketplace.visualstudio.com/items?itemName=typeguard.quicktype-vs)\*
48
+ - [Homebrew](http://formulae.brew.sh/formula/quicktype) _(infrequently updated)_
49
+ - [Xcode extension](https://itunes.apple.com/us/app/paste-json-as-code-quicktype/id1330801220?mt=12)\*
50
+ - [VSCode extension](https://marketplace.visualstudio.com/items/quicktype.quicktype)\*
51
+ - [Visual Studio extension](https://marketplace.visualstudio.com/items?itemName=typeguard.quicktype-vs)\*
57
52
 
58
53
  <small>\* limited functionality</small>
59
54
 
@@ -117,9 +112,9 @@ You can achieve a similar result by writing or generating a [TypeScript](http://
117
112
 
118
113
  ```typescript
119
114
  interface Person {
120
- name: string;
121
- nickname?: string; // an optional property
122
- luckyNumber: number;
115
+ name: string;
116
+ nickname?: string; // an optional property
117
+ luckyNumber: number;
123
118
  }
124
119
  ```
125
120
 
@@ -144,63 +139,55 @@ In general, first you create an `InputData` value with one or more JSON samples,
144
139
 
145
140
  ```javascript
146
141
  const {
147
- quicktype,
148
- InputData,
149
- jsonInputForTargetLanguage,
150
- JSONSchemaInput,
151
- FetchingJSONSchemaStore,
142
+ quicktype,
143
+ InputData,
144
+ jsonInputForTargetLanguage,
145
+ JSONSchemaInput,
146
+ FetchingJSONSchemaStore
152
147
  } = require("quicktype-core");
153
148
 
154
149
  async function quicktypeJSON(targetLanguage, typeName, jsonString) {
155
- const jsonInput = jsonInputForTargetLanguage(targetLanguage);
156
-
157
- // We could add multiple samples for the same desired
158
- // type, or many sources for other types. Here we're
159
- // just making one type from one piece of sample JSON.
160
- await jsonInput.addSource({
161
- name: typeName,
162
- samples: [jsonString],
163
- });
164
-
165
- const inputData = new InputData();
166
- inputData.addInput(jsonInput);
167
-
168
- return await quicktype({
169
- inputData,
170
- lang: targetLanguage,
171
- });
150
+ const jsonInput = jsonInputForTargetLanguage(targetLanguage);
151
+
152
+ // We could add multiple samples for the same desired
153
+ // type, or many sources for other types. Here we're
154
+ // just making one type from one piece of sample JSON.
155
+ await jsonInput.addSource({
156
+ name: typeName,
157
+ samples: [jsonString]
158
+ });
159
+
160
+ const inputData = new InputData();
161
+ inputData.addInput(jsonInput);
162
+
163
+ return await quicktype({
164
+ inputData,
165
+ lang: targetLanguage
166
+ });
172
167
  }
173
168
 
174
169
  async function quicktypeJSONSchema(targetLanguage, typeName, jsonSchemaString) {
175
- const schemaInput = new JSONSchemaInput(new FetchingJSONSchemaStore());
170
+ const schemaInput = new JSONSchemaInput(new FetchingJSONSchemaStore());
176
171
 
177
- // We could add multiple schemas for multiple types,
178
- // but here we're just making one type from JSON schema.
179
- await schemaInput.addSource({ name: typeName, schema: jsonSchemaString });
172
+ // We could add multiple schemas for multiple types,
173
+ // but here we're just making one type from JSON schema.
174
+ await schemaInput.addSource({ name: typeName, schema: jsonSchemaString });
180
175
 
181
- const inputData = new InputData();
182
- inputData.addInput(schemaInput);
176
+ const inputData = new InputData();
177
+ inputData.addInput(schemaInput);
183
178
 
184
- return await quicktype({
185
- inputData,
186
- lang: targetLanguage,
187
- });
179
+ return await quicktype({
180
+ inputData,
181
+ lang: targetLanguage
182
+ });
188
183
  }
189
184
 
190
185
  async function main() {
191
- const { lines: swiftPerson } = await quicktypeJSON(
192
- "swift",
193
- "Person",
194
- jsonString
195
- );
196
- console.log(swiftPerson.join("\n"));
197
-
198
- const { lines: pythonPerson } = await quicktypeJSONSchema(
199
- "python",
200
- "Person",
201
- jsonSchemaString
202
- );
203
- console.log(pythonPerson.join("\n"));
186
+ const { lines: swiftPerson } = await quicktypeJSON("swift", "Person", jsonString);
187
+ console.log(swiftPerson.join("\n"));
188
+
189
+ const { lines: pythonPerson } = await quicktypeJSONSchema("python", "Person", jsonSchemaString);
190
+ console.log(pythonPerson.join("\n"));
204
191
  }
205
192
 
206
193
  main();
@@ -223,6 +210,7 @@ Clone this repo and do:
223
210
  #### macOS / Linux
224
211
 
225
212
  ```bash
213
+ nvm use
226
214
  npm install
227
215
  script/quicktype # rebuild (slow) and run (fast)
228
216
  ```
@@ -264,18 +252,18 @@ files, URLs, or add other options.
264
252
 
265
253
  `quicktype` has many complex test dependencies:
266
254
 
267
- - `crystal` compiler
268
- - `dotnetcore` SDK
269
- - Java, Maven
270
- - `elm` tools
271
- - `g++` C++ compiler
272
- - `golang` stack
273
- - `swift` compiler
274
- - `clang` and Objective-C Foundation (must be tested separately on macOS)
275
- - `rust` tools
276
- - `pike` interpreter
277
- - [Bundler](https://bundler.io) for Ruby
278
- - `haskell` [stack](https://docs.haskellstack.org/)
255
+ - `crystal` compiler
256
+ - `dotnetcore` SDK
257
+ - Java, Maven
258
+ - `elm` tools
259
+ - `g++` C++ compiler
260
+ - `golang` stack
261
+ - `swift` compiler
262
+ - `clang` and Objective-C Foundation (must be tested separately on macOS)
263
+ - `rust` tools
264
+ - `pike` interpreter
265
+ - [Bundler](https://bundler.io) for Ruby
266
+ - `haskell` [stack](https://docs.haskellstack.org/)
279
267
 
280
268
  We've assembled all of these tools in a Docker container that you build and test within:
281
269
 
package/dist/cli/index.js CHANGED
@@ -34,7 +34,7 @@ function sourceFromFileOrUrlArray(name, filesOrUrls, httpHeaders) {
34
34
  }
35
35
  function typeNameFromFilename(filename) {
36
36
  const name = path.basename(filename);
37
- return name.substr(0, name.lastIndexOf("."));
37
+ return name.substring(0, name.lastIndexOf("."));
38
38
  }
39
39
  function samplesFromDirectory(dataDir, httpHeaders) {
40
40
  return __awaiter(this, void 0, void 0, function* () {
@@ -149,7 +149,7 @@ function inferLang(options, defaultLanguage) {
149
149
  if (extension === "") {
150
150
  return quicktype_core_1.messageError("DriverNoLanguageOrExtension", {});
151
151
  }
152
- return extension.substr(1);
152
+ return extension.slice(1);
153
153
  }
154
154
  return defaultLanguage;
155
155
  }
@@ -232,7 +232,7 @@ function makeLangTypeLabel(targetLanguages) {
232
232
  function negatedInferenceFlagName(name) {
233
233
  const prefix = "infer";
234
234
  if (name.startsWith(prefix)) {
235
- name = name.substr(prefix.length);
235
+ name = name.slice(prefix.length);
236
236
  }
237
237
  return "no" + quicktype_core_1.capitalize(name);
238
238
  }
@@ -61,7 +61,7 @@ function train(lines, depth) {
61
61
  const trie = makeTrie();
62
62
  for (const l of lines) {
63
63
  for (let i = depth; i <= l.length; i++) {
64
- increment(trie, l.substr(i - depth, depth), 0);
64
+ increment(trie, l.slice(i - depth, i), 0);
65
65
  }
66
66
  }
67
67
  return { trie, depth };
@@ -79,7 +79,7 @@ function evaluateFull(mc, word) {
79
79
  let p = 1;
80
80
  const scores = [];
81
81
  for (let i = depth; i <= word.length; i++) {
82
- let cp = lookup(trie, word.substr(i - depth, depth), 0);
82
+ let cp = lookup(trie, word.slice(i - depth, i), 0);
83
83
  if (typeof cp === "object") {
84
84
  return Support_1.panic("Did we mess up the depth?");
85
85
  }
@@ -27,7 +27,7 @@ class DescriptionTypeAttributeKind extends TypeAttributes_1.TypeAttributeKind {
27
27
  if (result === undefined)
28
28
  return undefined;
29
29
  if (result.length > 5 + 3) {
30
- result = `${result.substr(0, 5)}...`;
30
+ result = `${result.slice(0, 5)}...`;
31
31
  }
32
32
  if (descriptions.size > 1) {
33
33
  result = `${result}, ...`;
@@ -60,8 +60,8 @@ function combineNames(names) {
60
60
  }
61
61
  }
62
62
  }
63
- const prefix = prefixLength > 2 ? first.substr(0, prefixLength) : "";
64
- const suffix = suffixLength > 2 ? first.substr(first.length - suffixLength) : "";
63
+ const prefix = prefixLength > 2 ? first.slice(0, prefixLength) : "";
64
+ const suffix = suffixLength > 2 ? first.slice(first.length - suffixLength) : "";
65
65
  const combined = prefix + suffix;
66
66
  if (combined.length > 2) {
67
67
  return combined;
@@ -4,7 +4,7 @@ export { Input, InputData, JSONInput, JSONSourceData, jsonInputForTargetLanguage
4
4
  export { JSONSchemaInput, JSONSchemaSourceData } from "./input/JSONSchemaInput";
5
5
  export { Ref, JSONSchemaType, JSONSchemaAttributes } from "./input/JSONSchemaInput";
6
6
  export { RenderContext } from "./Renderer";
7
- export { Option, OptionDefinition, getOptionValues } from "./RendererOptions";
7
+ export { Option, OptionDefinition, getOptionValues, OptionValues } from "./RendererOptions";
8
8
  export { TargetLanguage, MultiFileRenderResult } from "./TargetLanguage";
9
9
  export { all as defaultTargetLanguages, languageNamed } from "./language/All";
10
10
  export { MultiWord, Sourcelike, SerializedRenderResult, Annotation, modifySource, singleWord, parenIfNeeded } from "./Source";
@@ -104,7 +104,7 @@ class Ref {
104
104
  const elements = [];
105
105
  if (path.startsWith("/")) {
106
106
  elements.push({ kind: PathElementKind.Root });
107
- path = path.substr(1);
107
+ path = path.slice(1);
108
108
  }
109
109
  if (path !== "") {
110
110
  const parts = path.split("/");
@@ -171,7 +171,7 @@ class Ref {
171
171
  let name = this.addressURI !== undefined ? this.addressURI.filename() : "";
172
172
  const suffix = this.addressURI !== undefined ? this.addressURI.suffix() : "";
173
173
  if (name.length > suffix.length + 1) {
174
- name = name.substr(0, name.length - suffix.length - 1);
174
+ name = name.slice(0, name.length - suffix.length - 1);
175
175
  }
176
176
  if (name === "") {
177
177
  return "Something";
@@ -853,7 +853,7 @@ function removeExtension(fn) {
853
853
  const extensions = [".json", ".schema"];
854
854
  for (const ext of extensions) {
855
855
  if (lower.endsWith(ext)) {
856
- const base = fn.substr(0, fn.length - ext.length);
856
+ const base = fn.slice(0, fn.length - ext.length);
857
857
  if (base.length > 0) {
858
858
  return base;
859
859
  }
@@ -884,7 +884,7 @@ function refsInSchemaForURI(resolver, uri, defaultName) {
884
884
  const fragment = uri.fragment();
885
885
  let propertiesAreTypes = fragment.endsWith("/");
886
886
  if (propertiesAreTypes) {
887
- uri = uri.clone().fragment(fragment.substr(0, fragment.length - 1));
887
+ uri = uri.clone().fragment(fragment.slice(0, -1));
888
888
  }
889
889
  const ref = Ref.parseURI(uri);
890
890
  if (ref.isRoot) {
@@ -35,19 +35,22 @@ function parseHeaders(httpHeaders) {
35
35
  function readableFromFileOrURL(fileOrURL, httpHeaders) {
36
36
  return __awaiter(this, void 0, void 0, function* () {
37
37
  try {
38
- if (browser_or_node_1.isNode && fileOrURL === "-") {
39
- // Cast node readable to isomorphic readable from readable-stream
40
- return process.stdin;
41
- }
42
- else if (isURL(fileOrURL)) {
38
+ if (isURL(fileOrURL)) {
43
39
  const response = yield fetch(fileOrURL, {
44
40
  headers: parseHeaders(httpHeaders)
45
41
  });
46
42
  return response.body;
47
43
  }
48
- else if (browser_or_node_1.isNode && fs.existsSync(fileOrURL)) {
49
- // Cast node readable to isomorphic readable from readable-stream
50
- return fs.createReadStream(fileOrURL, "utf8");
44
+ else if (browser_or_node_1.isNode) {
45
+ if (fileOrURL === "-") {
46
+ // Cast node readable to isomorphic readable from readable-stream
47
+ return process.stdin;
48
+ }
49
+ const filePath = fs.lstatSync(fileOrURL).isSymbolicLink() ? fs.readlinkSync(fileOrURL) : fileOrURL;
50
+ if (fs.existsSync(filePath)) {
51
+ // Cast node readable to isomorphic readable from readable-stream
52
+ return fs.createReadStream(filePath, "utf8");
53
+ }
51
54
  }
52
55
  }
53
56
  catch (e) {
@@ -438,13 +438,13 @@ class CPlusPlusRenderer extends ConvenienceRenderer_1.ConvenienceRenderer {
438
438
  name: MemberNames.MinValue,
439
439
  getter: MemberNames.GetMinValue,
440
440
  setter: MemberNames.SetMinValue,
441
- cppType: "int"
441
+ cppType: "int64_t"
442
442
  },
443
443
  {
444
444
  name: MemberNames.MaxValue,
445
445
  getter: MemberNames.GetMaxValue,
446
446
  setter: MemberNames.SetMaxValue,
447
- cppType: "int"
447
+ cppType: "int64_t"
448
448
  },
449
449
  {
450
450
  name: MemberNames.MinLength,
@@ -349,7 +349,7 @@ class DartRenderer extends ConvenienceRenderer_1.ConvenienceRenderer {
349
349
  this.emitLine(className, "({");
350
350
  this.indent(() => {
351
351
  this.forEachClassProperty(c, "none", (name, _, _p) => {
352
- this.emitLine(this._options.requiredProperties ? "@required " : "", "this.", name, ",");
352
+ this.emitLine(this._options.requiredProperties ? "required " : "", "this.", name, ",");
353
353
  });
354
354
  });
355
355
  this.emitLine("});");
@@ -70,6 +70,7 @@ const javaKeywords = [
70
70
  "Double",
71
71
  "Boolean",
72
72
  "String",
73
+ "List",
73
74
  "Map",
74
75
  "UUID",
75
76
  "Exception",
@@ -5,6 +5,7 @@ import { Sourcelike } from "../Source";
5
5
  import { TargetLanguage } from "../TargetLanguage";
6
6
  import { ArrayType, ClassType, EnumType, MapType, ObjectType, PrimitiveType, Type, UnionType } from "../Type";
7
7
  import { RenderContext } from "../Renderer";
8
+ import { AcronymStyleOptions } from "../support/Acronyms";
8
9
  export declare enum Framework {
9
10
  None = 0,
10
11
  Jackson = 1,
@@ -13,6 +14,7 @@ export declare enum Framework {
13
14
  }
14
15
  export declare const kotlinOptions: {
15
16
  framework: EnumOption<Framework>;
17
+ acronymStyle: EnumOption<AcronymStyleOptions>;
16
18
  packageName: StringOption;
17
19
  };
18
20
  export declare class KotlinTargetLanguage extends TargetLanguage {
@@ -11,6 +11,7 @@ const Support_1 = require("../support/Support");
11
11
  const TargetLanguage_1 = require("../TargetLanguage");
12
12
  const Type_1 = require("../Type");
13
13
  const TypeUtils_1 = require("../TypeUtils");
14
+ const Acronyms_1 = require("../support/Acronyms");
14
15
  var Framework;
15
16
  (function (Framework) {
16
17
  Framework[Framework["None"] = 0] = "None";
@@ -20,6 +21,7 @@ var Framework;
20
21
  })(Framework = exports.Framework || (exports.Framework = {}));
21
22
  exports.kotlinOptions = {
22
23
  framework: new RendererOptions_1.EnumOption("framework", "Serialization framework", [["just-types", Framework.None], ["jackson", Framework.Jackson], ["klaxon", Framework.Klaxon], ["kotlinx", Framework.KotlinX]], "klaxon"),
24
+ acronymStyle: Acronyms_1.acronymOption(Acronyms_1.AcronymStyleOptions.Pascal),
23
25
  packageName: new RendererOptions_1.StringOption("package", "Package", "PACKAGE", "quicktype")
24
26
  };
25
27
  class KotlinTargetLanguage extends TargetLanguage_1.TargetLanguage {
@@ -27,7 +29,7 @@ class KotlinTargetLanguage extends TargetLanguage_1.TargetLanguage {
27
29
  super("Kotlin", ["kotlin"], "kt");
28
30
  }
29
31
  getOptions() {
30
- return [exports.kotlinOptions.framework, exports.kotlinOptions.packageName];
32
+ return [exports.kotlinOptions.framework, exports.kotlinOptions.acronymStyle, exports.kotlinOptions.packageName];
31
33
  }
32
34
  get supportsOptionalClassProperties() {
33
35
  return true;
@@ -110,9 +112,9 @@ function isStartCharacter(codePoint) {
110
112
  return isPartCharacter(codePoint) && !Strings_1.isDigit(codePoint);
111
113
  }
112
114
  const legalizeName = Strings_1.legalizeCharacters(isPartCharacter);
113
- function kotlinNameStyle(isUpper, original) {
115
+ function kotlinNameStyle(isUpper, original, acronymsStyle = Strings_1.allUpperWordStyle) {
114
116
  const words = Strings_1.splitIntoWords(original);
115
- return Strings_1.combineWords(words, legalizeName, isUpper ? Strings_1.firstUpperWordStyle : Strings_1.allLowerWordStyle, Strings_1.firstUpperWordStyle, isUpper ? Strings_1.allUpperWordStyle : Strings_1.allLowerWordStyle, Strings_1.allUpperWordStyle, "", isStartCharacter);
117
+ return Strings_1.combineWords(words, legalizeName, isUpper ? Strings_1.firstUpperWordStyle : Strings_1.allLowerWordStyle, Strings_1.firstUpperWordStyle, isUpper ? Strings_1.allUpperWordStyle : Strings_1.allLowerWordStyle, acronymsStyle, "", isStartCharacter);
116
118
  }
117
119
  function unicodeEscape(codePoint) {
118
120
  return "\\u" + Strings_1.intToHex(codePoint, 4);
@@ -122,8 +124,6 @@ function stringEscape(s) {
122
124
  // "$this" is a template string in Kotlin so we have to escape $
123
125
  return _stringEscape(s).replace(/\$/g, "\\$");
124
126
  }
125
- const upperNamingFunction = Naming_1.funPrefixNamer("upper", s => kotlinNameStyle(true, s));
126
- const lowerNamingFunction = Naming_1.funPrefixNamer("lower", s => kotlinNameStyle(false, s));
127
127
  class KotlinRenderer extends ConvenienceRenderer_1.ConvenienceRenderer {
128
128
  constructor(targetLanguage, renderContext, _kotlinOptions) {
129
129
  super(targetLanguage, renderContext);
@@ -145,16 +145,16 @@ class KotlinRenderer extends ConvenienceRenderer_1.ConvenienceRenderer {
145
145
  return kotlinNameStyle(true, rawName);
146
146
  }
147
147
  makeNamedTypeNamer() {
148
- return upperNamingFunction;
148
+ return Naming_1.funPrefixNamer("upper", s => kotlinNameStyle(true, s, Acronyms_1.acronymStyle(this._kotlinOptions.acronymStyle)));
149
149
  }
150
150
  namerForObjectProperty() {
151
- return lowerNamingFunction;
151
+ return Naming_1.funPrefixNamer("lower", s => kotlinNameStyle(false, s, Acronyms_1.acronymStyle(this._kotlinOptions.acronymStyle)));
152
152
  }
153
153
  makeUnionMemberNamer() {
154
154
  return Naming_1.funPrefixNamer("upper", s => kotlinNameStyle(true, s) + "Value");
155
155
  }
156
156
  makeEnumCaseNamer() {
157
- return upperNamingFunction;
157
+ return Naming_1.funPrefixNamer("upper", s => kotlinNameStyle(true, s, Acronyms_1.acronymStyle(this._kotlinOptions.acronymStyle)));
158
158
  }
159
159
  emitDescriptionBlock(lines) {
160
160
  this.emitCommentLines(lines, " * ", "/**", " */");
@@ -735,12 +735,12 @@ class KotlinXRenderer extends KotlinRenderer {
735
735
  super(targetLanguage, renderContext, _kotlinOptions);
736
736
  }
737
737
  anySourceType(optional) {
738
- return ["JsonObject", optional];
738
+ return ["JsonElement", optional];
739
739
  }
740
740
  arrayType(arrayType, withIssues = false, noOptional = false) {
741
741
  const valType = this.kotlinType(arrayType.items, withIssues, true);
742
742
  const name = this.sourcelikeToString(valType);
743
- if (name === "JsonObject") {
743
+ if (name === "JsonObject" || name === "JsonElement") {
744
744
  return "JsonArray";
745
745
  }
746
746
  return super.arrayType(arrayType, withIssues, noOptional);
@@ -748,7 +748,7 @@ class KotlinXRenderer extends KotlinRenderer {
748
748
  mapType(mapType, withIssues = false, noOptional = false) {
749
749
  const valType = this.kotlinType(mapType.values, withIssues, true);
750
750
  const name = this.sourcelikeToString(valType);
751
- if (name === "JsonObject") {
751
+ if (name === "JsonObject" || name === "JsonElement") {
752
752
  return "JsonObject";
753
753
  }
754
754
  return super.mapType(mapType, withIssues, noOptional);
@@ -802,28 +802,12 @@ class KotlinXRenderer extends KotlinRenderer {
802
802
  }
803
803
  emitEnumDefinition(e, enumName) {
804
804
  this.emitDescription(this.descriptionForType(e));
805
- this.emitLine(["@Serializable(with = ", enumName, ".Companion::class)"]);
805
+ this.emitLine(["@Serializable"]);
806
806
  this.emitBlock(["enum class ", enumName, "(val value: String)"], () => {
807
807
  let count = e.cases.size;
808
808
  this.forEachEnumCase(e, "none", (name, json) => {
809
- this.emitLine(name, `("${stringEscape(json)}")`, --count === 0 ? ";" : ",");
810
- });
811
- this.ensureBlankLine();
812
- this.emitBlock(["companion object : KSerializer<", enumName, ">"], () => {
813
- this.emitBlock("override val descriptor: SerialDescriptor get()", () => {
814
- this.emitLine("return PrimitiveSerialDescriptor(\"", this._kotlinOptions.packageName, ".", enumName, "\", PrimitiveKind.STRING)");
815
- });
816
- this.emitBlock(["override fun deserialize(decoder: Decoder): ", enumName, " = when (val value = decoder.decodeString())"], () => {
817
- let table = [];
818
- this.forEachEnumCase(e, "none", (name, json) => {
819
- table.push([[`"${stringEscape(json)}"`], [" -> ", name]]);
820
- });
821
- table.push([["else"], [" -> throw IllegalArgumentException(\"", enumName, " could not parse: $value\")"]]);
822
- this.emitTable(table);
823
- });
824
- this.emitBlock(["override fun serialize(encoder: Encoder, value: ", enumName, ")"], () => {
825
- this.emitLine(["return encoder.encodeString(value.value)"]);
826
- });
809
+ const jsonEnum = stringEscape(json);
810
+ this.emitLine(`@SerialName("${jsonEnum}") `, name, `("${jsonEnum}")`, --count === 0 ? ";" : ",");
827
811
  });
828
812
  });
829
813
  }
@@ -162,7 +162,7 @@ const forbiddenForEnumCases = ["new", staticEnumValuesIdentifier];
162
162
  function splitExtension(filename) {
163
163
  const i = filename.lastIndexOf(".");
164
164
  const extension = i !== -1 ? filename.split(".").pop() : "m";
165
- filename = i !== -1 ? filename.substr(0, i) : filename;
165
+ filename = i !== -1 ? filename.slice(0, i) : filename;
166
166
  return [filename, extension === undefined ? "m" : extension];
167
167
  }
168
168
  class ObjectiveCRenderer extends ConvenienceRenderer_1.ConvenienceRenderer {
@@ -186,7 +186,7 @@ class ObjectiveCRenderer extends ConvenienceRenderer_1.ConvenienceRenderer {
186
186
  }
187
187
  if (firstNonUpper < 2)
188
188
  return DEFAULT_CLASS_PREFIX;
189
- return name.substr(0, firstNonUpper - 1);
189
+ return name.slice(0, firstNonUpper - 1);
190
190
  }
191
191
  forbiddenNamesForGlobalNamespace() {
192
192
  return keywords;
@@ -605,7 +605,7 @@ class ObjectiveCRenderer extends ConvenienceRenderer_1.ConvenienceRenderer {
605
605
  variableNameForTopLevel(name) {
606
606
  const camelCaseName = Source_1.modifySource(serialized => {
607
607
  // 1. remove class prefix
608
- serialized = serialized.substr(this._classPrefix.length);
608
+ serialized = serialized.slice(this._classPrefix.length);
609
609
  // 2. camel case
610
610
  return Strings_1.camelCase(serialized);
611
611
  }, name);
@@ -43,7 +43,13 @@ class RustTargetLanguage extends TargetLanguage_1.TargetLanguage {
43
43
  super("Rust", ["rust", "rs", "rustlang"], "rs");
44
44
  }
45
45
  getOptions() {
46
- return [exports.rustOptions.density, exports.rustOptions.visibility, exports.rustOptions.deriveDebug];
46
+ return [
47
+ exports.rustOptions.density,
48
+ exports.rustOptions.visibility,
49
+ exports.rustOptions.deriveDebug,
50
+ exports.rustOptions.edition2018,
51
+ exports.rustOptions.leadingComments
52
+ ];
47
53
  }
48
54
  }
49
55
  exports.RustTargetLanguage = RustTargetLanguage;
@@ -12,7 +12,6 @@ export declare const swiftOptions: {
12
12
  justTypes: BooleanOption;
13
13
  convenienceInitializers: BooleanOption;
14
14
  explicitCodingKeys: BooleanOption;
15
- urlSession: BooleanOption;
16
15
  alamofire: BooleanOption;
17
16
  namedTypePrefix: StringOption;
18
17
  useClasses: EnumOption<boolean>;
@@ -92,6 +91,5 @@ export declare class SwiftRenderer extends ConvenienceRenderer {
92
91
  private emitConvenienceMutator;
93
92
  protected emitMark(line: Sourcelike, horizontalLine?: boolean): void;
94
93
  protected emitSourceStructure(): void;
95
- private emitURLSessionExtension;
96
94
  private emitAlamofireExtension;
97
95
  }
@@ -19,18 +19,26 @@ exports.swiftOptions = {
19
19
  justTypes: new RendererOptions_1.BooleanOption("just-types", "Plain types only", false),
20
20
  convenienceInitializers: new RendererOptions_1.BooleanOption("initializers", "Generate initializers and mutators", true),
21
21
  explicitCodingKeys: new RendererOptions_1.BooleanOption("coding-keys", "Explicit CodingKey values in Codable types", true),
22
- urlSession: new RendererOptions_1.BooleanOption("url-session", "URLSession task extensions", false),
23
22
  alamofire: new RendererOptions_1.BooleanOption("alamofire", "Alamofire extensions", false),
24
23
  namedTypePrefix: new RendererOptions_1.StringOption("type-prefix", "Prefix for type names", "PREFIX", "", "secondary"),
25
- useClasses: new RendererOptions_1.EnumOption("struct-or-class", "Structs or classes", [["struct", false], ["class", true]]),
24
+ useClasses: new RendererOptions_1.EnumOption("struct-or-class", "Structs or classes", [
25
+ ["struct", false],
26
+ ["class", true]
27
+ ]),
26
28
  mutableProperties: new RendererOptions_1.BooleanOption("mutable-properties", "Use var instead of let for object properties", false),
27
29
  acronymStyle: Acronyms_1.acronymOption(Acronyms_1.AcronymStyleOptions.Pascal),
28
- dense: new RendererOptions_1.EnumOption("density", "Code density", [["dense", true], ["normal", false]], "dense", "secondary"),
30
+ dense: new RendererOptions_1.EnumOption("density", "Code density", [
31
+ ["dense", true],
32
+ ["normal", false]
33
+ ], "dense", "secondary"),
29
34
  linux: new RendererOptions_1.BooleanOption("support-linux", "Support Linux", false, "secondary"),
30
35
  objcSupport: new RendererOptions_1.BooleanOption("objective-c-support", "Objects inherit from NSObject and @objcMembers is added to classes", false),
31
36
  swift5Support: new RendererOptions_1.BooleanOption("swift-5-support", "Renders output in a Swift 5 compatible mode", false),
32
37
  multiFileOutput: new RendererOptions_1.BooleanOption("multi-file-output", "Renders each top-level object in its own Swift file", false),
33
- accessLevel: new RendererOptions_1.EnumOption("access-level", "Access level", [["internal", "internal"], ["public", "public"]], "internal", "secondary"),
38
+ accessLevel: new RendererOptions_1.EnumOption("access-level", "Access level", [
39
+ ["internal", "internal"],
40
+ ["public", "public"]
41
+ ], "internal", "secondary"),
34
42
  protocol: new RendererOptions_1.EnumOption("protocol", "Make types implement protocol", [
35
43
  ["none", { equatable: false, hashable: false }],
36
44
  ["equatable", { equatable: true, hashable: false }],
@@ -65,7 +73,6 @@ class SwiftTargetLanguage extends TargetLanguage_1.TargetLanguage {
65
73
  exports.swiftOptions.convenienceInitializers,
66
74
  exports.swiftOptions.explicitCodingKeys,
67
75
  exports.swiftOptions.accessLevel,
68
- exports.swiftOptions.urlSession,
69
76
  exports.swiftOptions.alamofire,
70
77
  exports.swiftOptions.linux,
71
78
  exports.swiftOptions.namedTypePrefix,
@@ -97,6 +104,7 @@ class SwiftTargetLanguage extends TargetLanguage_1.TargetLanguage {
97
104
  }
98
105
  exports.SwiftTargetLanguage = SwiftTargetLanguage;
99
106
  const keywords = [
107
+ "await",
100
108
  "associatedtype",
101
109
  "class",
102
110
  "deinit",
@@ -227,20 +235,12 @@ class SwiftRenderer extends ConvenienceRenderer_1.ConvenienceRenderer {
227
235
  this.ensureBlankLine();
228
236
  this.forEachTopLevel("leading-and-interposing", (t, name) => this.emitTopLevelMapAndArrayConvenienceInitializerExtensions(t, name));
229
237
  }
230
- if ((!this._options.justTypes && this._options.convenienceInitializers) ||
231
- this._options.urlSession ||
232
- this._options.alamofire) {
238
+ if ((!this._options.justTypes && this._options.convenienceInitializers) || this._options.alamofire) {
233
239
  this.ensureBlankLine();
234
240
  this.emitMark("Helper functions for creating encoders and decoders", true);
235
241
  this.ensureBlankLine();
236
242
  this.emitNewEncoderDecoder();
237
243
  }
238
- if (this._options.urlSession) {
239
- this.ensureBlankLine();
240
- this.emitMark("URLSession response handlers", true);
241
- this.ensureBlankLine();
242
- this.emitURLSessionExtension();
243
- }
244
244
  if (this._options.alamofire) {
245
245
  this.ensureBlankLine();
246
246
  this.emitMark("Alamofire response handlers", true);
@@ -641,18 +641,6 @@ class SwiftRenderer extends ConvenienceRenderer_1.ConvenienceRenderer {
641
641
  this.emitLine("// let ", Source_1.modifySource(Strings_1.camelCase, name), " = ", "try? newJSONDecoder().decode(", name, ".self, from: jsonData)");
642
642
  }
643
643
  }
644
- if (this._options.urlSession) {
645
- this.emitLine("//");
646
- this.emitLine("// To read values from URLs:");
647
- const lowerName = Source_1.modifySource(Strings_1.camelCase, name);
648
- this.emitLine("//");
649
- this.emitLine("// let task = URLSession.shared.", lowerName, "Task(with: url) { ", lowerName, ", response, error in");
650
- this.emitLine("// if let ", lowerName, " = ", lowerName, " {");
651
- this.emitLine("// ...");
652
- this.emitLine("// }");
653
- this.emitLine("// }");
654
- this.emitLine("// task.resume()");
655
- }
656
644
  if (this._options.alamofire) {
657
645
  this.emitLine("//");
658
646
  this.emitLine("// To parse values from Alamofire responses:");
@@ -756,7 +744,13 @@ class SwiftRenderer extends ConvenienceRenderer_1.ConvenienceRenderer {
756
744
  }
757
745
  propertyLinesDefinition(name, parameter) {
758
746
  const useMutableProperties = this._options.mutableProperties;
759
- return [this.accessLevel, useMutableProperties ? "var " : "let ", name, ": ", this.swiftPropertyType(parameter)];
747
+ return [
748
+ this.accessLevel,
749
+ useMutableProperties ? "var " : "let ",
750
+ name,
751
+ ": ",
752
+ this.swiftPropertyType(parameter)
753
+ ];
760
754
  }
761
755
  renderClassDefinition(c, className) {
762
756
  this.startFile(className);
@@ -853,7 +847,7 @@ class SwiftRenderer extends ConvenienceRenderer_1.ConvenienceRenderer {
853
847
  }
854
848
  if (this.propertyCount(c) === 0 && this._options.objcSupport) {
855
849
  this.emitBlockWithAccess(["override init()"], () => {
856
- "";
850
+ return "";
857
851
  });
858
852
  }
859
853
  else {
@@ -1152,33 +1146,6 @@ encoder.dateEncodingStrategy = .formatted(formatter)`);
1152
1146
  this.emitSupportFunctions4();
1153
1147
  }
1154
1148
  }
1155
- emitURLSessionExtension() {
1156
- this.ensureBlankLine();
1157
- this.emitBlockWithAccess("extension URLSession", () => {
1158
- this
1159
- .emitMultiline(`fileprivate func codableTask<T: Codable>(with url: URL, completionHandler: @escaping (T?, URLResponse?, Error?) -> Void) -> URLSessionDataTask {
1160
- return self.dataTask(with: url) { data, response, error in
1161
- guard let data = data, error == nil else {
1162
- completionHandler(nil, response, error)
1163
- return
1164
- }
1165
- completionHandler(try? newJSONDecoder().decode(T.self, from: data), response, nil)
1166
- }
1167
- }`);
1168
- this.ensureBlankLine();
1169
- this.forEachTopLevel("leading-and-interposing", (_, name) => {
1170
- this.emitBlock([
1171
- "func ",
1172
- Source_1.modifySource(Strings_1.camelCase, name),
1173
- "Task(with url: URL, completionHandler: @escaping (",
1174
- name,
1175
- "?, URLResponse?, Error?) -> Void) -> URLSessionDataTask"
1176
- ], () => {
1177
- this.emitLine(`return self.codableTask(with: url, completionHandler: completionHandler)`);
1178
- });
1179
- });
1180
- });
1181
- }
1182
1149
  emitAlamofireExtension() {
1183
1150
  this.ensureBlankLine();
1184
1151
  this.emitBlockWithAccess("extension DataRequest", () => {
@@ -119,6 +119,10 @@ class TypeScriptFlowBaseRenderer extends JavaScript_1.JavaScriptRenderer {
119
119
  [this.sourceFor(t).source, ";"]
120
120
  ];
121
121
  });
122
+ const additionalProperties = c.getAdditionalProperties();
123
+ if (additionalProperties) {
124
+ this.emitTable([["[property: string]", ": ", this.sourceFor(additionalProperties).source, ";"]]);
125
+ }
122
126
  }
123
127
  emitClass(c, className) {
124
128
  this.emitDescription(this.descriptionForType(c));
@@ -247,7 +247,7 @@ function trimEnd(str) {
247
247
  }
248
248
  if (firstWS === l)
249
249
  return str;
250
- return str.substr(0, firstWS);
250
+ return str.slice(0, firstWS);
251
251
  }
252
252
  exports.trimEnd = trimEnd;
253
253
  function modifyFirstChar(f, s) {
@@ -107,7 +107,7 @@ function schemaForTypeScriptSources(sources) {
107
107
  continue;
108
108
  }
109
109
  const index = quicktype_core_1.defined(matches.index);
110
- definition.description = description.substr(0, index) + description.substr(index + matches[0].length);
110
+ definition.description = description.slice(0, index) + description.slice(index + matches[0].length);
111
111
  uris.push(`#/definitions/${name}`);
112
112
  if (topLevelName === undefined) {
113
113
  if (typeof definition.title === "string") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "quicktype",
3
- "version": "15.0.261",
3
+ "version": "16.0.0",
4
4
  "license": "Apache-2.0",
5
5
  "main": "dist/cli/index.js",
6
6
  "types": "dist/cli/index.d.ts",
@@ -13,7 +13,8 @@
13
13
  "start": "script/watch",
14
14
  "pkg": "script/make-pkgs.sh",
15
15
  "tslint": "tslint --project src/cli --exclude 'src/__tests__/**' --exclude 'src/quicktype-core/input/io/get-stream/**'",
16
- "clean": "rm -rf dist node_modules *~"
16
+ "clean": "rm -rf dist node_modules *~",
17
+ "publish": "script/publish.sh"
17
18
  },
18
19
  "dependencies": {
19
20
  "chalk": "^2.4.1",
@@ -33,7 +34,7 @@
33
34
  "typescript": "~3.2.1",
34
35
  "@mark.probst/typescript-json-schema": "~0.32.0",
35
36
  "@mark.probst/unicode-properties": "~1.1.0",
36
- "urijs": "^1.19.6",
37
+ "urijs": "^1.19.11",
37
38
  "uuid": "^3.2.1",
38
39
  "wordwrap": "^1.0.0",
39
40
  "yaml": "^1.5.0",
@@ -52,16 +53,13 @@
52
53
  "@types/yaml": "^1.0.2",
53
54
  "ajv": "^5.5.2",
54
55
  "deep-equal": "^1.0.1",
55
- "elm": "0.18.0-exp5",
56
56
  "exit": "^0.1.2",
57
- "flow-bin": "^0.66.0",
58
- "flow-remove-types": "^1.2.3",
59
57
  "jest": "^23.1.0",
60
58
  "promise-timeout": "^1.3.0",
61
59
  "semver": "^5.5.0",
62
- "shelljs": "^0.7.8",
60
+ "shelljs": "^0.8.5",
63
61
  "ts-jest": "^23.1.3",
64
- "ts-node": "^3.3.0",
62
+ "ts-node": "^10.9.1",
65
63
  "tslint": "^5.11.0",
66
64
  "uglify-js": "^3.3.22",
67
65
  "watch": "^1.0.2",
package/dist/cli/ci.d.ts DELETED
@@ -1,5 +0,0 @@
1
- export declare function tryHash(envs: Array<string | undefined>): string | undefined;
2
- export declare function getProvider(environment?: any): {
3
- provider: string;
4
- userId: string;
5
- } | undefined;
package/dist/cli/ci.js DELETED
@@ -1,39 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const process = require("process");
4
- const crypto_1 = require("crypto");
5
- // A map from CI providers to environment variables that uniquely identify a project.
6
- // If present, these variables are hashed to produce a unique userId for quicktype in CI.
7
- function getProviders(env = process.env) {
8
- return [
9
- ["Travis", [env.TRAVIS_REPO_SLUG]],
10
- ["Jenkins", [env.JENKINS_URL]],
11
- ["TeamCity", [env.TEAMCITY_PROJECT_NAME]],
12
- ["CircleCI", [env.CIRCLE_PROJECT_USERNAME, env.CIRCLE_PROJECT_REPONAME]],
13
- ["Codeship", [env.CI_REPO_NAME]],
14
- ["GitLab", [env.GITLAB_CI, env.CI_REPOSITORY_URL, env.CI_PROJECT_ID]],
15
- ["VSTS", [env.SYSTEM_TEAMFOUNDATIONCOLLECTIONURI, env.BUILD_REPOSITORY_NAME]],
16
- ["App Center", [env.SYSTEM_TEAMFOUNDATIONCOLLECTIONURI, env.BUILD_REPOSITORY_NAME]],
17
- // We intentionally collapse users with env.CI to prevent over-counting for unidentified CI
18
- ["Other", [env.CI]]
19
- ];
20
- }
21
- function tryHash(envs) {
22
- if (envs.some(s => s === undefined)) {
23
- return undefined;
24
- }
25
- const hash = crypto_1.createHash("sha256");
26
- envs.forEach(s => hash.update(s));
27
- return hash.digest("base64");
28
- }
29
- exports.tryHash = tryHash;
30
- function getProvider(environment) {
31
- for (const [provider, vars] of getProviders(environment)) {
32
- const hash = tryHash(vars);
33
- if (hash !== undefined) {
34
- return { provider, userId: hash };
35
- }
36
- }
37
- return undefined;
38
- }
39
- exports.getProvider = getProvider;