This repository has been archived by the owner on Nov 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparse.ts
83 lines (70 loc) · 1.94 KB
/
parse.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
const acorn = require("acorn-jsx");
import { ParsedTest } from "./types";
const stripStyleBlock = (s: string) => s.replace(/<style>.*<\/style>/gs, "");
const stripJestStructures = (s: string) =>
s
.replace(/Array\s\[/g, "[")
.replace(/Object\s\{/g, "{")
.replace(/>[\s]*{.*}[\s]*</gs, ">[Replaced Object]<");
const stripStyledComponentStyles = (s: string) =>
s.replace(/\.c\d {.*}\s*(?=<|Array \[)/gs, "");
const tryJson = (key: string, rawValue: string, value: string) => {
try {
// confirm this is simply JSON that we don't care about
JSON.parse(JSON.stringify(value));
return {
key,
rawValue,
value: null
};
} catch (e) {
return {
key,
rawValue,
value: null,
error: e.message
};
}
};
const parseVal = (snapObj: { [key: string]: string }) => (
key: string
): ParsedTest => {
let value;
const sanitised = stripStyleBlock(stripJestStructures(snapObj[key]));
try {
value = acorn.parse(sanitised, {
plugins: { jsx: true }
});
} catch (e) {
// pending outcome of https://github.com/styled-components/jest-styled-components/issues/135
const styledComponentsStyleRegex = /\.c\d {.*}\s*(?=<|Array \[)/gs;
const noStyleBlock = stripStyleBlock(snapObj[key]);
const hasStyledComponentStyles = styledComponentsStyleRegex.test(
noStyleBlock
);
if (hasStyledComponentStyles) {
try {
value = acorn.parse(
stripJestStructures(stripStyledComponentStyles(noStyleBlock)),
{
plugins: { jsx: true }
}
);
} catch (e) {}
}
if (!value) {
return tryJson(key, snapObj[key], sanitised);
}
}
return {
key,
rawValue: snapObj[key],
value
};
};
export default (snapContents: string): ParsedTest[] => {
const evil = new Function("exports", snapContents);
const snapObj = {};
evil(snapObj);
return Object.keys(snapObj).map(parseVal(snapObj));
};