Open History to see the last commit
1import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises'
2import { dirname, relative, resolve } from 'node:path'
3β
4const projectDir = process.cwd()
5const esmDir = resolve(projectDir, 'dist')
6const outDir = resolve(process.cwd(), 'dist-cjs')
7const esmOnlyPackages = new Set(['lit'])
8const esmImportTypeRegex = /import type \{([^}]*)\} from (['"])([^'"]+)\2;/g
9const esmValueImportRegex = /import \{([^}]*)\} from (['"])([^'"]+)\2;/g
10const importTypeExpressionRegex = /import\((['"])([^'"]+)\1\)/g
11β
12await mkdir(outDir, { recursive: true })
13await writeFile(
14 resolve(outDir, 'package.json'),
15 `${JSON.stringify({ type: 'commonjs' }, null, 2)}\n`,
16 'utf8',
17)
18β
19for (const declarationFile of await findDeclarationFiles(esmDir)) {
20 const source = await readFile(declarationFile, 'utf8')
21 const relativePath = relative(esmDir, declarationFile)
22 const outputPath = resolve(outDir, relativePath.replace(/\.d\.ts$/, '.d.cts'))
23β
24 await mkdir(dirname(outputPath), { recursive: true })
25 await writeFile(outputPath, rewriteDeclaration(source), 'utf8')
26}
27β
28async function findDeclarationFiles(rootDir) {
29 const entries = await readdir(rootDir, { withFileTypes: true })
30 const files = []
31β
32 for (const entry of entries) {
33 const entryPath = resolve(rootDir, entry.name)
34β
35 if (entry.isDirectory()) {
36 files.push(...(await findDeclarationFiles(entryPath)))
37 continue
38 }
39β
40 if (entry.isFile() && entry.name.endsWith('.d.ts')) {
41 files.push(entryPath)
42 }
43 }
44β
45 return files
46}
47β
48function rewriteDeclaration(source) {
49 return source
50 .replace(/^\/\/# sourceMappingURL=.*$\n?/gm, '')
51 .replace(/(['"])(\.\.?\/[^'"]+)\.js\1/g, '$1$2.cjs$1')
52 .replace(esmImportTypeRegex, (match, specifiers, quote, packageName) => {
53 if (!esmOnlyPackages.has(packageName)) {
54 return match
55 }
56β
57 return `import type {${specifiers}} from ${quote}${packageName}${quote} with { "resolution-mode": "import" };`
58 })
59 .replace(esmValueImportRegex, (match, specifiers, quote, packageName) => {
60 if (!esmOnlyPackages.has(packageName)) {
61 return match
62 }
63β
64 return `import type {${specifiers}} from ${quote}${packageName}${quote} with { "resolution-mode": "import" };`
65 })
66 .replace(importTypeExpressionRegex, (match, quote, packageName) => {
67 if (packageName !== 'lit-html') {
68 return match
69 }
70β
71 return `import(${quote}${packageName}${quote}, { with: { "resolution-mode": "import" } })`
72 })
73}