|
1 | 1 | /* global console */ |
2 | 2 |
|
3 | | -import { copyFile, readdir } from 'node:fs/promises'; |
| 3 | +import { copyFile, readFile } from 'node:fs/promises'; |
4 | 4 | import path from 'node:path'; |
5 | 5 | import { fileURLToPath } from 'node:url'; |
6 | 6 |
|
7 | 7 | const __filename = fileURLToPath(import.meta.url); |
8 | 8 | const __dirname = path.dirname(__filename); |
| 9 | +const rootDir = path.resolve(__dirname, '..'); |
9 | 10 | const distDir = path.resolve(__dirname, '..', 'dist'); |
10 | | - |
11 | | -const findDeclarationFiles = async (directory) => { |
12 | | - const entries = await readdir(directory, { withFileTypes: true }); |
13 | | - const nestedFiles = await Promise.all( |
14 | | - entries.map(async (entry) => { |
15 | | - const resolvedPath = path.join(directory, entry.name); |
16 | | - |
17 | | - if (entry.isDirectory()) { |
18 | | - return findDeclarationFiles(resolvedPath); |
19 | | - } |
20 | | - |
21 | | - return entry.name.endsWith('.d.mts') ? [resolvedPath] : []; |
22 | | - }) |
| 11 | +const packageJsonPath = path.join(rootDir, 'package.json'); |
| 12 | + |
| 13 | +const getPublicDeclarationFiles = async () => { |
| 14 | + const packageJson = JSON.parse(await readFile(packageJsonPath, 'utf8')); |
| 15 | + const declarationFiles = new Set(); |
| 16 | + |
| 17 | + if (typeof packageJson.types === 'string') { |
| 18 | + declarationFiles.add(path.resolve(rootDir, packageJson.types)); |
| 19 | + } |
| 20 | + |
| 21 | + for (const exportDefinition of Object.values(packageJson.exports ?? {})) { |
| 22 | + if ( |
| 23 | + exportDefinition && |
| 24 | + typeof exportDefinition === 'object' && |
| 25 | + typeof exportDefinition.types === 'string' |
| 26 | + ) { |
| 27 | + declarationFiles.add(path.resolve(rootDir, exportDefinition.types)); |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + return [...declarationFiles].filter(fileName => |
| 32 | + fileName.startsWith(distDir) && fileName.endsWith('.d.ts') |
23 | 33 | ); |
24 | | - |
25 | | - return nestedFiles.flat(); |
26 | 34 | }; |
27 | 35 |
|
28 | 36 | try { |
29 | | - const declarationFiles = await findDeclarationFiles(distDir); |
| 37 | + const declarationFiles = await getPublicDeclarationFiles(); |
30 | 38 |
|
31 | 39 | await Promise.all( |
32 | 40 | declarationFiles.map(fileName => |
33 | 41 | copyFile( |
34 | | - fileName, |
35 | | - fileName.replace(/\.d\.mts$/, '.d.ts') |
| 42 | + fileName.replace(/\.d\.ts$/, '.d.mts'), |
| 43 | + fileName |
36 | 44 | ) |
37 | 45 | ) |
38 | 46 | ); |
39 | 47 | } catch (error) { |
40 | | - console.error('Unable to create .d.ts files from .d.mts build artifacts'); |
| 48 | + console.error('Unable to create public .d.ts files from .d.mts build artifacts'); |
41 | 49 | throw error; |
42 | 50 | } |
0 commit comments