/
parseAssertions.ts
61 lines (57 loc) · 2.02 KB
/
parseAssertions.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
import Identifier from '../ast/nodes/Identifier';
import ImportAttribute from '../ast/nodes/ImportAttribute';
import ImportExpression from '../ast/nodes/ImportExpression';
import Literal, { LiteralValue } from '../ast/nodes/Literal';
import ObjectExpression from '../ast/nodes/ObjectExpression';
import Property from '../ast/nodes/Property';
import SpreadElement from '../ast/nodes/SpreadElement';
import { EMPTY_OBJECT } from './blank';
export function getAssertionsFromImportExpression(node: ImportExpression): Record<string, string> {
const assertProperty = node.arguments?.[0]?.properties.find(
(property): property is Property => getPropertyKey(property) === 'assert'
)?.value;
if (!assertProperty) {
return EMPTY_OBJECT;
}
const assertFields = (assertProperty as ObjectExpression).properties
.map(property => {
const key = getPropertyKey(property);
if (
typeof key === 'string' &&
typeof ((property as Property).value as Literal).value === 'string'
) {
return [key, ((property as Property).value as Literal).value] as [string, string];
}
return null;
})
.filter((property): property is [string, string] => !!property);
if (assertFields.length > 0) {
return Object.fromEntries(assertFields);
}
return EMPTY_OBJECT;
}
const getPropertyKey = (
property: Property | SpreadElement | ImportAttribute
): LiteralValue | undefined => {
const key = (property as Property | ImportAttribute).key;
return key && ((key as Identifier).name || (key as Literal).value);
};
export function getAssertionsFromImportExportDeclaration(
assertions: ImportAttribute[] | undefined
) {
return assertions?.length
? Object.fromEntries(
assertions.map(assertion => [getPropertyKey(assertion), assertion.value.value])
)
: EMPTY_OBJECT;
}
export function doAssertionsDiffer(
assertionA: Record<string, string>,
assertionB: Record<string, string>
): boolean {
const keysA = Object.keys(assertionA);
return (
keysA.length !== Object.keys(assertionB).length ||
keysA.some(key => assertionA[key] !== assertionB[key])
);
}