|
| 1 | +/// <reference path="./lang.d.ts"/> |
| 2 | + |
| 3 | +import ESBuild from 'esbuild' |
| 4 | +import { existsSync } from 'fs' |
| 5 | +import { readdir, readFile } from 'fs/promises' |
| 6 | +import { load } from 'js-yaml' |
| 7 | +import { join } from 'path' |
| 8 | + |
| 9 | +const filterYamlFiles = (file: string) => { |
| 10 | + return file.endsWith('.yml') || file.endsWith('.yaml') |
| 11 | +} |
| 12 | + |
| 13 | +const flattenStructuredLanguageFile = (file: StructuredLanguageFile): Record<string, string> => { |
| 14 | + const result: Record<string, string> = {} |
| 15 | + for (const key in file) { |
| 16 | + if (typeof file[key] === 'string') { |
| 17 | + result[key] = file[key] |
| 18 | + continue |
| 19 | + } |
| 20 | + |
| 21 | + for (const [subKey, value] of Object.entries(flattenStructuredLanguageFile(file[key]))) { |
| 22 | + result[`${key}.${subKey}`] = value |
| 23 | + } |
| 24 | + } |
| 25 | + return result |
| 26 | +} |
| 27 | + |
| 28 | +const langPlugin = ({ languageFolder }: LangPluginOptions) => |
| 29 | + ({ |
| 30 | + name: 'lang', |
| 31 | + setup(build) { |
| 32 | + if (!existsSync(languageFolder)) { |
| 33 | + throw new Error(`Language folder "${languageFolder}" does not exist.`) |
| 34 | + } |
| 35 | + |
| 36 | + build.onResolve({ filter: /LANGUAGES/ }, () => { |
| 37 | + return { |
| 38 | + path: languageFolder, |
| 39 | + namespace: 'language-file', |
| 40 | + } |
| 41 | + }) |
| 42 | + |
| 43 | + build.onLoad({ filter: /.*/, namespace: 'language-file' }, async () => { |
| 44 | + const translations: Record<string, LanguageDefinition> = {} |
| 45 | + |
| 46 | + const files = (await readdir(languageFolder)).filter(filterYamlFiles) |
| 47 | + if (files.length === 0) { |
| 48 | + console.warn(`No language files found in "${languageFolder}"`) |
| 49 | + } |
| 50 | + |
| 51 | + const watchFiles: string[] = [] |
| 52 | + |
| 53 | + for (const file of files) { |
| 54 | + const path = join(languageFolder, file) |
| 55 | + watchFiles.push(path) |
| 56 | + |
| 57 | + const name = file.replace(/\.(yml|yaml)$/, '') |
| 58 | + const structured: StructuredLanguageFile = await readFile(path, { |
| 59 | + encoding: 'utf-8', |
| 60 | + }).then(data => load(data, { filename: path }) as StructuredLanguageFile) |
| 61 | + const flattened = flattenStructuredLanguageFile(structured) |
| 62 | + |
| 63 | + translations[name] = { name, structured, flattened } |
| 64 | + } |
| 65 | + |
| 66 | + const contents = |
| 67 | + `export const LANGUAGES = ${JSON.stringify(translations)};` + |
| 68 | + `export const flattenStructuredLanguageFile = ${flattenStructuredLanguageFile.toString()};` |
| 69 | + |
| 70 | + return { |
| 71 | + contents, |
| 72 | + loader: 'js', |
| 73 | + watchFiles, |
| 74 | + } |
| 75 | + }) |
| 76 | + }, |
| 77 | + }) satisfies ESBuild.Plugin |
| 78 | + |
| 79 | +export default langPlugin |
0 commit comments