Skip to content

Commit

Permalink
review
Browse files Browse the repository at this point in the history
  • Loading branch information
liuxingbaoyu committed Jul 14, 2022
1 parent 501e407 commit 13011e1
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 30 deletions.
45 changes: 18 additions & 27 deletions packages/babel-types/src/definitions/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1961,45 +1961,36 @@ defineType("TaggedTemplateExpression", {
},
});

function templateElementCookedValidator(
node: t.TemplateElement,
key: string,
val: string,
) {
if (val != undefined) {
if (typeof val !== "string") {
throw new TypeError(
`Property ${key} expected type of string but got ${typeof val}`,
);
}
function templateElementCookedValidator(node: t.TemplateElement) {
const raw = node.value.raw;
if (node.value.cooked != null) {
return;
}

if (typeof node.value !== "object" || typeof node.value.raw !== "string") {
return;
}

let cooked;
let cooked = null;
try {
cooked = unraw(node.value.raw);
cooked = unraw(raw);
} catch (error) {}
node.value.cooked = cooked;
}
templateElementCookedValidator.type = "string"; // hack
templateElementCookedValidator.type = "{ raw: string; cooked?: string }"; // hack

defineType("TemplateElement", {
builder: ["value", "tail"],
fields: {
value: {
validate: assertShape({
raw: {
validate: assertValueType("string"),
},
cooked: {
validate: templateElementCookedValidator,
optional: "validateFn",
},
}),
validate: chain(
assertShape({
raw: {
validate: assertValueType("string"),
},
cooked: {
validate: assertValueType("string"),
optional: true,
},
}),
templateElementCookedValidator,
),
},
tail: {
default: false,
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-types/src/definitions/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export type Validator = (

export type FieldOptions = {
default?: string | number | boolean | [];
optional?: boolean | "validateFn";
optional?: boolean;
validate?: Validator;
};

Expand Down
2 changes: 1 addition & 1 deletion packages/babel-types/src/validators/validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export function validateField(
field: FieldOptions | undefined | null,
): void {
if (!field?.validate) return;
if (field.optional === true && val == null) return;
if (field.optional && val == null) return;

field.validate(node, key, val);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ Object {
"tail": false,
"type": "TemplateElement",
"value": Object {
"cooked": undefined,
"cooked": null,
"raw": "\\\\u",
},
}
Expand Down

0 comments on commit 13011e1

Please sign in to comment.