Created
June 20, 2024 08:37
-
-
Save sannajammeh/0d2ef984d9a076a90dae9ba27910ea5e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
copyFile, | |
readFile, | |
readdir, | |
unlink, | |
writeFile, | |
} from "node:fs/promises"; | |
import { basename } from "node:path"; | |
const CJS_DIR = new URL("./dist/cjs", import.meta.url).pathname; | |
const ESM_DIR = new URL("./dist/es", import.meta.url).pathname; | |
const stripComments = (content) => { | |
return content.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, "").trim(); | |
}; | |
const isTypeScriptDefinition = (content) => { | |
const stripped = stripComments(content); | |
const tsDefinitionPattern = | |
/declare\s+|export\s+interface|export\s+type|export\s+namespace|export\s+const|export\s+enum|export\s+function|export\s+class|export\s+abstract\s+class|export\s+var/; | |
return tsDefinitionPattern.test(stripped); | |
}; | |
async function renameFileExtension(path, extension) { | |
const newPath = path.replace(/\.js$/, extension); | |
await copyFile(path, newPath); | |
// Delete old file | |
await unlink(path); | |
return newPath; | |
} | |
async function processFile(file, dir) { | |
const path = `${dir}/${file}`; | |
if (!file.endsWith(".js")) { | |
return; | |
} | |
const content = await readFile(path, "utf8"); | |
if (!isTypeScriptDefinition(content)) { | |
return; | |
} | |
// replace the .js extension with .d.mts or .d.ts if in cjs dir | |
if (dir === CJS_DIR) { | |
return await renameFileExtension(path, ".d.ts"); | |
} else { | |
return await renameFileExtension(path, ".d.mts"); | |
} | |
} | |
async function transformDTS(files, dir) { | |
const fileMap = new Map(); | |
for await (const file of files) { | |
const path = await processFile(file, dir); | |
if (!path) { | |
// No match | |
continue; | |
} | |
// We have a new file path, now we need to get the exact fileName and replace all import statements in all files | |
const fileName = basename(path); | |
fileMap.set(file, fileName); | |
} | |
// Loop through all files and replace import statements | |
for (const filename of await readdir(dir)) { | |
const path = `${dir}/${filename}`; | |
for (const [old, newName] of Array.from(fileMap.entries())) { | |
const content = await readFile(path, "utf8"); | |
const newContent = content.replaceAll(old, newName); | |
if (newContent !== content) { | |
await writeFile(path, newContent); | |
} | |
} | |
} | |
} | |
await transformDTS(await readdir(CJS_DIR), CJS_DIR); | |
await transformDTS(await readdir(ESM_DIR), ESM_DIR); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment