-
Notifications
You must be signed in to change notification settings - Fork 413
Expand file tree
/
Copy pathvalidate.ts
More file actions
103 lines (93 loc) · 4.51 KB
/
Copy pathvalidate.ts
File metadata and controls
103 lines (93 loc) · 4.51 KB
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
import ts from 'typescript';
import { Result, success, error } from '../result';
import { JsonSchemaOptions, TypeChatJsonValidator } from "../typechat";
import { tsToJsonSchema } from './ast';
const libText = `interface Array<T> { length: number, [n: number]: T }
interface Object { toString(): string }
interface Function { prototype: unknown }
interface CallableFunction extends Function {}
interface NewableFunction extends Function {}
interface String { readonly length: number }
interface Boolean { valueOf(): boolean }
interface Number { valueOf(): number }
interface RegExp { test(string: string): boolean }`;
/**
* Represents an object that can validate JSON strings according to a given TypeScript schema.
*/
export interface TypeScriptJsonValidator<T extends object> extends TypeChatJsonValidator<T> {
/**
* Transform JSON into TypeScript code for validation. Returns a `Success<string>` object if the conversion is
* successful, or an `Error` object if the JSON can't be transformed. The returned TypeScript source code is
* expected to be an ECMAScript module that imports one or more types from `"./schema"` and combines those
* types and a representation of the JSON object in a manner suitable for type-checking by the TypeScript compiler.
*/
createModuleTextFromJson(jsonObject: object): Result<string>;
}
/**
* Returns a JSON validator for a given TypeScript schema. Validation is performed by an in-memory instance of
* the TypeScript compiler. The specified type argument `T` must be the same type as `typeName` in the given `schema`.
* @param schema A string containing the TypeScript source code for the JSON schema.
* @param typeName The name of the JSON target type in the schema.
* @returns A `TypeChatJsonValidator<T>` instance.
*/
export function createTypeScriptJsonValidator<T extends object = object>(schema: string, typeName: string): TypeScriptJsonValidator<T> {
const options = {
...ts.getDefaultCompilerOptions(),
strict: true,
skipLibCheck: true,
noLib: true,
types: []
};
const rootProgram = createProgramFromModuleText("");
const validator: TypeScriptJsonValidator<T> = {
getSchemaText: () => schema,
getTypeName: () => typeName,
createModuleTextFromJson,
getJsonSchema,
validate
};
return validator;
function getJsonSchema(options?: JsonSchemaOptions) {
const program = createProgramFromModuleText("", rootProgram);
return tsToJsonSchema(program, options);
}
function validate(jsonObject: object) {
const moduleResult = validator.createModuleTextFromJson(jsonObject);
if (!moduleResult.success) {
return moduleResult;
}
const program = createProgramFromModuleText(moduleResult.data, rootProgram);
const syntacticDiagnostics = program.getSyntacticDiagnostics();
const programDiagnostics = syntacticDiagnostics.length ? syntacticDiagnostics : program.getSemanticDiagnostics();
if (programDiagnostics.length) {
const diagnostics = programDiagnostics.map(d => typeof d.messageText === "string" ? d.messageText : d.messageText.messageText).join("\n");
return error(diagnostics);
}
return success(jsonObject as T);
}
function createModuleTextFromJson(jsonObject: object) {
return success(`import { ${typeName} } from './schema';\nconst json: ${typeName} = ${JSON.stringify(jsonObject, undefined, 2)};\n`);
}
function createProgramFromModuleText(moduleText: string, oldProgram?: ts.Program) {
const fileMap = new Map([
createFileMapEntry("/lib.d.ts", libText),
createFileMapEntry("/schema.ts", schema),
createFileMapEntry("/json.ts", moduleText)
]);
const host: ts.CompilerHost = {
getSourceFile: fileName => fileMap.get(fileName),
getDefaultLibFileName: () => "lib.d.ts",
writeFile: () => {},
getCurrentDirectory: () => "/",
getCanonicalFileName: fileName => fileName,
useCaseSensitiveFileNames: () => true,
getNewLine: () => "\n",
fileExists: fileName => fileMap.has(fileName),
readFile: fileName => "",
};
return ts.createProgram(Array.from(fileMap.keys()), options, host, oldProgram);
}
function createFileMapEntry(filePath: string, fileText: string): [string, ts.SourceFile] {
return [filePath, ts.createSourceFile(filePath, fileText, ts.ScriptTarget.Latest)];
}
}