| 1 | const parseBuilder = (str) => { |
| 2 | let lines = str.split("\n"); |
| 3 | const ref = {}; |
| 4 | for (let line of lines) { |
| 5 | if (!line.trim()) continue; |
| 6 | const r = /^(?<tabs>\s*)(?<name>\w*)(?<optional>\??):(?<regex>.*)/.exec( |
| 7 | line |
| 8 | ); |
| 9 | if (!r) return ""; |
| 10 | const lineData = r.groups; |
| 11 | const tabs = lineData.tabs.length; |
| 12 | if (!ref[tabs]) ref[tabs] = [lineData]; |
| 13 | else ref[tabs].push(lineData); |
| 14 | if (tabs) { |
| 15 | const parentRefInd = ref[tabs - 1].length - 1; |
| 16 | let parent = ref[tabs - 1][parentRefInd]; |
| 17 | if (!parent.children) parent.children = [lineData]; |
| 18 | else parent.children.push(lineData); |
| 19 | } |
| 20 | } |
| 21 | return buildToRegex(ref[0]); |
| 22 | }; |
| 23 | |
| 24 | const buildToRegex = (build) => { |
| 25 | const re = buildToRegexRecursion(build, ""); |
| 26 | return re; |
| 27 | }; |
| 28 | |
| 29 | const buildToRegexRecursion = (build, re) => { |
| 30 | if (!build?.length) return re; |
| 31 | const val = build.shift(); |
| 32 | if (val.name) re += `(?P<${val.name}>${val.regex}`; |
| 33 | else re += `(?:${val.regex}`; |
| 34 | if (val.children) re += buildToRegexRecursion(val.children, ""); |
| 35 | re += `${val.optional})`; |
| 36 | |
| 37 | return buildToRegexRecursion(build, re); |
| 38 | }; |
| 39 | |
| 40 | export default parseBuilder; |