{"$schema":"https://doc-kit.nodejs.org/schemas/api-doc/1.0.1.json","id":"generators-ast-js","path":"/generators/ast-js","type":"module","module":"generators-ast-js","title":"Parsing JavaScript","introducedIn":null,"sourceLink":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The `ast-js` stage parses the `.js` files among your inputs into syntax trees\nwith [Acorn](https://github.com/acornjs/acorn), for generators that read source\ncode rather than Markdown. [API links](https://doc-kit.nodejs.org/generators/api-links)\nis the built-in generator that reads it, and a\n[generator of your own](https://doc-kit.nodejs.org/creating-generators) can\ntoo.\n\n**Stage:** `ast-js` · **Package:** [`@doc-kit/core`](https://doc-kit.nodejs.org/packages/core) · **Reads:** the `.js` files in `input` · **Writes:** no files","summary":"The `ast-js` stage parses the `.js` files among your inputs into syntax trees with Acorn, for generators that read source code rather than Markdown. API links is the built-in generator that reads it, and a generator of your own can too.","examples":[],"children":[{"kind":"section","id":"usage","name":"Usage","title":"Usage","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"You don't ask for `ast-js` yourself: it runs when a target depends on it, once\nper run however many targets read it. Request `api-links`, from\n[`@node-core/doc-kit`](https://doc-kit.nodejs.org/packages/node), and point\n`--input` at your JavaScript:\n\n```bash\nnpm install --save-dev @doc-kit/cli @node-core/doc-kit\nnpx doc-kit generate -t api-links -i \"lib/*.js\" -o out\n```","summary":"You don't ask for `ast-js` yourself: it runs when a target depends on it, once per run however many targets read it. Request `api-links`, from `@node-core/doc-kit`, and point `--input` at your JavaScript:","examples":[{"language":"bash","displayName":null,"code":"npm install --save-dev @doc-kit/cli @node-core/doc-kit\nnpx doc-kit generate -t api-links -i \"lib/*.js\" -o out"}],"children":[]},{"kind":"section","id":"configuring","name":"Configuring","title":"Configuring","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"`ast-js` has no options of its own. It reads these global options, which you\ncan also set in an `ast-js` section to apply to it alone:\n\n* `input` {string | string[]} Glob patterns of the files to parse, relative to\n  the working directory. Of the files they match, only those ending in `.js`\n  are parsed; `.mjs`, `.cjs` and any other file is skipped. **Default:** from\n  `global.input` (`--input`).\n* `ignore` {string | string[]} Glob patterns of files to leave out.\n  **Default:** from `global.ignore` (`--ignore`).\n\nFiles are parsed in worker threads,\n[`chunkSize`](https://doc-kit.nodejs.org/configuration#execution-options) files\nper task.\n\nWhen the same run builds pages, keep `global.input` for your docs and give\n`ast-js` its own: the [Markdown stage](https://doc-kit.nodejs.org/generators/ast)\nparses every file `global.input` matches as Markdown, whatever its extension.\n\n```js displayName=\"doc-kit.config.mjs\"\nexport default {\n  target: ['html', 'api-links'],\n  global: {\n    input: ['doc/api/*.md'],\n    output: 'out',\n  },\n  'ast-js': {\n    input: ['lib/*.js'],\n    ignore: ['lib/*.test.js'],\n  },\n};\n```","summary":"`ast-js` has no options of its own. It reads these global options, which you can also set in an `ast-js` section to apply to it alone:","examples":[{"language":"js","displayName":"doc-kit.config.mjs","code":"export default {\n  target: ['html', 'api-links'],\n  global: {\n    input: ['doc/api/*.md'],\n    output: 'out',\n  },\n  'ast-js': {\n    input: ['lib/*.js'],\n    ignore: ['lib/*.test.js'],\n  },\n};"}],"children":[]},{"kind":"section","id":"how-files-are-parsed","name":"How files are parsed","title":"How files are parsed","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Acorn parses every file with the same options:\n\n| Acorn option                 | Value                        | What it means for your files                                                                             |\n| ---------------------------- | ---------------------------- | -------------------------------------------------------------------------------------------------------- |\n| `ecmaVersion`                | `'latest'`                   | The newest syntax Acorn supports is accepted.                                                            |\n| `sourceType`                 | `'script'` (Acorn's default) | Files are read as CommonJS-style scripts, so `import`, `export` and top-level `await` are syntax errors. |\n| `allowReturnOutsideFunction` | `true`                       | A top-level `return` is allowed, as in a CommonJS module.                                                |\n| `locations`                  | `true`                       | Every node has a `loc` holding its start and end as `line` (from 1) and `column` (from 0).               |\n\nAcorn doesn't parse JSX or type annotations either. To document TypeScript\nsources, see [Documenting TypeScript](https://doc-kit.nodejs.org/typescript).\n\n> \\[!WARNING]\n> A file that fails to parse stops the whole run with Acorn's syntax error,\n> such as `'import' and 'export' may appear only with 'sourceType: module' (1:0)`.\n> The message gives the line and column but not the file. ES modules are the\n> usual cause: leave them out with `ignore`.","summary":"Acorn parses every file with the same options:","examples":[],"children":[]},{"kind":"section","id":"what-it-produces","name":"What it produces","title":"What it produces","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"An array with one ESTree\n[`Program`](https://github.com/estree/estree/blob/master/es5.md#programs) node\nper file, as Acorn returns it, plus a `path` property: the file's path as the\nglob matched it, such as `lib/fs.js`. Files are collected as their chunks\nfinish, so the array isn't in input order, and its order can change between\nruns. Sort by `path` when your output needs to be stable.\n\nA generator with `dependsOn: '@doc-kit/core/ast-js'` receives this array. This\none lists the top-level functions of each file, with the line each starts on:\n\n```mjs displayName=\"functions.mjs\"\nimport { join } from 'node:path';\n\nimport getConfig from '@doc-kit/core/utils/configuration/index.mjs';\nimport { writeJSON } from '@doc-kit/core/utils/file.mjs';\n\nexport default {\n  name: 'functions',\n  description: 'Lists the top-level functions of each JavaScript file',\n  dependsOn: '@doc-kit/core/ast-js',\n\n  async generate(programs) {\n    const { output, minify } = getConfig('functions');\n\n    const functions = programs\n      .toSorted((a, b) => a.path.localeCompare(b.path))\n      .flatMap(program =>\n        program.body\n          .filter(node => node.type === 'FunctionDeclaration')\n          .map(node => ({\n            name: node.id.name,\n            file: program.path,\n            line: node.loc.start.line,\n          }))\n      );\n\n    if (output) {\n      await writeJSON(join(output, 'functions.json'), functions, minify);\n    }\n\n    return functions;\n  },\n};\n```\n\n```bash\nnpx doc-kit generate -t ./functions.mjs -i \"lib/**/*.js\" -o out\n```\n\n[Creating generators](https://doc-kit.nodejs.org/creating-generators) covers\nthe rest of the generator API.","summary":"An array with one ESTree `Program` node per file, as Acorn returns it, plus a `path` property: the file's path as the glob matched it, such as `lib/fs.js`. Files are collected as their chunks finish, so the array isn't in input order, and its order can change between runs. Sort by `path` when your output needs to be stable.","examples":[{"language":"mjs","displayName":"functions.mjs","code":"import { join } from 'node:path';\n\nimport getConfig from '@doc-kit/core/utils/configuration/index.mjs';\nimport { writeJSON } from '@doc-kit/core/utils/file.mjs';\n\nexport default {\n  name: 'functions',\n  description: 'Lists the top-level functions of each JavaScript file',\n  dependsOn: '@doc-kit/core/ast-js',\n\n  async generate(programs) {\n    const { output, minify } = getConfig('functions');\n\n    const functions = programs\n      .toSorted((a, b) => a.path.localeCompare(b.path))\n      .flatMap(program =>\n        program.body\n          .filter(node => node.type === 'FunctionDeclaration')\n          .map(node => ({\n            name: node.id.name,\n            file: program.path,\n            line: node.loc.start.line,\n          }))\n      );\n\n    if (output) {\n      await writeJSON(join(output, 'functions.json'), functions, minify);\n    }\n\n    return functions;\n  },\n};"},{"language":"bash","displayName":null,"code":"npx doc-kit generate -t ./functions.mjs -i \"lib/**/*.js\" -o out"}],"children":[]}]}