Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/sxzz/rolldown-plugin-dts. A Rolldown plugin to generate and bundle dts files.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434import { fork, type ChildProcess } from 'node:child_process'import { existsSync } from 'node:fs'import { readFile, rm } from 'node:fs/promises'import path from 'node:path'import { parse } from '@babel/parser'import { createDebug } from 'obug'import { isolatedDeclarationSync } from 'rolldown/experimental'import { filename_to_dts, RE_DTS, RE_DTS_MAP, RE_JS, RE_JSON, RE_NODE_MODULES, RE_TS, RE_VUE, replaceTemplateName, resolveTemplateFn,} from './filename.ts'import { createContext, globalContext, invalidateContextFile, type TscContext,} from './tsc/context.ts'import { runTsgo } from './tsgo.ts'import type { OptionsResolved } from './options.ts'import type { TscOptions, TscResult } from './tsc/index.ts'import type { TscFunctions } from './tsc/worker.ts'import type { TSPropertySignature } from '@babel/types'import type { BirpcReturn } from 'birpc'import type { Plugin, SourceMapInput } from 'rolldown'
const debug = createDebug('rolldown-plugin-dts:generate')
const WORKER_URL = import.meta.WORKER_URL || './tsc/worker.ts'
export interface TsModule { /** `.ts` source code */ code: string /** `.ts` file name */ id: string isEntry: boolean}/** dts filename -> ts module */export type DtsMap = Map<string, TsModule>
export function createGeneratePlugin({ tsconfig, tsconfigRaw, build, incremental, cwd, oxc, emitDtsOnly, vue, tsMacro, parallel, eager, tsgo, newContext, emitJs, sourcemap,}: Pick< OptionsResolved, | 'cwd' | 'tsconfig' | 'tsconfigRaw' | 'build' | 'incremental' | 'oxc' | 'emitDtsOnly' | 'vue' | 'tsMacro' | 'parallel' | 'eager' | 'tsgo' | 'newContext' | 'emitJs' | 'sourcemap'>): Plugin { const dtsMap: DtsMap = new Map<string, TsModule>()
/** * A map of input id to output file name * * @example * * inputAlias = new Map([ * ['/absolute/path/to/src/source_file.ts', 'dist/foo/index'], * ]) */ const inputAliasMap = new Map<string, string>()
let childProcess: ChildProcess | undefined let rpc: BirpcReturn<TscFunctions> | undefined let tscModule: typeof import('./tsc/index.ts') let tscContext: TscContext | undefined let tsgoDist: string | undefined const rootDir = tsconfig ? path.dirname(tsconfig) : cwd
return { name: 'rolldown-plugin-dts:generate',
async buildStart(options) { if (tsgo) { tsgoDist = await runTsgo(rootDir, tsconfig, sourcemap, tsgo.path) } else if (!oxc) { // tsc if (parallel) { childProcess = fork(new URL(WORKER_URL, import.meta.url), { stdio: 'inherit', }) rpc = (await import('birpc')).createBirpc<TscFunctions>( {}, { post: (data) => childProcess!.send(data), on: (fn) => childProcess!.on('message', fn), }, ) } else { tscModule = await import('./tsc/index.ts') if (newContext) { tscContext = createContext() } } }
if (!Array.isArray(options.input)) { for (const [name, id] of Object.entries(options.input)) { debug('resolving input alias %s -> %s', name, id) let resolved = await this.resolve(id) if (!id.startsWith('./')) { resolved ||= await this.resolve(`./${id}`) } const resolvedId = resolved?.id || id debug('resolved input alias %s -> %s', id, resolvedId) inputAliasMap.set(resolvedId, name) } } },
outputOptions(options) { return { ...options, entryFileNames(chunk) { const { entryFileNames } = options const nameTemplate = resolveTemplateFn( entryFileNames || '[name].js', chunk, )
if (chunk.name.endsWith('.d')) { if (RE_DTS.test(nameTemplate)) { return replaceTemplateName(nameTemplate, chunk.name.slice(0, -2)) } if (RE_JS.test(nameTemplate)) { return nameTemplate.replace(RE_JS, '.$1ts') } }
return nameTemplate }, } },
resolveId(id) { if (dtsMap.has(id)) { debug('resolve dts id %s', id) return { id } } },
transform: { order: 'pre', filter: { id: { include: [RE_JS, RE_TS, RE_VUE, RE_JSON], exclude: [RE_DTS, RE_NODE_MODULES], }, }, handler(code, id) { const shouldEmit = !RE_JS.test(id) || emitJs
if (shouldEmit) { const mod = this.getModuleInfo(id) const isEntry = !!mod?.isEntry const dtsId = filename_to_dts(id) dtsMap.set(dtsId, { code, id, isEntry }) debug('register dts source: %s', id)
if (isEntry) { const name = inputAliasMap.get(id) this.emitFile({ type: 'chunk', id: dtsId, name: name ? `${name}.d` : undefined, }) } }
if (emitDtsOnly) { if (RE_JSON.test(id)) return '{}' return 'export { }' } }, },
load: { filter: { id: { include: [RE_DTS], exclude: [RE_NODE_MODULES], }, }, async handler(dtsId) { if (!dtsMap.has(dtsId)) return
const { code, id } = dtsMap.get(dtsId)! let dtsCode: string | undefined let map: SourceMapInput | undefined debug('generate dts %s from %s', dtsId, id)
if (tsgo) { if (RE_VUE.test(id)) throw new Error('tsgo does not support Vue files.') const dtsPath = path.resolve( tsgoDist!, path.relative(path.resolve(rootDir), filename_to_dts(id)), ) if (!existsSync(dtsPath)) { debug('[tsgo]', dtsPath, 'is missing') throw new Error( `tsgo did not generate dts file for ${id}, please check your tsconfig.`, ) }
dtsCode = await readFile(dtsPath, 'utf8')
const mapPath = `${dtsPath}.map` if (existsSync(mapPath)) { const mapRaw = await readFile(mapPath, 'utf8') map = { ...JSON.parse(mapRaw), sources: [id], } } } else if (oxc && !RE_VUE.test(id)) { const result = isolatedDeclarationSync(id, code, oxc) if (result.errors.length) { const [error] = result.errors return this.error({ message: error.message, frame: error.codeframe || undefined, }) } dtsCode = result.code if (result.map) { map = result.map map.sourcesContent = undefined } } else { const entries = eager ? undefined : Array.from(dtsMap.values()) .filter((v) => v.isEntry) .map((v) => v.id) const options: Omit<TscOptions, 'programs'> = { tsconfig, tsconfigRaw, build, incremental, cwd, entries, id, sourcemap, vue, tsMacro, context: tscContext, } let result: TscResult if (parallel) { result = await rpc!.tscEmit(options) } else { result = tscModule.tscEmit(options) } if (result.error) { return this.error(result.error) } dtsCode = result.code map = result.map
if (dtsCode && RE_JSON.test(id)) { // if contains invalid json keys if (dtsCode.includes('declare const _exports')) { if ( dtsCode.includes('declare const _exports: {') && !dtsCode.includes('\n}[];') ) { // patch: add named export const exports = collectJsonExports(dtsCode) let i = 0 dtsCode += exports .map((e) => { const valid = `_${e.replaceAll(/[^\w$]/g, '_')}${i++}` const jsonKey = JSON.stringify(e) return `declare let ${valid}: typeof _exports[${jsonKey}]\nexport { ${valid} as ${jsonKey} }` }) .join('\n') } } else { // patch: add default export const exportMap = collectJsonExportMap(dtsCode) dtsCode += `declare namespace __json_default_export { export { ${Array.from(exportMap.entries()) .map(([exported, local]) => exported === local ? exported : `${local} as ${exported}`, ) .join(', ')} }}export { __json_default_export as default }` } } }
return { code: dtsCode || '', map, } }, },
generateBundle: emitDtsOnly ? (options, bundle) => { for (const fileName of Object.keys(bundle)) { if ( bundle[fileName].type === 'chunk' && !RE_DTS.test(fileName) && !RE_DTS_MAP.test(fileName) ) { delete bundle[fileName] } } } : undefined,
async buildEnd() { childProcess?.kill() if (!debug.enabled && tsgoDist) { await rm(tsgoDist, { recursive: true, force: true }).catch(() => {}) } tsgoDist = undefined if (newContext) { tscContext = undefined } },
watchChange(id) { if (tscModule) { invalidateContextFile(tscContext || globalContext, id) } }, }}
function collectJsonExportMap(code: string): Map<string, string> { const exportMap = new Map<string, string>() const { program } = parse(code, { sourceType: 'module', plugins: [['typescript', { dts: true }]], errorRecovery: true, })
for (const decl of program.body) { if (decl.type === 'ExportNamedDeclaration') { // export declare let Hello: string; if (decl.declaration) { if (decl.declaration.type === 'VariableDeclaration') { for (const vdecl of decl.declaration.declarations) { if (vdecl.id.type === 'Identifier') { exportMap.set(vdecl.id.name, vdecl.id.name) } } } else if ( decl.declaration.type === 'TSModuleDeclaration' && decl.declaration.id.type === 'Identifier' ) { exportMap.set(decl.declaration.id.name, decl.declaration.id.name) } } else if (decl.specifiers.length) { for (const spec of decl.specifiers) { if ( spec.type === 'ExportSpecifier' && spec.exported.type === 'Identifier' ) { // declare let _class: string // export { _class as class } exportMap.set( spec.exported.name, spec.local.type === 'Identifier' ? spec.local.name : spec.exported.name, ) } } } } }
return exportMap}
/** `declare const _exports` mode */function collectJsonExports(code: string) { const exports: string[] = [] const { program } = parse(code, { sourceType: 'module', plugins: [['typescript', { dts: true }]], }) const members = (program.body as any)[0].declarations[0].id.typeAnnotation .typeAnnotation.members as TSPropertySignature[]
for (const member of members) { if (member.key.type === 'Identifier') { exports.push(member.key.name) } else if (member.key.type === 'StringLiteral') { exports.push(member.key.value) } }
return exports}