yaml.js 1.8 KB

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