-
Notifications
You must be signed in to change notification settings - Fork 640
/
type-checker.ts
186 lines (166 loc) · 4.94 KB
/
type-checker.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
import {
MstError,
EMPTY_ARRAY,
isPrimitive,
getStateTreeNode,
isStateTreeNode,
isPrimitiveType,
IAnyType,
ExtractCSTWithSTN,
isTypeCheckingEnabled,
devMode
} from "../../internal"
/** Validation context entry, this is, where the validation should run against which type */
export interface IValidationContextEntry {
/** Subpath where the validation should be run, or an empty string to validate it all */
path: string
/** Type to validate the subpath against */
type: IAnyType
}
/** Array of validation context entries */
export type IValidationContext = IValidationContextEntry[]
/** Type validation error */
export interface IValidationError {
/** Validation context */
context: IValidationContext
/** Value that was being validated, either a snapshot or an instance */
value: any
/** Error message */
message?: string
}
/** Type validation result, which is an array of type validation errors */
export type IValidationResult = IValidationError[]
function safeStringify(value: any) {
try {
return JSON.stringify(value)
} catch (e) {
// istanbul ignore next
return `<Unserializable: ${e}>`
}
}
/**
* @internal
* @hidden
*/
export function prettyPrintValue(value: any) {
return typeof value === "function"
? `<function${value.name ? " " + value.name : ""}>`
: isStateTreeNode(value)
? `<${value}>`
: `\`${safeStringify(value)}\``
}
function shortenPrintValue(valueInString: string) {
return valueInString.length < 280
? valueInString
: `${valueInString.substring(0, 272)}......${valueInString.substring(valueInString.length - 8)}`
}
function toErrorString(error: IValidationError): string {
const { value } = error
const type = error.context[error.context.length - 1].type!
const fullPath = error.context
.map(({ path }) => path)
.filter((path) => path.length > 0)
.join("/")
const pathPrefix = fullPath.length > 0 ? `at path "/${fullPath}" ` : ``
const currentTypename = isStateTreeNode(value)
? `value of type ${getStateTreeNode(value).type.name}:`
: isPrimitive(value)
? "value"
: "snapshot"
const isSnapshotCompatible =
type && isStateTreeNode(value) && type.is(getStateTreeNode(value).snapshot)
return (
`${pathPrefix}${currentTypename} ${prettyPrintValue(value)} is not assignable ${
type ? `to type: \`${type.name}\`` : ``
}` +
(error.message ? ` (${error.message})` : "") +
(type
? isPrimitiveType(type) || isPrimitive(value)
? `.`
: `, expected an instance of \`${(type as IAnyType).name}\` or a snapshot like \`${(
type as IAnyType
).describe()}\` instead.` +
(isSnapshotCompatible
? " (Note that a snapshot of the provided value is compatible with the targeted type)"
: "")
: `.`)
)
}
/**
* @internal
* @hidden
*/
export function getContextForPath(
context: IValidationContext,
path: string,
type: IAnyType
): IValidationContext {
return context.concat([{ path, type }])
}
/**
* @internal
* @hidden
*/
export function typeCheckSuccess(): IValidationResult {
return EMPTY_ARRAY as any
}
/**
* @internal
* @hidden
*/
export function typeCheckFailure(
context: IValidationContext,
value: any,
message?: string
): IValidationResult {
return [{ context, value, message }]
}
/**
* @internal
* @hidden
*/
export function flattenTypeErrors(errors: IValidationResult[]): IValidationResult {
return errors.reduce((a, i) => a.concat(i), [])
}
// TODO; doublecheck: typecheck should only needed to be invoked from: type.create and array / map / value.property will change
/**
* @internal
* @hidden
*/
export function typecheckInternal<IT extends IAnyType>(
type: IAnyType,
value: ExtractCSTWithSTN<IT>
): void {
// runs typeChecking if it is in dev-mode or through a process.env.ENABLE_TYPE_CHECK flag
if (isTypeCheckingEnabled()) {
typecheck(type, value)
}
}
/**
* Run's the typechecker for the given type on the given value, which can be a snapshot or an instance.
* Throws if the given value is not according the provided type specification.
* Use this if you need typechecks even in a production build (by default all automatic runtime type checks will be skipped in production builds)
*
* @param type Type to check against.
* @param value Value to be checked, either a snapshot or an instance.
*/
export function typecheck<IT extends IAnyType>(type: IT, value: ExtractCSTWithSTN<IT>): void {
const errors = type.validate(value, [{ path: "", type }])
if (errors.length > 0) {
throw new MstError(validationErrorsToString(type, value, errors))
}
}
function validationErrorsToString<IT extends IAnyType>(
type: IT,
value: ExtractCSTWithSTN<IT>,
errors: IValidationError[]
): string | undefined {
if (errors.length === 0) {
return undefined
}
return (
`Error while converting ${shortenPrintValue(prettyPrintValue(value))} to \`${
type.name
}\`:\n\n ` + errors.map(toErrorString).join("\n ")
)
}