All files / backend/src/utils/format-providers toml-format-provider.ts

6.25% Statements 2/32
0% Branches 0/12
33.33% Functions 2/6
6.89% Lines 2/29

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                                10x               1x                                                                                                      
/**
 * TOML Format Provider
 *
 * Handles parsing and serialization of TOML frontmatter in content files.
 */
 
import tomlify from 'tomlify-j0.4';
import toml from 'toml';
import type { FormatProvider, ParsedContent } from './types.js';
 
export class TomlFormatProvider implements FormatProvider {
  defaultExt(): string {
    return 'toml';
  }
 
  matchContentFirstLine(line: string): boolean {
    return line.startsWith('+++');
  }
 
  parse(str: string): unknown {
    return toml.parse(str);
  }
 
  dump(obj: unknown): string {
    return tomlify.toToml(obj, { space: 2 });
  }
 
  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 reg = /^[+]{3} *(\r?\n|\r|^)/gm;
    let tomlEnd = -1;
    for (let i = 0; i < 2; i++) {
      const execResult = reg.exec(data);
      if (execResult === null) break;
      if (i === 1) tomlEnd = execResult.index;
    }
 
    let tomlStr: string, md: string;
 
    if (tomlEnd === -1) {
      tomlStr = '';
      md = data;
    } else {
      tomlStr = data.substr(3, tomlEnd - 3);
      md = data.substr(tomlEnd + 3);
    }
 
    const parsedData = this.parse(tomlStr) as ParsedContent;
    if (parsedData === undefined) {
      return {};
    }
 
    if (/\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;
  }
}