/
json-schema-type-util.ts
340 lines (287 loc) · 9.55 KB
/
json-schema-type-util.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
import type { ExtendedJsonSchema } from './typing/generic-node-type'
import { zodScripts } from './generic-node-constants'
import { FetchingJSONSchemaStore, InputData, JSONSchemaInput, quicktype } from '../../module-src/module-wrappers'
import { logKibana } from '../../util/log'
import {
Diagnostic, ScriptKind, ScriptTarget, TypeFormatFlags, createCompilerHost, createProgram, createSourceFile,
factory, getPreEmitDiagnostics, isExpressionStatement, isTypeAliasDeclaration, Node
} from 'typescript'
import { generateSchema, buildGenerator } from 'typescript-json-schema'
import type * as z from "zod"
import { v4 } from "uuid"
import type { JSONSchema6Definition } from 'json-schema'
import { join, dirname } from "path"
import { writeFile, mkdir, rm } from "fs/promises"
declare module "typescript" {
export interface SourceFile {
getNamedDeclarations(): Map<string, Array<Node>>
}
}
export const expansionType = `
type ExpandRecursively<T> = T extends Date
? T
: T extends object
? T extends infer O ? { [K in keyof O]: ExpandRecursively<O[K]> } : never
: T;
`
export function typeMerge(newType: string, oldType: string, mainInterfaceName: string) {
const source = createSourceFile("text.ts", `
type ExpandRecursively<T> = T extends object
? T extends infer O ? { [K in keyof O]: ExpandRecursively<O[K]> } : never
: T;
declare namespace Previous{
${oldType}
}
declare namespace Current{
${newType}
}
type result=ExpandRecursively<(Previous.${mainInterfaceName}|Current.${mainInterfaceName})>;
`, ScriptTarget.Latest, true, ScriptKind.TS)
const compilerHost = createCompilerHost({})
const getSoruce = compilerHost.getSourceFile
compilerHost.getSourceFile = (file, l, onError, createNew) => {
if (file == "text.ts") {
return source
}
return getSoruce(file, l, onError, createNew)
}
const p = createProgram(["text.ts"], { declaration: true, target: ScriptTarget.Latest }, compilerHost)
const typeChecker = p.getTypeChecker();
const mainStatement = source.getNamedDeclarations().get("result")?.[0]
if (mainStatement && isTypeAliasDeclaration(mainStatement)) {
const typenode = typeChecker.getTypeFromTypeNode(mainStatement.type)
// const resultType = typeChecker.getTypeAtLocation(mainStatement)
const typeAsString = typeChecker.typeToString(typenode, factory.createTypeLiteralNode([]), TypeFormatFlags.InTypeAlias)
console.log(typeAsString);
return typeAsString
} else {
throw new Error("invalid string")
}
}
function canDoSchema(jsonSchema: ExtendedJsonSchema | (JSONSchema6Definition & object)) {
if (jsonSchema.type == "object") {
return true
} else if (jsonSchema.type == "string" && (jsonSchema.enum?.length || jsonSchema.const)) {
return true
} else if (jsonSchema.type == "string") {
return false
} else if (jsonSchema.type == "boolean") {
return false
} else if (jsonSchema.type == "number") {
return false
} else if (jsonSchema.anyOf) {
return true
} else if (jsonSchema.$ref) {
return true
}
debugger
return true
}
export async function generateDtsFromSchema(jsonSchema: ExtendedJsonSchema | (JSONSchema6Definition & object), traceId?: string) {
if (traceId) {
console.log("creating schema for " + traceId)
} else {
logKibana("WARN", "missing traceid for call")
}
let wrapper = false
if (!canDoSchema(jsonSchema)) {
wrapper = true
jsonSchema = {
type: "object",
properties: {
wrapper: jsonSchema
},
required: ["wrapper"],
additionalProperties: false
}
}
const definistionStr = ""
/*if (jsonSchema.definitions) {
for (const def in jsonSchema.definitions) {
jsonSchema.definitions[def]
definistionStr = `${definistionStr}
${await generateDtsFromSchema(jsonSchema.definitions[def] as ExtendedJsonSchema)}
`
}
}*/
const schemaInput = new JSONSchemaInput(new FetchingJSONSchemaStore());
await schemaInput.addSource({ name: mainTypeName, schema: JSON.stringify(jsonSchema) });
const inputData = new InputData();
inputData.addInput(schemaInput);
const quicktyped = await quicktype({
inputData,
lang: "ts",
inferDateTimes: true,
allPropertiesOptional: false,
ignoreJsonRefs: false,
rendererOptions: {
'just-types': 'true',
"prefer-unions": true,
// "prefer-const-values": true "Use string instead of enum for string enums with single value",
//'explicit-unions': 'true',
//'acronym-style': 'camel',
}
});
const lines = quicktyped.lines;
if (wrapper) {
lines[0] = ""
lines[1] = lines[1].replace(/wrapper: ([^;]*);/, `export type ${mainTypeName} = $1;`).trim()
lines[2] = ""
return `
${lines.join("\n")}
`.trim()
}
const str = lines.join("\n").trim()
return str
}
export function programFromSource(name: string, source: string) {
const tsSourceFile = createSourceFile(name, source, ScriptTarget.Latest)
const host = createCompilerHost({
})
const program = createProgram([name], {
}, {
...host,
getSourceFile(file, ...args) {
if (file === name) {
return tsSourceFile
}
return host.getSourceFile(file, ...args)
}
})
return { program, tsSourceFile }
}
export class CompilerError extends Error {
constructor(message: string, public error_diagnostics: Array<Omit<Diagnostic, "file">>) {
super(message)
}
}
export function postfix(schema: ExtendedJsonSchema) {
if (!schema.$ref && schema.type == "object") {
schema.additionalProperties = false
}
if (schema.properties) {
for (const prop in schema.properties) {
const sub = schema.properties[prop]
if (typeof sub == "object") {
postfix(sub)
}
}
}
if (schema.definitions) {
for (const prop in schema.definitions) {
const sub = schema.definitions[prop]
if (typeof sub == "object") {
postfix(sub)
}
}
}
}
export function allRequired(schema: ExtendedJsonSchema) {
if (!schema.$ref && schema.type == "object") {
schema.required = Object.keys(schema.properties ?? {})
}
if (schema.properties) {
for (const prop in schema.properties) {
const sub = schema.properties[prop]
if (typeof sub == "object") {
allRequired(sub)
}
}
}
if (schema.definitions) {
for (const prop in schema.definitions) {
const sub = schema.definitions[prop]
if (typeof sub == "object") {
allRequired(sub)
}
}
}
}
export function generateJsonSchemaFromDts(dts: string, mainType: string | boolean, traceId: string) {
if (traceId) {
console.log("creating jscon schema from dts for " + traceId)
} else {
logKibana("WARN", "missing traceid for call")
}
const program = programFromSource("text.ts", `
${dts}
`)
const emitResults = getPreEmitDiagnostics(program.program)
if (emitResults.length) {
const jsonSafeResults = emitResults
.map(r => ({ ...r, file: null }))
throw new CompilerError("typescript compiler error while generating schema", jsonSafeResults)
}
if (typeof mainType == "boolean") {
const gnerator = buildGenerator(program.program, {
ref: false
})
const typeChecker = program.program.getTypeChecker()
let statement: Node = program.tsSourceFile.statements[program.tsSourceFile.statements.length - 1]
if (isExpressionStatement(statement)) {
statement = statement.expression
}
const typeDecl = typeChecker.getTypeAtLocation(statement)
//@ts-ignore
const generated = gnerator?.getTypeDefinition(typeDecl, false, undefined, undefined, undefined, undefined, true) as ExtendedJsonSchema;
//@ts-ignore
generated.definitions = gnerator?.reffedDefinitions
postfix(generated)
return generated as ExtendedJsonSchema
}
const schema = generateSchema(program.program, mainType, {
//required: true, constAsEnum: true, noExtraProps: true,
}, ["test.ts"])
if (schema) {
postfix(schema as ExtendedJsonSchema)
return schema as ExtendedJsonSchema
}
throw new Error("didnt get a schema")
}
export const mainTypeName = "Main"
export async function generateZodTypeFromSchema(jsonSchema: ExtendedJsonSchema, traceId?: string) {
if (traceId) {
console.log("creating zod schema for " + traceId)
} else {
logKibana("WARN", "missing traceid for call")
}
let wrapper = false
if (!canDoSchema(jsonSchema)) {
wrapper = true
jsonSchema = {
type: "object",
properties: {
wrapper: jsonSchema
},
required: ["wrapper"],
additionalProperties: false
}
}
const schemaInput = new JSONSchemaInput(new FetchingJSONSchemaStore());
await schemaInput.addSource({ name: mainTypeName, schema: JSON.stringify(jsonSchema) });
const inputData = new InputData();
inputData.addInput(schemaInput);
const quicktyped = await quicktype({
inputData,
lang: "typescript-zod",
inferDateTimes: true,
allPropertiesOptional: false,
rendererOptions: {
'just-types': 'true',
"prefer-unions": true,
"prefer-const-values": true
}
});
const lines = quicktyped.lines;
const str = lines.join("\n").trim()
const target = join(zodScripts, v4() + ".ts");
await mkdir(dirname(target), { recursive: true })
await writeFile(target, str)
const module = require(target)
rm(target)
const zodValidator = module[`${mainTypeName}Schema`] as z.ZodObject<{ wrapper: never }>
if (wrapper) {
return zodValidator.shape.wrapper as z.ZodObject<never>
}
return zodValidator as z.ZodObject<never>
}