publish-docsearch-config.js 1.6 KB

12345678910111213141516171819202122232425262728293031
  1. 'use strict'
  2. const fsp = require('node:fs/promises')
  3. const ospath = require('node:path')
  4. /**
  5. * An Antora extension that generates the docsearch config file from a Handlebars template and publishes it with the
  6. * site, where the scraper job can retrieve it.
  7. */
  8. module.exports.register = function ({ config: { templatePath = './docsearch/config.json.hbs' } }) {
  9. const expandPath = this.require('@antora/expand-path-helper')
  10. const handlebars = this.require('handlebars').create()
  11. handlebars.registerHelper('eq', (a, b) => a === b)
  12. handlebars.registerHelper('and', (a, b) => a && b)
  13. this.on('beforePublish', async ({ playbook, contentCatalog, siteCatalog }) => {
  14. templatePath = expandPath(templatePath, { dot: playbook.dir })
  15. const templateSrc = await fsp.readFile(templatePath, 'utf8')
  16. const templateBasename = ospath.basename(templatePath)
  17. const template = handlebars.compile(templateSrc, { noEscape: true, preventIndent: true, srcName: templateBasename })
  18. const latestVersions = contentCatalog.getComponentsSortedBy('name').reduce((accum, component) => {
  19. component.versions.forEach((version) => version.versionSegment !== undefined && accum.push(version))
  20. return accum
  21. }, [])
  22. const stopPages = contentCatalog.getPages((page) => {
  23. return page.out && ('page-archived' in page.asciidoc.attributes || 'page-noindex' in page.asciidoc.attributes)
  24. })
  25. const compiled = template({ latestVersions, site: playbook.site, stopPages })
  26. siteCatalog.addFile({ contents: Buffer.from(compiled), out: { path: 'docsearch-config.json' } })
  27. })
  28. }