|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +import * as acorn from 'acorn'; |
| 4 | + |
| 5 | +/** |
| 6 | + * Creates a Javascript source parser for a given source file |
| 7 | + */ |
| 8 | +const createParser = () => { |
| 9 | + /** |
| 10 | + * Parses a given JavaScript file into an ESTree AST representation of it |
| 11 | + * |
| 12 | + * @param {import('vfile').VFile | Promise<import('vfile').VFile>} sourceFile |
| 13 | + * @returns {Promise<JsProgram>} |
| 14 | + */ |
| 15 | + const parseJsSource = async sourceFile => { |
| 16 | + // We allow the API doc VFile to be a Promise of a VFile also, |
| 17 | + // hence we want to ensure that it first resolves before we pass it to the parser |
| 18 | + const resolvedSourceFile = await Promise.resolve(sourceFile); |
| 19 | + |
| 20 | + if (typeof resolvedSourceFile.value !== 'string') { |
| 21 | + throw new TypeError( |
| 22 | + `expected resolvedSourceFile.value to be string but got ${typeof resolvedSourceFile.value}` |
| 23 | + ); |
| 24 | + } |
| 25 | + |
| 26 | + const res = acorn.parse(resolvedSourceFile.value, { |
| 27 | + allowReturnOutsideFunction: true, |
| 28 | + ecmaVersion: 'latest', |
| 29 | + locations: true, |
| 30 | + }); |
| 31 | + |
| 32 | + return { |
| 33 | + ...res, |
| 34 | + path: resolvedSourceFile.path, |
| 35 | + }; |
| 36 | + }; |
| 37 | + |
| 38 | + /** |
| 39 | + * Parses multiple JavaScript files into ESTree ASTs by wrapping parseJsSource |
| 40 | + * |
| 41 | + * @param {Array<import('vfile').VFile | Promise<import('vfile').VFile>>} apiDocs List of API doc files to be parsed |
| 42 | + * @returns {Promise<Array<JsProgram>>} |
| 43 | + */ |
| 44 | + const parseJsSources = async apiDocs => { |
| 45 | + // We do a Promise.all, to ensure that each API doc is resolved asynchronously |
| 46 | + // but all need to be resolved first before we return the result to the caller |
| 47 | + const resolvedApiDocEntries = await Promise.all(apiDocs.map(parseJsSource)); |
| 48 | + |
| 49 | + return resolvedApiDocEntries; |
| 50 | + }; |
| 51 | + |
| 52 | + return { parseJsSource, parseJsSources }; |
| 53 | +}; |
| 54 | + |
| 55 | +export default createParser; |
0 commit comments