( source: EditableSettingSource, settings: SettingsJson, )
| 414 | * the key is present with an explicit `undefined` value. |
| 415 | */ |
| 416 | export function updateSettingsForSource( |
| 417 | source: EditableSettingSource, |
| 418 | settings: SettingsJson, |
| 419 | ): { error: Error | null } { |
| 420 | if ( |
| 421 | (source as unknown) === 'policySettings' || |
| 422 | (source as unknown) === 'flagSettings' |
| 423 | ) { |
| 424 | return { error: null } |
| 425 | } |
| 426 | |
| 427 | // Create the folder if needed |
| 428 | const filePath = getSettingsFilePathForSource(source) |
| 429 | if (!filePath) { |
| 430 | return { error: null } |
| 431 | } |
| 432 | |
| 433 | try { |
| 434 | getFsImplementation().mkdirSync(dirname(filePath)) |
| 435 | |
| 436 | // Try to get existing settings with validation. Bypass the per-source |
| 437 | // cache — mergeWith below mutates its target (including nested refs), |
| 438 | // and mutating the cached object would leak unpersisted state if the |
| 439 | // write fails before resetSettingsCache(). |
| 440 | let existingSettings = getSettingsForSourceUncached(source) |
| 441 | |
| 442 | // If validation failed, check if file exists with a JSON syntax error |
| 443 | if (!existingSettings) { |
| 444 | let content: string | null = null |
| 445 | try { |
| 446 | content = readFileSync(filePath) |
| 447 | } catch (e) { |
| 448 | if (!isENOENT(e)) { |
| 449 | throw e |
| 450 | } |
| 451 | // File doesn't exist — fall through to merge with empty settings |
| 452 | } |
| 453 | if (content !== null) { |
| 454 | const rawData = safeParseJSON(content) |
| 455 | if (rawData === null) { |
| 456 | // JSON syntax error - return validation error instead of overwriting |
| 457 | // safeParseJSON will already log the error, so we'll just return the error here |
| 458 | return { |
| 459 | error: new Error( |
| 460 | `Invalid JSON syntax in settings file at ${filePath}`, |
| 461 | ), |
| 462 | } |
| 463 | } |
| 464 | if (rawData && typeof rawData === 'object') { |
| 465 | existingSettings = rawData as SettingsJson |
| 466 | logForDebugging( |
| 467 | `Using raw settings from ${filePath} due to validation failure`, |
| 468 | ) |
| 469 | } |
| 470 | } |
| 471 | } |
| 472 | |
| 473 | const updatedSettings = mergeWith( |
no test coverage detected