(content: string, newItem: unknown)
| 226 | } |
| 227 | |
| 228 | export function addItemToJSONCArray(content: string, newItem: unknown): string { |
| 229 | try { |
| 230 | // If the content is empty or whitespace, create a new JSON file |
| 231 | if (!content || content.trim() === '') { |
| 232 | return jsonStringify([newItem], null, 4) |
| 233 | } |
| 234 | |
| 235 | // Strip BOM before parsing - PowerShell 5.x adds BOM to UTF-8 files |
| 236 | const cleanContent = stripBOM(content) |
| 237 | |
| 238 | // Parse the content to check if it's valid JSON |
| 239 | const parsedContent = parseJsonc(cleanContent) |
| 240 | |
| 241 | // If the parsed content is a valid array, modify it |
| 242 | if (Array.isArray(parsedContent)) { |
| 243 | // Get the length of the array |
| 244 | const arrayLength = parsedContent.length |
| 245 | |
| 246 | // Determine if we are dealing with an empty array |
| 247 | const isEmpty = arrayLength === 0 |
| 248 | |
| 249 | // If it's an empty array we want to add at index 0, otherwise append to the end |
| 250 | const insertPath = isEmpty ? [0] : [arrayLength] |
| 251 | |
| 252 | // Generate edits - we're using isArrayInsertion to add a new item without overwriting existing ones |
| 253 | const edits = modify(cleanContent, insertPath, newItem, { |
| 254 | formattingOptions: { insertSpaces: true, tabSize: 4 }, |
| 255 | isArrayInsertion: true, |
| 256 | }) |
| 257 | |
| 258 | // If edits could not be generated, fall back to manual JSON string manipulation |
| 259 | if (!edits || edits.length === 0) { |
| 260 | const copy = [...parsedContent, newItem] |
| 261 | return jsonStringify(copy, null, 4) |
| 262 | } |
| 263 | |
| 264 | // Apply the edits to preserve comments (use cleanContent without BOM) |
| 265 | return applyEdits(cleanContent, edits) |
| 266 | } |
| 267 | // If it's not an array at all, create a new array with the item |
| 268 | else { |
| 269 | // If the content exists but is not an array, we'll replace it completely |
| 270 | return jsonStringify([newItem], null, 4) |
| 271 | } |
| 272 | } catch (e) { |
| 273 | // If parsing fails for any reason, log the error and fallback to creating a new JSON array |
| 274 | logError(e) |
| 275 | return jsonStringify([newItem], null, 4) |
| 276 | } |
| 277 | } |
no test coverage detected