-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
193 lines (179 loc) · 4.83 KB
/
index.js
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
187
188
189
190
191
192
193
import moo from 'moo'
import json5 from 'json5/dist/index.mjs'
function isNumeric(str) {
if (typeof str != 'string') return false // we only process strings!
return (
!isNaN(str) && // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)...
!isNaN(parseFloat(str))
) // ...and ensure strings of whitespace fail
}
/**
* Creates a regex that matches if any one of the elements in the array is matched
* with backslash being an escape
* @param {string[] | string} elements
*/
function createORRegex(elements) {
if (!Array.isArray(elements)) {
return new RegExp(`${elements}`)
}
const regexString = `(?:${elements.join('|')})`
return new RegExp(regexString)
}
export const parse = (line, configuration = {}) => {
let mergedConfig = {
operator: ['=', ':'],
separator: ',',
strict: false,
...configuration,
}
const lexer = moo.states({
key: {
escape: { match: /\\/, push: 'escape' },
operator: { match: createORRegex(mergedConfig.operator), next: 'firstValue' },
startQuote: { match: /"/, push: 'inQuote' },
startSingleQuote: { match: /'/, push: 'inSingleQuote' },
separator: { match: createORRegex(mergedConfig.separator), next: 'key' },
keyText: { match: /[^]+?/, lineBreaks: true },
},
escape: {
escapeText: { match: /[^]+?/, lineBreaks: true, pop: 1 },
},
firstValue: {
escape: { match: /\\/, push: 'escape' },
startObject: { match: /{/, push: 'inObject' },
startArray: { match: /\[/, push: 'inArray' },
startQuote: { match: /"/, push: 'inQuote' },
startSingleQuote: { match: /'/, push: 'inSingleQuote' },
valueText: { match: /[^]+?/, lineBreaks: true, next: 'value' },
},
value: {
escape: { match: /\\/, push: 'escape' },
separator: { match: createORRegex(mergedConfig.separator), next: 'key' },
valueText: { match: /[^]+?/, lineBreaks: true },
},
inObject: {
escape: { match: /\\/, push: 'escape' },
startObject: { match: /{/, push: 'inObject' },
endObject: { match: /}/, pop: 1 },
objectText: { match: /[^]+?/, lineBreaks: true },
},
inArray: {
escape: { match: /\\/, push: 'escape' },
endArray: { match: /\]/, pop: 1 },
arrayText: { match: /[^]+?/, lineBreaks: true },
},
inQuote: {
escape: { match: /\\/, push: 'escape' },
endQuote: { match: /"/, pop: 1 },
quotedText: { match: /[^]+?/, lineBreaks: true },
},
inSingleQuote: {
escape: { match: /\\/, push: 'escape' },
endSingleQuote: { match: /'/, pop: 1 },
quotedText: { match: /[^]+?/, lineBreaks: true },
},
})
lexer.reset(line)
const parsedObject = {}
let currentKey = ''
let currentValue = ''
let hasSeenOperator = false
const convertValue = (value, onlyBasics = false) => {
if (isNumeric(value)) {
if (value.includes('.')) {
return parseFloat(value)
}
if (value.startsWith('0x')) {
return parseInt(value, 16)
}
return parseInt(value, 10)
}
if (value === 'true') {
return true
}
if (value === 'false') {
return false
}
if (!onlyBasics) {
try {
if (value.startsWith('{') && value.endsWith('}')) {
return json5.parse(value)
}
if (value.startsWith('[') && value.endsWith(']')) {
return json5.parse(value)
}
} catch (e) {
if (mergedConfig.strict) {
throw e
}
console.warn('Failed to convert to JSON5 object, falling back to string. Error: ', e)
return value
}
}
if (value.startsWith("'") && value.endsWith("'")) {
return value.slice(1, value.length - 1)
}
if (value.startsWith('"') && value.endsWith('"')) {
return value.slice(1, value.length - 1)
}
return value
}
const addValueToParsedObject = () => {
// create a parsed value
currentKey = currentKey.trim()
currentValue = currentValue.trim()
if (!currentKey) {
currentKey = ''
currentValue = ''
hasSeenOperator = false
return
}
if (!currentValue) {
if (!parsedObject._) {
parsedObject._ = []
}
parsedObject._.push(convertValue(currentKey))
} else {
// TODO: add some ability to JSON parse or sync.
parsedObject[currentKey] = convertValue(currentValue)
}
currentKey = ''
currentValue = ''
hasSeenOperator = false
}
for (let token of Array.from(lexer)) {
switch (token.type) {
case 'keyText':
currentKey += token.value
break
case 'separator':
addValueToParsedObject()
break
case 'operator':
hasSeenOperator = true
break
case 'valueText':
case 'startObject':
case 'startArray':
case 'endObject':
case 'endArray':
case 'objectText':
case 'arrayText':
currentValue += token.value
break
case 'startQuote':
case 'endQuote':
case 'startSingleQuote':
case 'endSingleQuote':
case 'quotedText':
case 'escapeText':
if (hasSeenOperator) {
currentValue += token.value
} else {
currentKey += token.value
}
}
}
addValueToParsedObject()
return parsedObject
}