|
| 1 | +import type { Options as PrettierOptions } from 'prettier' |
| 2 | +import type { BundledLanguage, BundledTheme } from 'shiki' |
| 3 | +import { bundledLanguagesInfo, bundledThemesInfo } from 'shiki/bundle/full' |
| 4 | + |
| 5 | +export interface ShikiCodegenOptions { |
| 6 | + /** |
| 7 | + * The header to add to the generated code. |
| 8 | + * |
| 9 | + * @default '/* Generate by @shikijs/codegen *\/' |
| 10 | + */ |
| 11 | + header?: string |
| 12 | + |
| 13 | + /** |
| 14 | + * The languages to bundle. |
| 15 | + */ |
| 16 | + langs: readonly BundledLanguage[] |
| 17 | + |
| 18 | + /** |
| 19 | + * The themes to bundle. |
| 20 | + */ |
| 21 | + themes: readonly BundledTheme[] |
| 22 | + |
| 23 | + /** |
| 24 | + * The engine to use for syntax highlighting. |
| 25 | + */ |
| 26 | + engine: 'oniguruma' | 'javascript' | 'javascript-raw' |
| 27 | + |
| 28 | + /** |
| 29 | + * Use precompiled grammars. |
| 30 | + * Only available when `engine` is set to `javascript` or `javascript-raw`. |
| 31 | + */ |
| 32 | + precompiled?: boolean |
| 33 | + |
| 34 | + /** |
| 35 | + * Whether to generate TypeScript code. |
| 36 | + * |
| 37 | + * @default true |
| 38 | + */ |
| 39 | + typescript?: boolean |
| 40 | + |
| 41 | + /** |
| 42 | + * Generate shorthands for the highlighter. |
| 43 | + * |
| 44 | + * @default true |
| 45 | + */ |
| 46 | + shorthands?: boolean |
| 47 | + |
| 48 | + /** |
| 49 | + * Use Prettier to format the generated code. |
| 50 | + */ |
| 51 | + format?: boolean | PrettierOptions |
| 52 | +} |
| 53 | + |
| 54 | +export interface ShikiCodegenResult { |
| 55 | + code: string |
| 56 | +} |
| 57 | + |
| 58 | +export async function codegen(options: ShikiCodegenOptions): Promise<ShikiCodegenResult> { |
| 59 | + const { |
| 60 | + header = '/* Generate by @shikijs/codegen */', |
| 61 | + typescript = true, |
| 62 | + precompiled = false, |
| 63 | + format: _format = true, |
| 64 | + shorthands = true, |
| 65 | + } = options |
| 66 | + |
| 67 | + const ts = (code: string): string => typescript ? code : '' |
| 68 | + |
| 69 | + if (precompiled && options.engine !== 'javascript' && options.engine !== 'javascript-raw') |
| 70 | + throw new Error('Precompiled grammars are only available when using the JavaScript engine') |
| 71 | + |
| 72 | + const langs = options.langs.map((lang) => { |
| 73 | + const info = bundledLanguagesInfo.find(i => i.id === lang || i.aliases?.includes(lang)) |
| 74 | + if (!info) |
| 75 | + throw new Error(`Language ${lang} not found`) |
| 76 | + return info |
| 77 | + }) |
| 78 | + |
| 79 | + const themes = options.themes.map((theme) => { |
| 80 | + const info = bundledThemesInfo.find(i => i.id === theme) |
| 81 | + if (!info) |
| 82 | + throw new Error(`Theme ${theme} not found`) |
| 83 | + return info |
| 84 | + }) |
| 85 | + |
| 86 | + const langsCode = `{\n${langs.flatMap((lang) => { |
| 87 | + const ids = [lang.id, ...(lang.aliases || [])] |
| 88 | + return ids.map((id) => { |
| 89 | + return `${JSON.stringify(id)}: () => import('@shikijs/${precompiled ? 'langs-precompiled' : 'langs'}/${lang.id}'),\n` |
| 90 | + }) |
| 91 | + }).join('')}}` |
| 92 | + |
| 93 | + const themesCode = `{\n${themes.map((theme) => { |
| 94 | + return `${JSON.stringify(theme.id)}: () => import('@shikijs/themes/${theme.id}'),\n` |
| 95 | + }).join('')}}` |
| 96 | + |
| 97 | + const typeImports: Record<string, string[]> = { |
| 98 | + '@shikijs/types': ['HighlighterGeneric', 'DynamicImportThemeRegistration', 'DynamicImportLanguageRegistration'], |
| 99 | + } |
| 100 | + const imports: Record<string, string[]> = { |
| 101 | + '@shikijs/core': ['createdBundledHighlighter'], |
| 102 | + } |
| 103 | + const lines: string[] = [ |
| 104 | + '', |
| 105 | + ] |
| 106 | + const exports: string[] = [] |
| 107 | + const typeExports: string[] = [] |
| 108 | + |
| 109 | + if (typescript) { |
| 110 | + lines.push( |
| 111 | + '', |
| 112 | + `type BundledLanguage = ${langs.flatMap(lang => [lang.id, ...(lang.aliases || [])]).map(lang => `'${lang}'`).join(' | ')}`, |
| 113 | + `type BundledTheme = ${themes.map(theme => `'${theme.id}'`).join(' | ')}`, |
| 114 | + `type Highlighter = HighlighterGeneric<BundledLanguage, BundledTheme>`, |
| 115 | + '', |
| 116 | + ) |
| 117 | + typeExports.push('BundledLanguage', 'BundledTheme', 'Highlighter') |
| 118 | + } |
| 119 | + |
| 120 | + lines.push( |
| 121 | + '', |
| 122 | + `const bundledLanguages = ${langsCode}${ts(' as Record<BundledLanguage, DynamicImportLanguageRegistration>')}`, |
| 123 | + '', |
| 124 | + `const bundledThemes = ${themesCode}${ts(' as Record<BundledTheme, DynamicImportThemeRegistration>')}`, |
| 125 | + '', |
| 126 | + ) |
| 127 | + exports.push('bundledLanguages', 'bundledThemes') |
| 128 | + |
| 129 | + let engine: string |
| 130 | + |
| 131 | + if (options.engine === 'javascript') { |
| 132 | + imports['@shikijs/engine-javascript'] = ['createJavaScriptRegexEngine'] |
| 133 | + engine = 'createJavaScriptRegexEngine()' |
| 134 | + } |
| 135 | + else if (options.engine === 'javascript-raw') { |
| 136 | + imports['@shikijs/engine-javascript/raw'] = ['createJavaScriptRawEngine'] |
| 137 | + engine = 'createJavaScriptRawEngine()' |
| 138 | + } |
| 139 | + else { |
| 140 | + imports['@shikijs/engine-oniguruma'] = ['createOnigurumaEngine'] |
| 141 | + engine = 'createOnigurumaEngine(import(\'shiki/wasm\'))' |
| 142 | + } |
| 143 | + |
| 144 | + lines.push( |
| 145 | + '', |
| 146 | + `const createHighlighter = /* @__PURE__ */ createdBundledHighlighter${ts('<BundledLanguage, BundledTheme>')}({`, |
| 147 | + ` langs: bundledLanguages,`, |
| 148 | + ` themes: bundledThemes,`, |
| 149 | + ` engine: () => ${engine}`, |
| 150 | + `})`, |
| 151 | + ) |
| 152 | + exports.push('createHighlighter') |
| 153 | + |
| 154 | + if (shorthands) { |
| 155 | + imports['@shikijs/core'].push('createSingletonShorthands') |
| 156 | + const shorthandFunctions = [ |
| 157 | + 'codeToHtml', |
| 158 | + 'codeToHast', |
| 159 | + 'codeToTokensBase', |
| 160 | + 'codeToTokens', |
| 161 | + 'codeToTokensWithThemes', |
| 162 | + 'getSingletonHighlighter', |
| 163 | + 'getLastGrammarState', |
| 164 | + ] |
| 165 | + lines.push( |
| 166 | + '', |
| 167 | + `const { ${shorthandFunctions.join(', ')} } = /* @__PURE__ */ createSingletonShorthands${ts('<BundledLanguage,BundledTheme>')}(createHighlighter)`, |
| 168 | + ) |
| 169 | + exports.push( |
| 170 | + ...shorthandFunctions, |
| 171 | + ) |
| 172 | + } |
| 173 | + |
| 174 | + // Imports |
| 175 | + lines.unshift( |
| 176 | + Object.entries(imports).map(([module, imports]) => { |
| 177 | + return `import { ${imports.sort().join(', ')} } from '${module}'` |
| 178 | + }, |
| 179 | + ).join('\n'), |
| 180 | + ) |
| 181 | + |
| 182 | + if (typescript) { |
| 183 | + lines.unshift( |
| 184 | + Object.entries(typeImports).map(([module, types]) => { |
| 185 | + return `import type { ${types.sort().join(', ')} } from '${module}'` |
| 186 | + }, |
| 187 | + ).join('\n'), |
| 188 | + ) |
| 189 | + } |
| 190 | + |
| 191 | + // Exports |
| 192 | + lines.push( |
| 193 | + '', |
| 194 | + `export { ${exports.sort().join(', ')} }`, |
| 195 | + ) |
| 196 | + if (typescript) { |
| 197 | + lines.push( |
| 198 | + `export type { ${typeExports.sort().join(', ')} }`, |
| 199 | + ) |
| 200 | + } |
| 201 | + |
| 202 | + lines.unshift(header) |
| 203 | + |
| 204 | + // Format code |
| 205 | + let code = lines.join('\n') |
| 206 | + if (_format) { |
| 207 | + const { format } = await import('prettier') |
| 208 | + const prettierOptions: PrettierOptions = { |
| 209 | + parser: typescript ? 'typescript' : 'babel', |
| 210 | + semi: false, |
| 211 | + tabWidth: 2, |
| 212 | + useTabs: false, |
| 213 | + singleQuote: true, |
| 214 | + trailingComma: 'all', |
| 215 | + ...(_format === true ? {} : _format), |
| 216 | + } |
| 217 | + code = await format(code, prettierOptions) |
| 218 | + } |
| 219 | + |
| 220 | + return { |
| 221 | + code, |
| 222 | + } |
| 223 | +} |
0 commit comments