| 100 | * @since 4.0.0 |
| 101 | */ |
| 102 | export const parse = (input: string): Record<string, unknown> => { |
| 103 | const output: Record<string, any> = Object.create(null) |
| 104 | let current = output |
| 105 | const sectionPattern = /^\[([^\]]*)\]\s*$/ |
| 106 | const propertyPattern = /^([^=]+)(=(.*))?$/ |
| 107 | |
| 108 | for (const line of input.split(/[\r\n]+/g)) { |
| 109 | if (line.length === 0 || /^\s*(?:[;#]|$)/.test(line)) { |
| 110 | continue |
| 111 | } |
| 112 | |
| 113 | const sectionMatch = sectionPattern.exec(line) |
| 114 | if (sectionMatch !== null) { |
| 115 | const section = unquote(sectionMatch[1]) |
| 116 | if (section === "__proto__") { |
| 117 | current = Object.create(null) |
| 118 | } else { |
| 119 | if (!isRecord(output[section])) { |
| 120 | output[section] = Object.create(null) |
| 121 | } |
| 122 | current = output[section] |
| 123 | } |
| 124 | continue |
| 125 | } |
| 126 | |
| 127 | const propertyMatch = propertyPattern.exec(line) |
| 128 | if (propertyMatch === null) { |
| 129 | continue |
| 130 | } |
| 131 | |
| 132 | const rawKey = unquote(propertyMatch[1]) |
| 133 | const array = rawKey.length > 2 && rawKey.endsWith("[]") |
| 134 | const key = array ? rawKey.slice(0, -2) : rawKey |
| 135 | if (key === "__proto__") { |
| 136 | continue |
| 137 | } |
| 138 | |
| 139 | const rawValue = propertyMatch[2] === undefined ? true : unquote(propertyMatch[3]) |
| 140 | const value = rawValue === "true" || rawValue === "false" || rawValue === "null" |
| 141 | ? JSON.parse(rawValue) |
| 142 | : rawValue |
| 143 | |
| 144 | if (array) { |
| 145 | if (!hasOwn.call(current, key)) { |
| 146 | current[key] = [] |
| 147 | } else if (!Array.isArray(current[key])) { |
| 148 | current[key] = [current[key]] |
| 149 | } |
| 150 | } |
| 151 | if (Array.isArray(current[key])) { |
| 152 | current[key].push(value) |
| 153 | } else { |
| 154 | current[key] = value |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | const remove: Array<string> = [] |
| 159 | for (const section of Object.keys(output)) { |