-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse.ts
39 lines (36 loc) · 1002 Bytes
/
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
import {isKebabCase, kebabCaseToCamelCase} from './utils'
/**
* parse the LESS source, and extract variables in `#less-vars {...}`;
* variable names should be kebab-case, and will be converted into camelCase
* @param {string} source
* @returns {object}
*/
export function parse(source: string): Record<string, string> {
const vars: Record<string, string> = {}
const m = source.replace(/[\r\n]/gm, ' ').match(/#less-vars\s*{([^{}]+)}/gm)
if (m) {
m.forEach((m) =>
m
.replace(/.*{|}.*/, '')
.split(';')
.forEach((kv) => {
const i = kv.indexOf(':')
if (i > 0) {
const k = kv.substr(0, i).trim()
const v = kv.substr(i + 1).trim()
if (k.length > 0 && v.length > 0) {
vars[k] = v
}
}
}),
)
}
const result: Record<string, string> = {}
Object.entries(vars).forEach(([k, v]) => {
if (!isKebabCase(k)) {
throw new Error(`Less variable is not kebab-case: ${k}`)
}
result[kebabCaseToCamelCase(k)] = v
})
return result
}