Skip to content

Commit

Permalink
Merge 5a7010c into 415ba4b
Browse files Browse the repository at this point in the history
  • Loading branch information
horiuchi committed Dec 8, 2021
2 parents 415ba4b + 5a7010c commit 0a1670a
Show file tree
Hide file tree
Showing 11 changed files with 2,811 additions and 3,402 deletions.
6,059 changes: 2,729 additions & 3,330 deletions package-lock.json

Large diffs are not rendered by default.

30 changes: 15 additions & 15 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,37 +44,37 @@
"node": ">= 10.0"
},
"dependencies": {
"commander": "^8.2.0",
"commander": "^8.3.0",
"cross-fetch": "^3.1.4",
"debug": "^4.3.2",
"debug": "^4.3.3",
"glob": "^7.2.0",
"https-proxy-agent": "^5.0.0",
"js-yaml": "^4.1.0",
"tslib": "^2.3.1",
"typescript": "^4.4.3"
"typescript": "^4.5.2"
},
"devDependencies": {
"@dtsgenerator/do-nothing": "^2.5.1",
"@dtsgenerator/eslint-config": "^0.4.0",
"@dtsgenerator/eslint-config": "^0.5.0",
"@dtsgenerator/replace-namespace": "^1.5.1",
"@dtsgenerator/single-quote": "^1.6.1",
"@istanbuljs/nyc-config-typescript": "^1.0.1",
"@istanbuljs/nyc-config-typescript": "^1.0.2",
"@types/debug": "^4.1.7",
"@types/glob": "^7.1.4",
"@types/js-yaml": "^4.0.3",
"@types/glob": "^7.2.0",
"@types/js-yaml": "^4.0.5",
"@types/mkdirp": "^1.0.2",
"@types/mocha": "^9.0.0",
"@types/node": "^16.10.3",
"@types/node": "^16.11.12",
"cross-env": "^7.0.3",
"eslint": "^7.32.0",
"husky": "^7.0.2",
"lint-staged": "^11.2.0",
"mocha": "^9.1.2",
"eslint": "^8.4.1",
"husky": "^7.0.4",
"lint-staged": "^12.1.2",
"mocha": "^9.1.3",
"nyc": "^15.1.0",
"prettier": "^2.4.1",
"prettier": "^2.5.1",
"rimraf": "^3.0.2",
"source-map-support": "^0.5.20",
"ts-node": "^10.2.1"
"source-map-support": "^0.5.21",
"ts-node": "^10.4.0"
},
"lint-staged": {
"**/*.ts": [
Expand Down
2 changes: 1 addition & 1 deletion src/commandOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ function parse(options: CommandOptions, argv: string[]): commander.Command {
}

// eslint-disable-next-line @typescript-eslint/no-var-requires,@typescript-eslint/no-unsafe-assignment
const pkg: Record<string, any> = require('../package.json');
const pkg: Record<string, string> = require('../package.json');

// <hoge> is required, [hoge] is optional
program
Expand Down
2 changes: 1 addition & 1 deletion src/core/astBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@ function getComment(schema: NormalizedSchema): string[] {
function protectComment(str: string): string {
return str.replace(/\*\//g, '*\u200B/'); // Unicode [ZERO WIDTH SPACE]
}
function appendComment(value?: string): void {
function appendComment(value?: any): void {
if (value == null) {
return;
}
Expand Down
60 changes: 15 additions & 45 deletions src/core/dtsGenerator.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Debug from 'debug';
import * as ts from 'typescript';
import { get, set, tilde } from '../jsonPointer';
import { tilde } from '../jsonPointer';
import * as ast from './astBuilder';
import config from './config';
import { getSubSchema, NormalizedSchema } from './jsonSchema';
Expand All @@ -13,10 +13,10 @@ import {
PreProcessHandler,
loadPlugin,
} from './type';
import { buildTypeTree, TypeTree } from './typeTree';
import * as utils from './utils';

const debug = Debug('dtsgen');
const typeMarker = Symbol();

interface PluginConfig {
plugin: Plugin;
Expand All @@ -42,11 +42,8 @@ export default class DtsGenerator {
this.contents.forEach((schema) => this.resolver.registerSchema(schema));
await this.resolver.resolve();

// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const map = this.buildSchemaMergedMap(
this.resolver.getAllRegisteredSchema()
);
const root = this.walk(map, true);
const tree = buildTypeTree(this.resolver.getAllRegisteredSchema());
const root = this.walk(tree);
const file = ts.createSourceFile(
'_.d.ts',
'',
Expand Down Expand Up @@ -77,31 +74,6 @@ export default class DtsGenerator {
return transformedContent;
}

private buildSchemaMergedMap(schemas: IterableIterator<Schema>): any {
const map: any = {};
const paths: { path: string[]; type: Schema }[] = [];
for (const type of schemas) {
const path = type.id.toNames();
paths.push({ path, type });
}

for (const item of paths) {
const path = item.path;
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const parent = get(map, path, true);
if (parent == null) {
set(map, path, { [typeMarker]: item.type });
} else {
Object.assign(parent, { [typeMarker]: item.type });
}
}
if (Object.keys(map).length === 0) {
throw new Error('There is no schema in the input contents.');
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return map;
}

private async getPlugins(): Promise<{
pre: PluginConfig[];
post: PluginConfig[];
Expand Down Expand Up @@ -169,24 +141,22 @@ export default class DtsGenerator {
return result;
}

private walk(map: any, root: boolean): ts.Statement[] {
private walk(tree: TypeTree, root = true): ts.Statement[] {
const result: ts.Statement[] = [];
const keys = Object.keys(map).sort();
const keys = [...tree.children.keys()].sort();
for (const key of keys) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
const value = map[key];
if (
typeof value === 'object' &&
Object.prototype.hasOwnProperty.call(value, typeMarker)
) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
const schema = value[typeMarker] as Schema;
const value = tree.children.get(key);
if (value === undefined) {
continue;
}
if (value.schema !== undefined) {
const schema = value.schema;
debug(
` walk doProcess: key=${key} schemaId=${schema.id.getAbsoluteId()}`
);
result.push(this.walkSchema(schema, root));
}
if (typeof value === 'object' && Object.keys(value).length > 0) {
if (value.children.size > 0) {
result.push(
ast.buildNamespaceNode(key, this.walk(value, false), root)
);
Expand Down Expand Up @@ -458,11 +428,11 @@ export default class DtsGenerator {
case 'number':
return ast.buildNumericLiteralTypeNode(String(value));
case 'boolean':
return ast.buildBooleanLiteralTypeNode(value);
return ast.buildBooleanLiteralTypeNode(Boolean(value));
case 'null':
return ast.buildNullKeyword();
case 'string':
return ast.buildStringLiteralTypeNode(value);
return ast.buildStringLiteralTypeNode(String(value));
}
if (value === null) {
return ast.buildNullKeyword();
Expand Down
39 changes: 39 additions & 0 deletions src/core/typeTree.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { Schema } from './type';

export interface TypeTree {
children: Map<string, TypeTree>;
schema?: Schema;
}

export function buildTypeTree(schemas: IterableIterator<Schema>): TypeTree {
const tree: TypeTree = buildTree();
for (const type of schemas) {
setTypeToTree(tree, type.id.toNames(), type);
}
if (tree.children.size === 0) {
throw new Error('There is no schema in the input contents.');
}
return tree;
}

function setTypeToTree(tree: TypeTree, paths: string[], type: Schema): void {
if (paths.length === 0) {
throw new Error('The paths is nothing for set the type to TypeTree.');
}
let t: TypeTree = tree;
for (const key of paths) {
let next = t.children.get(key);
if (next === undefined) {
next = buildTree();
t.children.set(key, next);
}
t = next;
}
t.schema = type;
}

function buildTree(): TypeTree {
return {
children: new Map(),
};
}
2 changes: 1 addition & 1 deletion src/core/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export function mergeSchema(a: any, b: any): any {
if ('$ref' in a || '$ref' in b) {
return { $ref: b['$ref'] || a['$ref'] };
}
Object.keys(b).forEach((key: string) => {
Object.keys(b as object).forEach((key: string) => {
const value = b[key];
if (a[key] != null && typeof value !== typeof a[key]) {
debug(`mergeSchema warning: type is mismatched, key=${key}`);
Expand Down
3 changes: 2 additions & 1 deletion test/core/jsonSchema_test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import assert from 'assert';
import { JsonSchema } from '../../src/core';
import { selectSchemaType } from '../../src/core/jsonSchema';

describe('selectSchemaType test', () => {
Expand Down Expand Up @@ -90,7 +91,7 @@ describe('selectSchemaType test', () => {
});
it('schema is invalid', () => {
assert.throws(() => {
selectSchemaType('invalid schema' as any);
selectSchemaType('invalid schema' as JsonSchema);
});
});
});
10 changes: 5 additions & 5 deletions test/error_case_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,10 @@ describe('error schema test', () => {
}
});
it('unknown type schema', async () => {
const schema: any = {
const schema: JsonSchemaDraft04.Schema = {
id: '/test/unknown_type',
type: 'hoge',
};
} as any;
try {
await dtsgenerator({ contents: [parseSchema(schema)] });
assert.fail();
Expand All @@ -38,15 +38,15 @@ describe('error schema test', () => {
}
});
it('unknown type property', async () => {
const schema: any = {
const schema: JsonSchemaDraft04.Schema = {
id: '/test/unknown_property',
type: 'object',
properties: {
name: {
type: 'fuga',
},
},
};
} as any;
try {
await dtsgenerator({ contents: [parseSchema(schema)] });
assert.fail();
Expand Down Expand Up @@ -99,7 +99,7 @@ describe('error schema test', () => {
}
});
it('invalid format schema', async () => {
const schema =
const schema: JsonSchemaDraft04.Schema =
'This string is not schema data and invalid JSON format {.' as any;
try {
await dtsgenerator({ contents: [parseSchema(schema)] });
Expand Down
4 changes: 2 additions & 2 deletions test/snapshot_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import assert from 'assert';
import fs from 'fs';
import path from 'path';
import dtsgenerator from '../src/core';
import { clearToDefault, setConfig } from '../src/core/config';
import { clearToDefault, Config, setConfig } from '../src/core/config';
import { parseFileContent, parseSchema } from '../src/core/type';

const fixturesDir = path.join(__dirname, 'snapshots');
Expand All @@ -26,7 +26,7 @@ describe('Snapshot testing', () => {
expectedFileName
);
const configFilePath = path.join(fixtureDir, configFileName);
const config = fs.existsSync(configFilePath)
const config: Partial<Config> = fs.existsSync(configFilePath)
? require(configFilePath)
: {};

Expand Down
2 changes: 1 addition & 1 deletion test/utils_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ describe('root utils test', () => {
]);
});
it('throw error on getting files', () => {
assert.rejects(() => globFiles(null as any));
assert.rejects(() => globFiles(null as unknown as string));
});
});

Expand Down

0 comments on commit 0a1670a

Please sign in to comment.