publish-docsearch-config.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. 'use strict'
  2. const fsp = require('node:fs/promises')
  3. const ospath = require('node:path')
  4. /**
  5. * An Antora extension that generates a config file that controls the behavior of the docsearch scraper.
  6. *
  7. * This extension generates a docsearch config file by evaluating a Handlebars template (e.g.,
  8. * .github/actions/docsearch-config.json.hbs). It then publishes the output file to the root of the site
  9. * (docsearch-config.json). The docsearch scraper will retrieve for the config file from the published site.
  10. *
  11. * This extension will only add entries for the latest version in each release line. Additionally, if the page-archived
  12. * or page-noindex attribute is defined in the document header of the page, that page will be excluded from the index.
  13. */
  14. module.exports.register = function ({ config: { templatePath = './docsearch/config.json.hbs' } }) {
  15. const expandPath = this.require('@antora/expand-path-helper')
  16. const handlebars = this.require('handlebars').create()
  17. handlebars.registerHelper('eq', (a, b) => a === b)
  18. handlebars.registerHelper('and', (a, b) => a && b)
  19. this.on('beforePublish', async ({ playbook, contentCatalog, siteCatalog }) => {
  20. templatePath = expandPath(templatePath, { dot: playbook.dir })
  21. const templateSrc = await fsp.readFile(templatePath, 'utf8')
  22. const templateBasename = ospath.basename(templatePath)
  23. const template = handlebars.compile(templateSrc, { noEscape: true, preventIndent: true, srcName: templateBasename })
  24. const latestVersions = contentCatalog.getComponentsSortedBy('name').reduce((accum, component) => {
  25. component.versions.forEach((version) => version.versionSegment !== undefined && accum.push(version))
  26. return accum
  27. }, [])
  28. const stopPages = contentCatalog.getPages((page) => {
  29. return page.out && ('page-archived' in page.asciidoc.attributes || 'page-noindex' in page.asciidoc.attributes)
  30. })
  31. const compiled = template({ latestVersions, site: playbook.site, stopPages })
  32. siteCatalog.addFile({ contents: Buffer.from(compiled), out: { path: 'docsearch-config.json' } })
  33. })
  34. }