-
-
Notifications
You must be signed in to change notification settings - Fork 224
Expand file tree
/
Copy pathcheck_template.ts
More file actions
83 lines (73 loc) · 2.34 KB
/
check_template.ts
File metadata and controls
83 lines (73 loc) · 2.34 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
import ts from "typescript";
import { ExpressionFactory } from "../../factories/ExpressionFactory";
import { MetadataTemplate } from "../../schemas/metadata/MetadataTemplate";
import { ITypiaContext } from "../../transformers/ITypiaContext";
import { ICheckEntry } from "../helpers/ICheckEntry";
import { template_to_pattern } from "./template_to_pattern";
/** @internal */
export const check_template = (props: {
context: ITypiaContext;
templates: MetadataTemplate[];
input: ts.Expression;
}): ICheckEntry => {
// TYPEOF STRING
const conditions: ts.Expression[] = [
ts.factory.createStrictEquality(
ts.factory.createStringLiteral("string"),
ts.factory.createTypeOfExpression(props.input),
),
];
// TEMPLATES
const internal: ts.Expression[] = props.templates.map((tpl) =>
ts.factory.createCallExpression(
ts.factory.createIdentifier(
`RegExp(/${template_to_pattern({
top: true,
template: tpl.row,
})}/).test`,
),
undefined,
[props.input],
),
);
conditions.push(
internal.length === 1
? internal[0]!
: internal.reduce((x, y) => ts.factory.createLogicalOr(x, y)),
);
// VALIDATION TAGS - handle validation tags attached to template literals
const validationConditions: ICheckEntry.ICondition[][] =
check_template_type_tags({
context: props.context,
templates: props.templates,
input: props.input,
});
// COMBINATION
return {
expression: conditions.reduce((x, y) => ts.factory.createLogicalAnd(x, y)),
conditions: validationConditions,
expected: props.templates.map((tpl) => tpl.getName()).join(" | "),
};
};
/** @internal */
const check_template_type_tags = (props: {
context: ITypiaContext;
templates: MetadataTemplate[];
input: ts.Expression;
}): ICheckEntry.ICondition[][] => {
// Collect validation tags from all templates
const allTags = props.templates.flatMap((tpl) => tpl.tags);
return allTags
.map((row) => row.filter((tag) => !!tag.validate))
.filter((row) => !!row.length)
.map((row) =>
row.map((tag) => ({
expected: `string & ${tag.name}`,
expression: ExpressionFactory.transpile({
transformer: props.context.transformer,
importer: props.context.importer,
script: tag.validate!,
})(props.input),
})),
);
};