| 1 |
"use strict"; |
| 2 |
|
| 3 |
const { ParserError } = require("../util/errors"); |
| 4 |
|
| 5 |
module.exports = { |
| 6 |
/** |
| 7 |
* The order that this parser will run, in relation to other parsers. |
| 8 |
* |
| 9 |
* @type {number} |
| 10 |
*/ |
| 11 |
order: 100, |
| 12 |
|
| 13 |
/** |
| 14 |
* Whether to allow "empty" files. This includes zero-byte files, as well as empty JSON objects. |
| 15 |
* |
| 16 |
* @type {boolean} |
| 17 |
*/ |
| 18 |
allowEmpty: true, |
| 19 |
|
| 20 |
/** |
| 21 |
* Determines whether this parser can parse a given file reference. |
| 22 |
* Parsers that match will be tried, in order, until one successfully parses the file. |
| 23 |
* Parsers that don't match will be skipped, UNLESS none of the parsers match, in which case |
| 24 |
* every parser will be tried. |
| 25 |
* |
| 26 |
* @type {RegExp|string|string[]|function} |
| 27 |
*/ |
| 28 |
canParse: ".json", |
| 29 |
|
| 30 |
/** |
| 31 |
* Parses the given file as JSON |
| 32 |
* |
| 33 |
* @param {object} file - An object containing information about the referenced file |
| 34 |
* @param {string} file.url - The full URL of the referenced file |
| 35 |
* @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) |
| 36 |
* @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver |
| 37 |
* @returns {Promise} |
| 38 |
*/ |
| 39 |
async parse (file) { // eslint-disable-line require-await |
| 40 |
let data = file.data; |
| 41 |
if (Buffer.isBuffer(data)) { |
| 42 |
data = data.toString(); |
| 43 |
} |
| 44 |
|
| 45 |
if (typeof data === "string") { |
| 46 |
if (data.trim().length === 0) { |
| 47 |
return; // This mirrors the YAML behavior |
| 48 |
} |
| 49 |
else { |
| 50 |
try { |
| 51 |
return JSON.parse(data); |
| 52 |
} |
| 53 |
catch (e) { |
| 54 |
throw new ParserError(e.message, file.url); |
| 55 |
} |
| 56 |
} |
| 57 |
} |
| 58 |
else { |
| 59 |
// data is already a JavaScript value (object, array, number, null, NaN, etc.) |
| 60 |
return data; |
| 61 |
} |
| 62 |
} |
| 63 |
}; |