parse.js 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. "use strict";
  2. const { ono } = require("@jsdevtools/ono");
  3. const url = require("./util/url");
  4. const plugins = require("./util/plugins");
  5. const { ResolverError, ParserError, UnmatchedParserError, UnmatchedResolverError, isHandledError } = require("./util/errors");
  6. module.exports = parse;
  7. /**
  8. * Reads and parses the specified file path or URL.
  9. *
  10. * @param {string} path - This path MUST already be resolved, since `read` doesn't know the resolution context
  11. * @param {$Refs} $refs
  12. * @param {$RefParserOptions} options
  13. *
  14. * @returns {Promise}
  15. * The promise resolves with the parsed file contents, NOT the raw (Buffer) contents.
  16. */
  17. async function parse (path, $refs, options) {
  18. // Remove the URL fragment, if any
  19. path = url.stripHash(path);
  20. // Add a new $Ref for this file, even though we don't have the value yet.
  21. // This ensures that we don't simultaneously read & parse the same file multiple times
  22. let $ref = $refs._add(path);
  23. // This "file object" will be passed to all resolvers and parsers.
  24. let file = {
  25. url: path,
  26. extension: url.getExtension(path),
  27. };
  28. // Read the file and then parse the data
  29. try {
  30. const resolver = await readFile(file, options, $refs);
  31. $ref.pathType = resolver.plugin.name;
  32. file.data = resolver.result;
  33. const parser = await parseFile(file, options, $refs);
  34. $ref.value = parser.result;
  35. return parser.result;
  36. }
  37. catch (err) {
  38. if (isHandledError(err)) {
  39. $ref.value = err;
  40. }
  41. throw err;
  42. }
  43. }
  44. /**
  45. * Reads the given file, using the configured resolver plugins
  46. *
  47. * @param {object} file - An object containing information about the referenced file
  48. * @param {string} file.url - The full URL of the referenced file
  49. * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
  50. * @param {$RefParserOptions} options
  51. *
  52. * @returns {Promise}
  53. * The promise resolves with the raw file contents and the resolver that was used.
  54. */
  55. function readFile (file, options, $refs) {
  56. return new Promise(((resolve, reject) => {
  57. // console.log('Reading %s', file.url);
  58. // Find the resolvers that can read this file
  59. let resolvers = plugins.all(options.resolve);
  60. resolvers = plugins.filter(resolvers, "canRead", file);
  61. // Run the resolvers, in order, until one of them succeeds
  62. plugins.sort(resolvers);
  63. plugins.run(resolvers, "read", file, $refs)
  64. .then(resolve, onError);
  65. function onError (err) {
  66. if (!err && options.continueOnError) {
  67. // No resolver could be matched
  68. reject(new UnmatchedResolverError(file.url));
  69. }
  70. else if (!err || !("error" in err)) {
  71. // Throw a generic, friendly error.
  72. reject(ono.syntax(`Unable to resolve $ref pointer "${file.url}"`));
  73. }
  74. // Throw the original error, if it's one of our own (user-friendly) errors.
  75. else if (err.error instanceof ResolverError) {
  76. reject(err.error);
  77. }
  78. else {
  79. reject(new ResolverError(err, file.url));
  80. }
  81. }
  82. }));
  83. }
  84. /**
  85. * Parses the given file's contents, using the configured parser plugins.
  86. *
  87. * @param {object} file - An object containing information about the referenced file
  88. * @param {string} file.url - The full URL of the referenced file
  89. * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
  90. * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver
  91. * @param {$RefParserOptions} options
  92. *
  93. * @returns {Promise}
  94. * The promise resolves with the parsed file contents and the parser that was used.
  95. */
  96. function parseFile (file, options, $refs) {
  97. return new Promise(((resolve, reject) => {
  98. // console.log('Parsing %s', file.url);
  99. // Find the parsers that can read this file type.
  100. // If none of the parsers are an exact match for this file, then we'll try ALL of them.
  101. // This handles situations where the file IS a supported type, just with an unknown extension.
  102. let allParsers = plugins.all(options.parse);
  103. let filteredParsers = plugins.filter(allParsers, "canParse", file);
  104. let parsers = filteredParsers.length > 0 ? filteredParsers : allParsers;
  105. // Run the parsers, in order, until one of them succeeds
  106. plugins.sort(parsers);
  107. plugins.run(parsers, "parse", file, $refs)
  108. .then(onParsed, onError);
  109. function onParsed (parser) {
  110. if (!parser.plugin.allowEmpty && isEmpty(parser.result)) {
  111. reject(ono.syntax(`Error parsing "${file.url}" as ${parser.plugin.name}. \nParsed value is empty`));
  112. }
  113. else {
  114. resolve(parser);
  115. }
  116. }
  117. function onError (err) {
  118. if (!err && options.continueOnError) {
  119. // No resolver could be matched
  120. reject(new UnmatchedParserError(file.url));
  121. }
  122. else if (!err || !("error" in err)) {
  123. reject(ono.syntax(`Unable to parse ${file.url}`));
  124. }
  125. else if (err.error instanceof ParserError) {
  126. reject(err.error);
  127. }
  128. else {
  129. reject(new ParserError(err.error.message, file.url));
  130. }
  131. }
  132. }));
  133. }
  134. /**
  135. * Determines whether the parsed value is "empty".
  136. *
  137. * @param {*} value
  138. * @returns {boolean}
  139. */
  140. function isEmpty (value) {
  141. return value === undefined ||
  142. (typeof value === "object" && Object.keys(value).length === 0) ||
  143. (typeof value === "string" && value.trim().length === 0) ||
  144. (Buffer.isBuffer(value) && value.length === 0);
  145. }