| 65 | * Returns field positions mapped to their document-level line/col. |
| 66 | */ |
| 67 | export function parseFrontmatter(text: string): ParsedFrontmatter | null { |
| 68 | const bounds = findFrontmatterBounds(text); |
| 69 | if (!bounds) { |
| 70 | return null; |
| 71 | } |
| 72 | |
| 73 | const { startLine, endLine, yamlText } = bounds; |
| 74 | // Offset: YAML content starts at line 1 (after opening `---`) |
| 75 | const yamlLineOffset = startLine + 1; |
| 76 | |
| 77 | const lineCounter = new LineCounter(); |
| 78 | const doc = parseDocument(yamlText, { lineCounter, keepSourceTokens: true }); |
| 79 | |
| 80 | const errors: Array<{ message: string; range: Range }> = []; |
| 81 | for (const err of doc.errors) { |
| 82 | const pos = err.pos; |
| 83 | const startPos = lineCounter.linePos(pos[0]); |
| 84 | const endPos = lineCounter.linePos(pos[1]); |
| 85 | errors.push({ |
| 86 | message: err.message, |
| 87 | range: { |
| 88 | start: { line: startPos.line - 1 + yamlLineOffset, col: startPos.col - 1 }, |
| 89 | end: { line: endPos.line - 1 + yamlLineOffset, col: endPos.col - 1 }, |
| 90 | }, |
| 91 | }); |
| 92 | } |
| 93 | |
| 94 | const fields = new Map<string, FrontmatterField>(); |
| 95 | const contents = doc.contents; |
| 96 | |
| 97 | if (isMap(contents)) { |
| 98 | for (const item of contents.items) { |
| 99 | if (!isPair(item)) continue; |
| 100 | |
| 101 | const keyNode = item.key; |
| 102 | if (!isScalar(keyNode) || typeof keyNode.value !== "string") continue; |
| 103 | |
| 104 | const fieldName = keyNode.value; |
| 105 | const keyRange = nodeRange(keyNode, lineCounter, yamlLineOffset); |
| 106 | |
| 107 | let value: unknown; |
| 108 | let valueRange: Range; |
| 109 | |
| 110 | const valNode = item.value; |
| 111 | if (valNode && valNode.range) { |
| 112 | valueRange = nodeRange(valNode, lineCounter, yamlLineOffset); |
| 113 | if (isScalar(valNode)) { |
| 114 | value = valNode.value; |
| 115 | } else if (isSeq(valNode)) { |
| 116 | value = valNode.toJSON(); |
| 117 | } else if (isMap(valNode)) { |
| 118 | value = valNode.toJSON(); |
| 119 | } else { |
| 120 | value = valNode.toJSON?.() ?? null; |
| 121 | } |
| 122 | } else { |
| 123 | // Missing value — point at end of key |
| 124 | valueRange = { start: keyRange.end, end: keyRange.end }; |