-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetValueValidation.ts
More file actions
48 lines (39 loc) · 1.86 KB
/
Copy pathgetValueValidation.ts
File metadata and controls
48 lines (39 loc) · 1.86 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
import ts from "typescript";
import {DataType, LiteralValue} from "@code0-tech/sagittarius-graphql-types";
import {createCompilerHost, getSharedTypeDeclarations, ValidationResult} from "../utils";
import { stringify } from 'lossless-json'
export const getValueValidation = (
type?: string,
value?: LiteralValue,
dataTypes?: DataType[]
): ValidationResult => {
const jsonString = stringify(value?.value)
// 1. Construct the source code for validation.
const sourceCode = `
${getSharedTypeDeclarations(dataTypes)}
const testValue: ${type} = ${jsonString};
`;
const fileName = "index.ts";
const compilerHost = createCompilerHost(fileName, sourceCode);
const diagnostics = compilerHost.languageService.getSemanticDiagnostics(fileName);
const errors = diagnostics.map(d => {
const message = ts.flattenDiagnosticMessageText(d.messageText, "\n");
// Generic placeholders like T, R, K, V are often warnings rather than hard errors if they remains un-inferred
// Match specific phrases that indicate a mock error from our code generation,
// while allowing other "not assignable" errors (which represent real logic errors).
const isMockError = (message.includes("not assignable to parameter of type") && (message.includes("'{}'") || message.includes("undefined"))) ||
message.includes("not assignable to type 'undefined'") ||
message.includes("not assignable to type 'void'") ||
message.includes("may be a mistake because neither type sufficiently overlaps");
return {
message,
code: d.code,
severity: (isMockError ? "warning" : "error") as "error" | "warning",
};
});
return {
isValid: !errors.some(e => e.severity === "error"),
returnType: "void",
diagnostics: errors,
};
};