| 9 | * consumption time. |
| 10 | */ |
| 11 | export function dtsPathsTransformer( |
| 12 | mapping?: Record<string, string>, |
| 13 | externals?: (string | RegExp)[] |
| 14 | ): ts.TransformerFactory<ts.SourceFile | ts.Bundle> { |
| 15 | return (context: ts.TransformationContext) => { |
| 16 | if (!mapping) { |
| 17 | mapping = {}; |
| 18 | const options = context.getCompilerOptions(); |
| 19 | if (options.paths) { |
| 20 | for (const [k, v] of Object.entries(options.paths)) { |
| 21 | if (k.endsWith('*') && v[0].endsWith('*')) { |
| 22 | mapping[k.substring(0, k.length - 1)] = v[0].substring(0, v[0].length - 1); |
| 23 | } |
| 24 | } |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | const isExternal = (input: string) => { |
| 29 | if (!externals) { |
| 30 | return false; |
| 31 | } |
| 32 | for (const e of externals) { |
| 33 | if (typeof e === 'string') { |
| 34 | if (input === e) { |
| 35 | return true; |
| 36 | } |
| 37 | } else if (e instanceof RegExp) { |
| 38 | if (e.test(input)) { |
| 39 | return true; |
| 40 | } |
| 41 | } |
| 42 | } |
| 43 | return false; |
| 44 | }; |
| 45 | |
| 46 | const mapPath = (filePath: string, input: string): string | undefined => { |
| 47 | for (const [k, v] of Object.entries(mapping!)) { |
| 48 | if (input.startsWith(k) && !isExternal(input)) { |
| 49 | const absoluteFile = path.resolve(v, input.substring(k.length)); |
| 50 | return `./${path.relative(path.dirname(filePath), absoluteFile).replaceAll('\\', '/')}`; |
| 51 | } |
| 52 | } |
| 53 | return undefined; |
| 54 | }; |
| 55 | |
| 56 | return (source: ts.SourceFile | ts.Bundle) => { |
| 57 | const sourceFilePath = ts.isSourceFile(source) ? source.fileName : source.sourceFiles[0].fileName; |
| 58 | |
| 59 | const visitor = (node: ts.Node): ts.Node => { |
| 60 | if (ts.isExportDeclaration(node) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) { |
| 61 | const mapped = mapPath(sourceFilePath, node.moduleSpecifier.text); |
| 62 | if (mapped) { |
| 63 | return ts.factory.createExportDeclaration( |
| 64 | node.modifiers, |
| 65 | node.isTypeOnly, |
| 66 | node.exportClause, |
| 67 | ts.factory.createStringLiteral(mapped), |
| 68 | node.attributes |