Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | 10x 12x 1x | /**
* JSON Format Provider
*
* Handles parsing and serialization of JSON frontmatter in content files.
*/
import type { FormatProvider, ParsedContent } from './types.js';
export class JsonFormatProvider implements FormatProvider {
defaultExt(): string {
return 'json';
}
matchContentFirstLine(line: string): boolean {
return line.startsWith('{');
}
parse(str: string): unknown {
return JSON.parse(str);
}
dump(obj: unknown): string {
return JSON.stringify(obj, null, ' ');
}
dumpContent(obj: ParsedContent): string {
let content = '';
if (obj.mainContent) {
content = obj.mainContent;
delete obj.mainContent;
}
const header = this.dump(obj);
return `${header}
${content}`;
}
parseFromMdFileString(str: string): ParsedContent {
const data = str;
const jsonExecResult = /^} *(\r?\n|\r|^)/m.exec(data);
let jsonEnd = -1;
let hasFrontMatter = true;
if (jsonExecResult != null) {
jsonEnd = jsonExecResult.index;
}
// TODO: test
// what if the file only has a json?
// and what if it only has a markdown?
let json: string, md: string;
if (jsonEnd === -1) {
json = '{}';
md = data;
} else {
json = data.substr(0, jsonEnd + 1);
md = data.substr(jsonEnd + 1);
}
let parsedData = this.parse(json) as ParsedContent;
if (parsedData === undefined) {
parsedData = {};
hasFrontMatter = false;
}
if (hasFrontMatter && /\S/.test(md)) {
// if have non whitespaces
// remove the two first line breaks
md = md.replace(/(\r?\n|\r)/, '').replace(/(\r?\n|\r)/, '');
}
parsedData.mainContent = md;
return parsedData;
}
}
|