l0bsterssg

node.js static responsive blog post generator
Log | Files | Refs | README

index.js (1918B)


      1 var parser = require('js-yaml')
      2 var optionalByteOrderMark = '\\ufeff?'
      3 var platform = typeof process !== 'undefined' ? process.platform : ''
      4 var pattern = '^(' +
      5   optionalByteOrderMark +
      6   '(= yaml =|---)' +
      7   '$([\\s\\S]*?)' +
      8   '^(?:\\2|\\.\\.\\.)\\s*' +
      9   '$' +
     10   (platform === 'win32' ? '\\r?' : '') +
     11   '(?:\\n)?)'
     12 // NOTE: If this pattern uses the 'g' flag the `regex` variable definition will
     13 // need to be moved down into the functions that use it.
     14 var regex = new RegExp(pattern, 'm')
     15 
     16 module.exports = extractor
     17 module.exports.test = test
     18 
     19 function extractor (string, options) {
     20   string = string || ''
     21   var defaultOptions = { allowUnsafe: false }
     22   options = options instanceof Object ? { ...defaultOptions, ...options } : defaultOptions
     23   options.allowUnsafe = Boolean(options.allowUnsafe)
     24   var lines = string.split(/(\r?\n)/)
     25   if (lines[0] && /= yaml =|---/.test(lines[0])) {
     26     return parse(string, options.allowUnsafe)
     27   } else {
     28     return {
     29       attributes: {},
     30       body: string,
     31       bodyBegin: 1
     32     }
     33   }
     34 }
     35 
     36 function computeLocation (match, body) {
     37   var line = 1
     38   var pos = body.indexOf('\n')
     39   var offset = match.index + match[0].length
     40 
     41   while (pos !== -1) {
     42     if (pos >= offset) {
     43       return line
     44     }
     45     line++
     46     pos = body.indexOf('\n', pos + 1)
     47   }
     48 
     49   return line
     50 }
     51 
     52 function parse (string, allowUnsafe) {
     53   var match = regex.exec(string)
     54   if (!match) {
     55     return {
     56       attributes: {},
     57       body: string,
     58       bodyBegin: 1
     59     }
     60   }
     61 
     62   var loader = allowUnsafe ? parser.load : parser.safeLoad
     63   var yaml = match[match.length - 1].replace(/^\s+|\s+$/g, '')
     64   var attributes = loader(yaml) || {}
     65   var body = string.replace(match[0], '')
     66   var line = computeLocation(match, string)
     67 
     68   return {
     69     attributes: attributes,
     70     body: body,
     71     bodyBegin: line,
     72     frontmatter: yaml
     73   }
     74 }
     75 
     76 function test (string) {
     77   string = string || ''
     78 
     79   return regex.test(string)
     80 }