(jsoncString: string)
| 8 | } |
| 9 | |
| 10 | function extractCommentsFromJsonc(jsoncString: string): Record<string, any> { |
| 11 | const lines = jsoncString.split("\n"); |
| 12 | const comments: Record<string, any> = {}; |
| 13 | |
| 14 | // Parse to validate structure |
| 15 | const errors: ParseError[] = []; |
| 16 | const result = parse(jsoncString, errors, { |
| 17 | allowTrailingComma: true, |
| 18 | disallowComments: false, |
| 19 | allowEmptyContent: true, |
| 20 | }); |
| 21 | |
| 22 | if (errors.length > 0) { |
| 23 | return {}; |
| 24 | } |
| 25 | |
| 26 | // Track nesting context with array indices |
| 27 | const contextStack: Array<{ key: string; isArray: boolean; arrayIndex?: number }> = []; |
| 28 | let arrayObjectCount: Record<number, number> = {}; // Track object count per array depth |
| 29 | |
| 30 | for (let i = 0; i < lines.length; i++) { |
| 31 | const line = lines[i]; |
| 32 | const trimmedLine = line.trim(); |
| 33 | |
| 34 | if (!trimmedLine) continue; |
| 35 | |
| 36 | // Handle different comment types |
| 37 | const commentData = extractCommentFromLine(line, lines, i); |
| 38 | if (commentData.hint) { |
| 39 | let keyInfo; |
| 40 | |
| 41 | if (commentData.isInline) { |
| 42 | // For inline comments, extract key from the same line |
| 43 | const keyMatch = line.match(/^\s*["']?([^"':,\s]+)["']?\s*:/); |
| 44 | if (keyMatch) { |
| 45 | const key = keyMatch[1]; |
| 46 | const path = contextStack.map((ctx) => ctx.arrayIndex !== undefined ? String(ctx.arrayIndex) : ctx.key).filter(Boolean); |
| 47 | keyInfo = { key, path }; |
| 48 | } |
| 49 | } else { |
| 50 | // For standalone comments, find the next key |
| 51 | keyInfo = findAssociatedKey(lines, commentData.lineIndex, contextStack, arrayObjectCount); |
| 52 | } |
| 53 | |
| 54 | if (keyInfo && keyInfo.key) { |
| 55 | setCommentAtPath(comments, keyInfo.path, keyInfo.key, commentData.hint); |
| 56 | } |
| 57 | |
| 58 | // Skip processed lines for multi-line comments |
| 59 | i = commentData.endIndex; |
| 60 | continue; |
| 61 | } |
| 62 | |
| 63 | // Update context for object/array nesting |
| 64 | updateContext(contextStack, line, result, arrayObjectCount); |
| 65 | } |
| 66 | |
| 67 | return comments; |
no test coverage detected