|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright 2025 Google LLC |
| 4 | + * SPDX-License-Identifier: BSD-3-Clause |
| 5 | + */ |
| 6 | + |
| 7 | +import * as fs from 'fs/promises'; |
| 8 | +import * as path from 'path'; |
| 9 | +import type {UserFacingPageData} from '../plugin'; |
| 10 | + |
| 11 | +interface KeywordRecord { |
| 12 | + urls: string[]; |
| 13 | + keywords: string[]; |
| 14 | +} |
| 15 | + |
| 16 | +interface KeywordModifiers { |
| 17 | + keywords: KeywordRecord[]; |
| 18 | +} |
| 19 | + |
| 20 | +/** |
| 21 | + * Adds keyword metadata to pages in the search index based on keyword modifiers defined in a JSON file. |
| 22 | + * Only processes keywords for production builds (when outputDir is '_site'). |
| 23 | + * |
| 24 | + * @param outputDir - The output directory for the build ('_dev' or '_site'). Keywords are only added for '_site' builds. |
| 25 | + * @param index - Array of page data objects to be enhanced with keywords |
| 26 | + * @returns The modified index array with keywords added to relevant pages. Returns empty array for dev builds. |
| 27 | + */ |
| 28 | +export async function addKeywords( |
| 29 | + outputDir: '_dev' | '_site', |
| 30 | + index: UserFacingPageData[] |
| 31 | +) { |
| 32 | + if (outputDir === '_dev') { |
| 33 | + return index; |
| 34 | + } |
| 35 | + |
| 36 | + // Path to the keyword modifiers JSON file. |
| 37 | + const KEYWORD_MODIFIERS_PATH = path.resolve( |
| 38 | + __dirname, |
| 39 | + `../../../../lit-dev-content/${outputDir}/search-modifiers/keywords.json` |
| 40 | + ); |
| 41 | + |
| 42 | + const fileContents = await fs.readFile(KEYWORD_MODIFIERS_PATH, 'utf-8'); |
| 43 | + const data = JSON.parse(fileContents) as KeywordModifiers; |
| 44 | + |
| 45 | + const keywordMap = new Map<string, Set<string>>(); |
| 46 | + |
| 47 | + // Create a map of urls to keywords associated with that url. |
| 48 | + for (const keywordRecord of data.keywords) { |
| 49 | + const keywords = new Set(keywordRecord.keywords); |
| 50 | + |
| 51 | + for (const url of keywordRecord.urls) { |
| 52 | + let keywordsForURL = keywordMap.get(url); |
| 53 | + if (!keywordsForURL) { |
| 54 | + keywordsForURL = new Set<string>(); |
| 55 | + keywordMap.set(url, keywordsForURL); |
| 56 | + } |
| 57 | + |
| 58 | + for (const keyword of keywords) { |
| 59 | + keywordsForURL.add(keyword); |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + // Add keywords to the index to each url that has keywords associated with it. |
| 65 | + for (const page of index) { |
| 66 | + const keywords = keywordMap.get(page.relativeUrl); |
| 67 | + if (keywords) { |
| 68 | + page.keywords = Array.from(keywords); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + return index; |
| 73 | +} |
0 commit comments