( jsonString: string, )
| 259 | * and "enter" in Confirmation). |
| 260 | */ |
| 261 | export function checkDuplicateKeysInJson( |
| 262 | jsonString: string, |
| 263 | ): KeybindingWarning[] { |
| 264 | const warnings: KeybindingWarning[] = [] |
| 265 | |
| 266 | // Find each "bindings" block and check for duplicates within it |
| 267 | // Pattern: "bindings" : { ... } |
| 268 | const bindingsBlockPattern = |
| 269 | /"bindings"\s*:\s*\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}/g |
| 270 | |
| 271 | let blockMatch |
| 272 | while ((blockMatch = bindingsBlockPattern.exec(jsonString)) !== null) { |
| 273 | const blockContent = blockMatch[1] |
| 274 | if (!blockContent) continue |
| 275 | |
| 276 | // Find the context for this block by looking backwards |
| 277 | const textBeforeBlock = jsonString.slice(0, blockMatch.index) |
| 278 | const contextMatch = textBeforeBlock.match( |
| 279 | /"context"\s*:\s*"([^"]+)"[^{]*$/, |
| 280 | ) |
| 281 | const context = contextMatch?.[1] ?? 'unknown' |
| 282 | |
| 283 | // Find all keys within this bindings block |
| 284 | const keyPattern = /"([^"]+)"\s*:/g |
| 285 | const keysByName = new Map<string, number>() |
| 286 | |
| 287 | let keyMatch |
| 288 | while ((keyMatch = keyPattern.exec(blockContent)) !== null) { |
| 289 | const key = keyMatch[1] |
| 290 | if (!key) continue |
| 291 | |
| 292 | const count = (keysByName.get(key) ?? 0) + 1 |
| 293 | keysByName.set(key, count) |
| 294 | |
| 295 | if (count === 2) { |
| 296 | // Only warn on the second occurrence |
| 297 | warnings.push({ |
| 298 | type: 'duplicate', |
| 299 | severity: 'warning', |
| 300 | message: `Duplicate key "${key}" in ${context} bindings`, |
| 301 | key, |
| 302 | context, |
| 303 | suggestion: `This key appears multiple times in the same context. JSON uses the last value, earlier values are ignored.`, |
| 304 | }) |
| 305 | } |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | return warnings |
| 310 | } |
| 311 | |
| 312 | /** |
| 313 | * Validate user keybinding config and return all warnings. |
no test coverage detected