| 1 | import type { VirtualModuleTemplate } from './types' |
| 2 | import { builtinModules } from 'node:module' |
| 3 | |
| 4 | import { uniq } from '@antfu/utils' |
| 5 | import fg from 'fast-glob' |
| 6 | import { join, resolve } from 'pathe' |
| 7 | import { toAtFS } from '../resolver' |
| 8 | |
| 9 | export const templateMonacoTypes: VirtualModuleTemplate = { |
| 10 | id: '/@slidev/monaco-types', |
| 11 | getContent: async ({ userRoot, data, utils }) => { |
| 12 | if (!data.features.monaco) |
| 13 | return '' |
| 14 | const typesRoot = join(userRoot, 'snippets') |
| 15 | const files = await fg(['**/*.ts', '**/*.mts', '**/*.cts'], { cwd: typesRoot }) |
| 16 | let result = 'import { addFile } from "@slidev/client/setup/monaco.ts"\n' |
| 17 | |
| 18 | // User snippets |
| 19 | for (const file of files) { |
| 20 | const url = `${toAtFS(resolve(typesRoot, file))}?monaco-types&raw` |
| 21 | result += `addFile(() => import(${JSON.stringify(url)}), ${JSON.stringify(file)})\n` |
| 22 | } |
| 23 | |
| 24 | // Copied from https://github.com/microsoft/TypeScript-Website/blob/v2/packages/ata/src/edgeCases.ts |
| 25 | // Converts some of the known global imports to node so that we grab the right info |
| 26 | function mapModuleNameToModule(moduleSpecifier: string) { |
| 27 | if (moduleSpecifier.startsWith('node:')) |
| 28 | return 'node' |
| 29 | if (builtinModules.includes(moduleSpecifier)) |
| 30 | return 'node' |
| 31 | const mainPackageName = moduleSpecifier.split('/')[0] |
| 32 | if (builtinModules.includes(mainPackageName) && !mainPackageName.startsWith('@')) |
| 33 | return 'node' |
| 34 | |
| 35 | // strip module filepath e.g. lodash/identity => lodash |
| 36 | const [a = '', b = ''] = moduleSpecifier.split('/') |
| 37 | const moduleName = a.startsWith('@') ? `${a}/${b}` : a |
| 38 | |
| 39 | return moduleName |
| 40 | } |
| 41 | |
| 42 | // Dependencies |
| 43 | let deps = [...data.config.monacoTypesAdditionalPackages] |
| 44 | if (data.config.monacoTypesSource === 'local') |
| 45 | deps.push(...data.features.monaco.types) |
| 46 | |
| 47 | deps = uniq(deps.map((specifier) => { |
| 48 | if (specifier[0] === '.') |
| 49 | return '' |
| 50 | return mapModuleNameToModule(specifier) |
| 51 | }).filter(Boolean)) |
| 52 | deps = deps.filter(pkg => !utils.isMonacoTypesIgnored(pkg)) |
| 53 | |
| 54 | for (const pkg of deps) { |
| 55 | result += `import(${JSON.stringify(`/@slidev-monaco-types/resolve?${new URLSearchParams({ pkg })}`)})\n` |
| 56 | } |
| 57 | |
| 58 | return result |
| 59 | }, |
| 60 | } |
| 61 |