MCPcopy Create free account
hub / github.com/AnukarOP/claude-code-leaked / addItemToJSONCArray

Function addItemToJSONCArray

source code/utils/json.ts:230–279  ·  view source on GitHub ↗
(content: string, newItem: unknown)

Source from the content-addressed store, hash-verified

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

Callers 1

Calls 3

stripBOMFunction · 0.90
jsonStringifyFunction · 0.85
logErrorFunction · 0.70

Tested by

no test coverage detected