dtsgenerator 3.12.1 → 3.14.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.
@@ -1,17 +1,17 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const tslib_1 = require("tslib");
4
- const debug_1 = tslib_1.__importDefault(require("debug"));
5
- const ts = tslib_1.__importStar(require("typescript"));
4
+ const debug_1 = (0, tslib_1.__importDefault)(require("debug"));
5
+ const ts = (0, tslib_1.__importStar)(require("typescript"));
6
6
  const jsonPointer_1 = require("../jsonPointer");
7
- const ast = tslib_1.__importStar(require("./astBuilder"));
8
- const config_1 = tslib_1.__importDefault(require("./config"));
7
+ const ast = (0, tslib_1.__importStar)(require("./astBuilder"));
8
+ const config_1 = (0, tslib_1.__importDefault)(require("./config"));
9
9
  const jsonSchema_1 = require("./jsonSchema");
10
- const referenceResolver_1 = tslib_1.__importDefault(require("./referenceResolver"));
10
+ const referenceResolver_1 = (0, tslib_1.__importDefault)(require("./referenceResolver"));
11
11
  const type_1 = require("./type");
12
- const utils = tslib_1.__importStar(require("./utils"));
13
- const debug = debug_1.default('dtsgen');
14
- const typeMarker = Symbol();
12
+ const typeTree_1 = require("./typeTree");
13
+ const utils = (0, tslib_1.__importStar)(require("./utils"));
14
+ const debug = (0, debug_1.default)('dtsgen');
15
15
  class DtsGenerator {
16
16
  constructor(contents) {
17
17
  this.resolver = new referenceResolver_1.default();
@@ -26,8 +26,8 @@ class DtsGenerator {
26
26
  debug('generate type definition files.');
27
27
  this.contents.forEach((schema) => this.resolver.registerSchema(schema));
28
28
  await this.resolver.resolve();
29
- const map = this.buildSchemaMergedMap(this.resolver.getAllRegisteredSchema());
30
- const root = this.walk(map, true);
29
+ const tree = (0, typeTree_1.buildTypeTree)(this.resolver.getAllRegisteredSchema());
30
+ const root = this.walk(tree);
31
31
  const file = ts.createSourceFile('_.d.ts', '', config_1.default.target, false, ts.ScriptKind.TS);
32
32
  Object.assign(file, {
33
33
  statements: ts.factory.createNodeArray(root),
@@ -44,33 +44,11 @@ class DtsGenerator {
44
44
  result.dispose();
45
45
  return transformedContent;
46
46
  }
47
- buildSchemaMergedMap(schemas) {
48
- const map = {};
49
- const paths = [];
50
- for (const type of schemas) {
51
- const path = type.id.toNames();
52
- paths.push({ path, type });
53
- }
54
- for (const item of paths) {
55
- const path = item.path;
56
- const parent = jsonPointer_1.get(map, path, true);
57
- if (parent == null) {
58
- jsonPointer_1.set(map, path, { [typeMarker]: item.type });
59
- }
60
- else {
61
- Object.assign(parent, { [typeMarker]: item.type });
62
- }
63
- }
64
- if (Object.keys(map).length === 0) {
65
- throw new Error('There is no schema in the input contents.');
66
- }
67
- return map;
68
- }
69
47
  async getPlugins() {
70
48
  const pre = [];
71
49
  const post = [];
72
50
  for (const [name, option] of Object.entries(config_1.default.plugins)) {
73
- const plugin = await type_1.loadPlugin(name, option);
51
+ const plugin = await (0, type_1.loadPlugin)(name, option);
74
52
  if (plugin == null) {
75
53
  continue;
76
54
  }
@@ -117,18 +95,20 @@ class DtsGenerator {
117
95
  }
118
96
  return result;
119
97
  }
120
- walk(map, root) {
98
+ walk(tree, root = true) {
121
99
  const result = [];
122
- const keys = Object.keys(map).sort();
100
+ const keys = [...tree.children.keys()].sort();
123
101
  for (const key of keys) {
124
- const value = map[key];
125
- if (typeof value === 'object' &&
126
- Object.prototype.hasOwnProperty.call(value, typeMarker)) {
127
- const schema = value[typeMarker];
102
+ const value = tree.children.get(key);
103
+ if (value === undefined) {
104
+ continue;
105
+ }
106
+ if (value.schema !== undefined) {
107
+ const schema = value.schema;
128
108
  debug(` walk doProcess: key=${key} schemaId=${schema.id.getAbsoluteId()}`);
129
109
  result.push(this.walkSchema(schema, root));
130
110
  }
131
- if (typeof value === 'object' && Object.keys(value).length > 0) {
111
+ if (value.children.size > 0) {
132
112
  result.push(ast.buildNamespaceNode(key, this.walk(value, false), root));
133
113
  }
134
114
  }
@@ -137,23 +117,23 @@ class DtsGenerator {
137
117
  walkSchema(schema, root) {
138
118
  const normalized = this.normalizeContent(schema);
139
119
  this.currentSchema = normalized;
140
- const getNode = () => {
141
- const type = normalized.content.type;
142
- switch (type) {
143
- case 'any':
144
- return this.generateAnyTypeModel(normalized, root);
145
- case 'array':
146
- return this.generateTypeCollection(normalized, root);
147
- case 'object':
148
- default:
149
- return this.generateDeclareType(normalized, root);
150
- }
151
- };
152
- return ast.addOptionalInformation(ast.addComment(getNode(), normalized, true), normalized, true);
120
+ return ast.addOptionalInformation(ast.addComment(this.parseSchema(normalized, root), normalized, true), normalized, true);
121
+ }
122
+ parseSchema(schema, root = false) {
123
+ const type = schema.content.type;
124
+ switch (type) {
125
+ case 'any':
126
+ return this.generateAnyTypeModel(schema, root);
127
+ case 'array':
128
+ return this.generateTypeCollection(schema, root);
129
+ case 'object':
130
+ default:
131
+ return this.generateDeclareType(schema, root);
132
+ }
153
133
  }
154
134
  normalizeContent(schema, pointer) {
155
135
  if (pointer != null) {
156
- schema = jsonSchema_1.getSubSchema(schema, pointer);
136
+ schema = (0, jsonSchema_1.getSubSchema)(schema, pointer);
157
137
  }
158
138
  return Object.assign(schema, {
159
139
  content: this.normalizeSchemaContent(schema.content),
@@ -247,19 +227,15 @@ class DtsGenerator {
247
227
  }
248
228
  if (content.properties) {
249
229
  for (const propertyName of Object.keys(content.properties)) {
250
- const schema = this.normalizeContent(baseSchema, '/properties/' + jsonPointer_1.tilde(propertyName));
230
+ const schema = this.normalizeContent(baseSchema, '/properties/' + (0, jsonPointer_1.tilde)(propertyName));
251
231
  const node = ast.buildPropertySignature(schema, propertyName, this.generateTypeProperty(schema), baseSchema.content.required, false);
252
232
  result.push(ast.addOptionalInformation(ast.addComment(node, schema, true), schema, true));
253
233
  }
254
234
  }
255
235
  if (content.patternProperties) {
256
- const schemasTypes = [];
257
- for (const propertyName of Object.keys(content.patternProperties)) {
258
- const schema = this.normalizeContent(baseSchema, '/patternProperties/' + jsonPointer_1.tilde(propertyName));
259
- schemasTypes.push(this.generateTypeProperty(schema));
260
- }
261
- const node = ast.buildPropertySignature({ content: { readOnly: false } }, 'pattern', ts.createUnionTypeNode(schemasTypes), baseSchema.content.required, true);
262
- result.push(ts.addSyntheticTrailingComment(node, ts.SyntaxKind.MultiLineCommentTrivia, ` Patterns: ${Object.keys(content.patternProperties).join(' | ')} `));
236
+ const properties = Object.keys(content.patternProperties);
237
+ const node = ast.buildPropertySignature({ content: { readOnly: false } }, 'pattern', ast.buildUnionTypeNode(properties, (propertyName) => this.generateTypeProperty(this.normalizeContent(baseSchema, '/patternProperties/' + (0, jsonPointer_1.tilde)(propertyName))), true), baseSchema.content.required, true);
238
+ result.push(ts.addSyntheticTrailingComment(node, ts.SyntaxKind.MultiLineCommentTrivia, ` Patterns: ${properties.join(' | ')} `));
263
239
  }
264
240
  return result;
265
241
  }
@@ -271,19 +247,23 @@ class DtsGenerator {
271
247
  throw new Error('target referenced id is nothing: ' + content.$ref);
272
248
  }
273
249
  const refSchema = this.normalizeContent(ref);
274
- const node = ast.buildTypeReferenceNode(refSchema, this.currentSchema);
275
- return ast.addOptionalInformation(ast.addComment(node, refSchema, false), refSchema, false);
250
+ const node = ast.addOptionalInformation(ast.addComment(ast.buildTypeReferenceNode(refSchema, this.currentSchema), refSchema, false), refSchema, false);
251
+ return node;
276
252
  }
277
253
  if (content.anyOf) {
278
254
  const mergeContent = Object.assign({}, content);
279
255
  delete mergeContent.anyOf;
280
- return this.generateArrayedType(schema, content.anyOf, mergeContent, '/anyOf/', terminate);
256
+ return this.generateUnionType(schema, content.anyOf, mergeContent, '/anyOf/', terminate);
281
257
  }
282
258
  if (content.oneOf) {
283
259
  const mergeContent = Object.assign({}, content);
284
260
  delete mergeContent.oneOf;
285
- return this.generateArrayedType(schema, content.oneOf, mergeContent, '/oneOf/', terminate);
261
+ return this.generateUnionType(schema, content.oneOf, mergeContent, '/oneOf/', terminate);
286
262
  }
263
+ return this.generateLiteralTypeProperty(schema, terminate);
264
+ }
265
+ generateLiteralTypeProperty(schema, terminate = true) {
266
+ const content = schema.content;
287
267
  if (content.enum) {
288
268
  return ast.buildUnionTypeNode(content.enum, (value) => {
289
269
  return this.generateLiteralTypeNode(content, value);
@@ -299,17 +279,32 @@ class DtsGenerator {
299
279
  return this.generateType(schema, terminate);
300
280
  }
301
281
  }
282
+ checkExistOtherType(content, base) {
283
+ const schema = Object.assign({}, base, { content });
284
+ const result = this.generateLiteralTypeProperty(schema, false);
285
+ if (result.kind === ts.SyntaxKind.AnyKeyword) {
286
+ return undefined;
287
+ }
288
+ else if (result.kind === ts.SyntaxKind.TypeLiteral) {
289
+ const node = result;
290
+ if (node.members.length === 1 &&
291
+ node.members[0].kind === ts.SyntaxKind.IndexSignature) {
292
+ return undefined;
293
+ }
294
+ }
295
+ return result;
296
+ }
302
297
  generateLiteralTypeNode(content, value) {
303
298
  switch (content.type) {
304
299
  case 'integer':
305
300
  case 'number':
306
301
  return ast.buildNumericLiteralTypeNode(String(value));
307
302
  case 'boolean':
308
- return ast.buildBooleanLiteralTypeNode(value);
303
+ return ast.buildBooleanLiteralTypeNode(Boolean(value));
309
304
  case 'null':
310
305
  return ast.buildNullKeyword();
311
306
  case 'string':
312
- return ast.buildStringLiteralTypeNode(value);
307
+ return ast.buildStringLiteralTypeNode(String(value));
313
308
  }
314
309
  if (value === null) {
315
310
  return ast.buildNullKeyword();
@@ -324,17 +319,28 @@ class DtsGenerator {
324
319
  }
325
320
  return ast.buildStringLiteralTypeNode(String(value));
326
321
  }
327
- generateArrayedType(baseSchema, contents, mergeContent, path, terminate) {
328
- return ast.addOptionalInformation(ast.addComment(ast.buildUnionTypeNode(contents, (_, index) => {
322
+ generateUnionType(baseSchema, contents, mergeContent, path, terminate) {
323
+ const merged = [];
324
+ const children = contents.map((_, index) => {
329
325
  const schema = this.normalizeContent(baseSchema, path + index.toString());
330
- utils.mergeSchema(schema.content, mergeContent);
331
- if (schema.id.isEmpty()) {
332
- return ast.addOptionalInformation(this.generateTypeProperty(schema, false), schema, false);
333
- }
334
- else {
335
- return ast.addOptionalInformation(ast.buildTypeReferenceNode(schema, this.currentSchema), schema, false);
326
+ merged.push(utils.mergeSchema(schema.content, mergeContent));
327
+ return schema;
328
+ });
329
+ const allRef = merged.every((b) => !b);
330
+ const baseType = this.checkExistOtherType(mergeContent, baseSchema);
331
+ const result = ast.addOptionalInformation(ast.addComment(ast.buildUnionTypeNode(children, (schema, index) => {
332
+ const node = schema.id.isEmpty()
333
+ ? ast.addOptionalInformation(this.generateTypeProperty(schema, false), schema, false)
334
+ : ast.addOptionalInformation(ast.buildTypeReferenceNode(schema, this.currentSchema), schema, false);
335
+ if (baseType != null && !allRef && !merged[index]) {
336
+ return ast.buildIntersectionTypeNode([baseType, node], false);
336
337
  }
338
+ return node;
337
339
  }, terminate), baseSchema, false), baseSchema, terminate);
340
+ if (baseType != null && allRef) {
341
+ return ast.buildIntersectionTypeNode([baseType, result], terminate);
342
+ }
343
+ return result;
338
344
  }
339
345
  generateArrayTypeProperty(schema, terminate = true) {
340
346
  const items = schema.content.items;
@@ -3,13 +3,13 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.SchemaId = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const config_1 = require("./config");
6
- const dtsGenerator_1 = tslib_1.__importDefault(require("./dtsGenerator"));
6
+ const dtsGenerator_1 = (0, tslib_1.__importDefault)(require("./dtsGenerator"));
7
7
  var schemaId_1 = require("./schemaId");
8
- Object.defineProperty(exports, "SchemaId", { enumerable: true, get: function () { return tslib_1.__importDefault(schemaId_1).default; } });
9
- tslib_1.__exportStar(require("./type"), exports);
8
+ Object.defineProperty(exports, "SchemaId", { enumerable: true, get: function () { return (0, tslib_1.__importDefault)(schemaId_1).default; } });
9
+ (0, tslib_1.__exportStar)(require("./type"), exports);
10
10
  async function dtsGenerator(options) {
11
11
  if (options.config) {
12
- config_1.setConfig(options.config);
12
+ (0, config_1.setConfig)(options.config);
13
13
  }
14
14
  const generator = new dtsGenerator_1.default(options.contents);
15
15
  return await generator.generate();
@@ -2,8 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.selectSchemaType = exports.searchAllSubSchema = exports.setId = exports.getId = exports.getSubSchema = void 0;
4
4
  const tslib_1 = require("tslib");
5
- const JsonPointer = tslib_1.__importStar(require("../jsonPointer"));
6
- const schemaId_1 = tslib_1.__importDefault(require("./schemaId"));
5
+ const JsonPointer = (0, tslib_1.__importStar)(require("../jsonPointer"));
6
+ const schemaId_1 = (0, tslib_1.__importDefault)(require("./schemaId"));
7
7
  const type_1 = require("./type");
8
8
  function getSubSchema(rootSchema, pointer, id) {
9
9
  const content = JsonPointer.get(rootSchema.content, JsonPointer.parse(pointer));
@@ -36,7 +36,7 @@ const Draft04Id = 'id';
36
36
  const Draft07Id = '$id';
37
37
  function getId(type, content) {
38
38
  var _a, _b;
39
- if (type_1.isJsonSchemaDraft04(content, type)) {
39
+ if ((0, type_1.isJsonSchemaDraft04)(content, type)) {
40
40
  return (_a = content[Draft04Id]) !== null && _a !== void 0 ? _a : '';
41
41
  }
42
42
  else {
@@ -46,7 +46,7 @@ function getId(type, content) {
46
46
  exports.getId = getId;
47
47
  function setId(type, content, id) {
48
48
  var _a, _b;
49
- if (type_1.isJsonSchemaDraft04(content, type)) {
49
+ if ((0, type_1.isJsonSchemaDraft04)(content, type)) {
50
50
  (_a = content[Draft04Id]) !== null && _a !== void 0 ? _a : (content[Draft04Id] = id);
51
51
  }
52
52
  else {
@@ -382,6 +382,7 @@ function searchAllSubSchema(schema, onFoundSchema, onFoundReference) {
382
382
  }
383
383
  exports.searchAllSubSchema = searchAllSubSchema;
384
384
  function selectSchemaType(content) {
385
+ var _a;
385
386
  if (typeof content === 'boolean') {
386
387
  return { type: 'Draft07' };
387
388
  }
@@ -389,10 +390,21 @@ function selectSchemaType(content) {
389
390
  throw new Error(`expect parameter of type object, received ${typeof content}`);
390
391
  }
391
392
  if ('$schema' in content) {
392
- const { $schema: schema } = content;
393
- const match = /http:\/\/json-schema\.org\/draft-(\d+)\/schema#?/.exec(schema !== null && schema !== void 0 ? schema : '');
393
+ const schema = (_a = content['$schema']) !== null && _a !== void 0 ? _a : '';
394
+ if (/^https?:\/\/json-schema.org\/schema#?$/.test(schema)) {
395
+ return { type: 'Latest' };
396
+ }
397
+ const match = /^https?:\/\/json-schema\.org\/(?:draft\/(\d{4}-\d{2})|draft-(\d+))\/schema#?$/.exec(schema);
394
398
  if (match) {
395
- const version = Number(match[1]);
399
+ if (match[1] != null) {
400
+ switch (match[1]) {
401
+ case '2019-09':
402
+ return { type: '2019-09' };
403
+ case '2020-12':
404
+ return { type: '2020-12' };
405
+ }
406
+ }
407
+ const version = Number(match[2]);
396
408
  if (version <= 4) {
397
409
  return { type: 'Draft04' };
398
410
  }
@@ -5,7 +5,7 @@ export default class ReferenceResolver {
5
5
  private readonly referenceCache;
6
6
  dereference(refId: string): Schema;
7
7
  getAllRegisteredSchema(): IterableIterator<Schema>;
8
- getAllRegisteredIdAndSchema(): Iterator<[string, Schema]>;
8
+ getAllRegisteredIdAndSchema(): IterableIterator<[string, Schema]>;
9
9
  resolve(): Promise<void>;
10
10
  private searchParentSchema;
11
11
  registerSchema(schema: Schema): void;
@@ -2,11 +2,11 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const tslib_1 = require("tslib");
4
4
  require("cross-fetch/polyfill");
5
- const debug_1 = tslib_1.__importDefault(require("debug"));
5
+ const debug_1 = (0, tslib_1.__importDefault)(require("debug"));
6
6
  const jsonSchema_1 = require("./jsonSchema");
7
- const schemaId_1 = tslib_1.__importDefault(require("./schemaId"));
7
+ const schemaId_1 = (0, tslib_1.__importDefault)(require("./schemaId"));
8
8
  const type_1 = require("./type");
9
- const debug = debug_1.default('dtsgen');
9
+ const debug = (0, debug_1.default)('dtsgen');
10
10
  class ReferenceResolver {
11
11
  constructor() {
12
12
  this.schemaCache = new Map();
@@ -41,7 +41,7 @@ class ReferenceResolver {
41
41
  if (refSchema == null && id.isFetchable()) {
42
42
  try {
43
43
  debug(`fetch remote schema: id=[${fileId}].`);
44
- const s = await type_1.readSchemaFromUrl(fileId);
44
+ const s = await (0, type_1.readSchemaFromUrl)(fileId);
45
45
  this.registerSchema(s);
46
46
  }
47
47
  catch (e) {
@@ -62,7 +62,7 @@ class ReferenceResolver {
62
62
  error.push(`The $ref targets root is not found: ${id.getAbsoluteId()}`);
63
63
  continue;
64
64
  }
65
- const targetSchema = jsonSchema_1.getSubSchema(rootSchema, id.getJsonPointerHash(), id);
65
+ const targetSchema = (0, jsonSchema_1.getSubSchema)(rootSchema, id.getJsonPointerHash(), id);
66
66
  this.addSchema(targetSchema);
67
67
  this.registerSchema(targetSchema);
68
68
  this.referenceCache.set(id.getAbsoluteId(), targetSchema);
@@ -96,7 +96,7 @@ class ReferenceResolver {
96
96
  }
97
97
  registerSchema(schema) {
98
98
  debug(`register schema: schemaId=[${schema.id.getAbsoluteId()}].`);
99
- jsonSchema_1.searchAllSubSchema(schema, (subSchema) => {
99
+ (0, jsonSchema_1.searchAllSubSchema)(schema, (subSchema) => {
100
100
  this.addSchema(subSchema);
101
101
  }, (refId) => {
102
102
  this.addReference(refId);
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const tslib_1 = require("tslib");
4
- const url = tslib_1.__importStar(require("url"));
4
+ const url = (0, tslib_1.__importStar)(require("url"));
5
5
  const validateIdentifier_1 = require("./validateIdentifier");
6
6
  class SchemaId {
7
7
  constructor(inputId, parentIds) {
@@ -7,7 +7,7 @@ import SchemaId from './schemaId';
7
7
  export import ts = require('typescript');
8
8
  export declare type JsonSchema = JsonSchemaDraft04.Schema | JsonSchemaDraft07.Schema;
9
9
  export declare type JsonSchemaObject = JsonSchemaDraft04.Schema | JsonSchemaDraft07.SchemaObject;
10
- export declare type SchemaType = 'Draft04' | 'Draft07';
10
+ export declare type SchemaType = 'Draft04' | 'Draft07' | '2019-09' | '2020-12' | 'Latest';
11
11
  export declare function isJsonSchemaDraft04(_content: JsonSchemaObject, type: SchemaType): _content is JsonSchemaDraft04.Schema;
12
12
  export declare type $Ref = OpenApisV3.SchemaJson.Definitions.Reference | OpenApisV2.SchemaJson.Definitions.JsonReference;
13
13
  export interface Schema {
@@ -24,7 +24,7 @@ export declare function readSchemaFromUrl(url: string): Promise<Schema>;
24
24
  export declare function parseFileContent(content: string, filename?: string): JsonSchema;
25
25
  export interface PluginContext {
26
26
  option: boolean | Record<string, unknown>;
27
- inputSchemas: Iterator<[string, Schema]>;
27
+ inputSchemas: IterableIterator<[string, Schema]>;
28
28
  }
29
29
  export declare type PreProcessHandler = (contents: Schema[]) => Schema[];
30
30
  export declare type Plugin = {
package/dist/core/type.js CHANGED
@@ -2,25 +2,25 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.loadPlugin = exports.parseFileContent = exports.readSchemaFromUrl = exports.readSchemasFromFile = exports.readSchemaFromStdin = exports.parseSchema = exports.isJsonSchemaDraft04 = void 0;
4
4
  const tslib_1 = require("tslib");
5
- const fs = tslib_1.__importStar(require("fs"));
5
+ const fs = (0, tslib_1.__importStar)(require("fs"));
6
6
  const path_1 = require("path");
7
7
  const js_yaml_1 = require("js-yaml");
8
8
  const utils_1 = require("../utils");
9
9
  const jsonSchema_1 = require("./jsonSchema");
10
- const schemaId_1 = tslib_1.__importDefault(require("./schemaId"));
10
+ const schemaId_1 = (0, tslib_1.__importDefault)(require("./schemaId"));
11
11
  exports.ts = require("typescript");
12
12
  function isJsonSchemaDraft04(_content, type) {
13
13
  return type === 'Draft04';
14
14
  }
15
15
  exports.isJsonSchemaDraft04 = isJsonSchemaDraft04;
16
16
  function parseSchema(content, url) {
17
- const { type, openApiVersion } = jsonSchema_1.selectSchemaType(content);
17
+ const { type, openApiVersion } = (0, jsonSchema_1.selectSchemaType)(content);
18
18
  let id;
19
19
  if (typeof content !== 'boolean') {
20
20
  if (url != null) {
21
- jsonSchema_1.setId(type, content, url);
21
+ (0, jsonSchema_1.setId)(type, content, url);
22
22
  }
23
- id = jsonSchema_1.getId(type, content);
23
+ id = (0, jsonSchema_1.getId)(type, content);
24
24
  }
25
25
  return {
26
26
  type,
@@ -31,13 +31,13 @@ function parseSchema(content, url) {
31
31
  }
32
32
  exports.parseSchema = parseSchema;
33
33
  async function readSchemaFromStdin() {
34
- const data = await utils_1.readStream(process.stdin);
34
+ const data = await (0, utils_1.readStream)(process.stdin);
35
35
  const content = parseFileContent(data);
36
36
  return parseSchema(content);
37
37
  }
38
38
  exports.readSchemaFromStdin = readSchemaFromStdin;
39
39
  async function readSchemasFromFile(pattern) {
40
- const files = await utils_1.globFiles(pattern);
40
+ const files = await (0, utils_1.globFiles)(pattern);
41
41
  return Promise.all(files.map(async (file) => {
42
42
  const data = await fs.promises.readFile(file, {
43
43
  encoding: 'utf8',
@@ -48,17 +48,17 @@ async function readSchemasFromFile(pattern) {
48
48
  }
49
49
  exports.readSchemasFromFile = readSchemasFromFile;
50
50
  async function readSchemaFromUrl(url) {
51
- const data = await utils_1.readUrl(url);
51
+ const data = await (0, utils_1.readUrl)(url);
52
52
  const content = parseFileContent(data, url);
53
53
  return parseSchema(content, url);
54
54
  }
55
55
  exports.readSchemaFromUrl = readSchemaFromUrl;
56
56
  function parseFileContent(content, filename) {
57
- const ext = filename ? path_1.extname(filename).toLowerCase() : '';
57
+ const ext = filename ? (0, path_1.extname)(filename).toLowerCase() : '';
58
58
  const maybeYaml = ext === '.yaml' || ext === '.yml';
59
59
  try {
60
60
  if (maybeYaml) {
61
- return deepCopy(js_yaml_1.load(content));
61
+ return deepCopy((0, js_yaml_1.load)(content));
62
62
  }
63
63
  else {
64
64
  return JSON.parse(content);
@@ -69,7 +69,7 @@ function parseFileContent(content, filename) {
69
69
  return JSON.parse(content);
70
70
  }
71
71
  else {
72
- return deepCopy(js_yaml_1.load(content));
72
+ return deepCopy((0, js_yaml_1.load)(content));
73
73
  }
74
74
  }
75
75
  }
@@ -81,7 +81,7 @@ async function loadPlugin(name, option) {
81
81
  if (!option) {
82
82
  return undefined;
83
83
  }
84
- const mod = (await Promise.resolve().then(() => tslib_1.__importStar(require(name))));
84
+ const mod = (await Promise.resolve().then(() => (0, tslib_1.__importStar)(require(name))));
85
85
  if (!(mod === null || mod === void 0 ? void 0 : mod.default)) {
86
86
  console.warn(`The plugin (${name}) is invalid module. That is not default export format.`);
87
87
  return undefined;
@@ -0,0 +1,6 @@
1
+ import { Schema } from './type';
2
+ export interface TypeTree {
3
+ children: Map<string, TypeTree>;
4
+ schema?: Schema;
5
+ }
6
+ export declare function buildTypeTree(schemas: IterableIterator<Schema>): TypeTree;
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildTypeTree = void 0;
4
+ function buildTypeTree(schemas) {
5
+ const tree = buildTree();
6
+ for (const type of schemas) {
7
+ setTypeToTree(tree, type.id.toNames(), type);
8
+ }
9
+ if (tree.children.size === 0) {
10
+ throw new Error('There is no schema in the input contents.');
11
+ }
12
+ return tree;
13
+ }
14
+ exports.buildTypeTree = buildTypeTree;
15
+ function setTypeToTree(tree, paths, type) {
16
+ if (paths.length === 0) {
17
+ throw new Error('The paths is nothing for set the type to TypeTree.');
18
+ }
19
+ let t = tree;
20
+ for (const key of paths) {
21
+ let next = t.children.get(key);
22
+ if (next === undefined) {
23
+ next = buildTree();
24
+ t.children.set(key, next);
25
+ }
26
+ t = next;
27
+ }
28
+ t.schema = type;
29
+ }
30
+ function buildTree() {
31
+ return {
32
+ children: new Map(),
33
+ };
34
+ }
@@ -4,4 +4,4 @@ import { JsonSchemaObject } from './type';
4
4
  import SimpleTypes = JsonSchemaDraft04.Schema.Definitions.SimpleTypes;
5
5
  export declare function toTSType(type: string, debugSource?: JsonSchemaObject): ts.KeywordTypeSyntaxKind | ts.SyntaxKind.NullKeyword | undefined;
6
6
  export declare function reduceTypes(types: SimpleTypes[]): SimpleTypes[];
7
- export declare function mergeSchema(a: any, b: any): any;
7
+ export declare function mergeSchema(a: any, b: any): boolean;
@@ -2,9 +2,9 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.mergeSchema = exports.reduceTypes = exports.toTSType = void 0;
4
4
  const tslib_1 = require("tslib");
5
- const debug_1 = tslib_1.__importDefault(require("debug"));
6
- const ts = tslib_1.__importStar(require("typescript"));
7
- const debug = debug_1.default('dtsgen');
5
+ const debug_1 = (0, tslib_1.__importDefault)(require("debug"));
6
+ const ts = (0, tslib_1.__importStar)(require("typescript"));
7
+ const debug = (0, debug_1.default)('dtsgen');
8
8
  function toTSType(type, debugSource) {
9
9
  switch (type) {
10
10
  case 'any':
@@ -39,18 +39,16 @@ function reduceTypes(types) {
39
39
  return types;
40
40
  }
41
41
  const set = new Set(types);
42
- if (set.delete('integer')) {
43
- set.add('number');
44
- }
45
42
  return Array.from(set.values());
46
43
  }
47
44
  exports.reduceTypes = reduceTypes;
48
45
  function mergeSchema(a, b) {
49
46
  if ('$ref' in a || '$ref' in b) {
50
- return { $ref: b['$ref'] || a['$ref'] };
47
+ a.$ref = b.$ref || a.$ref;
48
+ return false;
51
49
  }
52
50
  Object.keys(b).forEach((key) => {
53
- var _a;
51
+ var _a, _b;
54
52
  const value = b[key];
55
53
  if (a[key] != null && typeof value !== typeof a[key]) {
56
54
  debug(`mergeSchema warning: type is mismatched, key=${key}`);
@@ -59,12 +57,13 @@ function mergeSchema(a, b) {
59
57
  a[key] = ((_a = a[key]) !== null && _a !== void 0 ? _a : []).concat(value);
60
58
  }
61
59
  else if (value != null && typeof value === 'object') {
62
- a[key] = mergeSchema(a[key] || {}, value);
60
+ (_b = a[key]) !== null && _b !== void 0 ? _b : (a[key] = {});
61
+ mergeSchema(a[key], value);
63
62
  }
64
63
  else {
65
64
  a[key] = value;
66
65
  }
67
66
  });
68
- return a;
67
+ return true;
69
68
  }
70
69
  exports.mergeSchema = mergeSchema;
package/dist/utils.d.ts CHANGED
@@ -1,5 +1,9 @@
1
1
  /// <reference types="node" />
2
2
  import glob from 'glob';
3
- export declare function readStream(stream: NodeJS.ReadStream, encoding?: BufferEncoding): Promise<string>;
3
+ import { CommandOptions } from './commandOptions';
4
+ import { Config } from './core/config';
5
+ export declare function readStream(stream: NodeJS.ReadableStream, encoding?: BufferEncoding): Promise<string>;
4
6
  export declare function readUrl(url: string): Promise<string>;
7
+ export declare function buildProxyOptions(url: string): RequestInit | undefined;
5
8
  export declare function globFiles(pattern: string, options?: glob.IOptions): Promise<string[]>;
9
+ export declare function readConfig(options: CommandOptions): Partial<Config>;