|
| 1 | +import { exec } from "node:child_process"; |
| 2 | +import { readdir, readFile, writeFile } from "node:fs/promises"; |
| 3 | +import process from "node:process"; |
| 4 | +import { promisify } from "node:util"; |
| 5 | + |
| 6 | +const execAsync = promisify(exec); |
| 7 | + |
| 8 | +async function run() { |
| 9 | + console.log("updating index.ts..."); |
| 10 | + let files = await readdir("./src"); |
| 11 | + files = files.filter((file) => file.endsWith(".ts") && file !== "index.ts"); |
| 12 | + |
| 13 | + const content = `// This file is auto-generated by scripts/update-index.ts |
| 14 | +// Do not edit this file directly. |
| 15 | +
|
| 16 | +${files.map((file) => `export * as ${file.replace(".ts", "").replace(".", "_")} from './${file.replace(".ts", "")}';`).join("\n")} |
| 17 | +`; |
| 18 | + |
| 19 | + // update index.ts |
| 20 | + await writeFile("./src/index.ts", content, { |
| 21 | + encoding: "utf-8", |
| 22 | + }); |
| 23 | + |
| 24 | + console.log("index.ts updated successfully!"); |
| 25 | + |
| 26 | + console.log("updating exports..."); |
| 27 | + // read pkg.json |
| 28 | + const pkg = JSON.parse(await readFile("./package.json", "utf-8")); |
| 29 | + |
| 30 | + const exports = pkg.exports; |
| 31 | + const newExports = {}; |
| 32 | + |
| 33 | + const exportEntries = Object.entries(exports); |
| 34 | + |
| 35 | + for (const file of files) { |
| 36 | + const name = file.replace(".ts", ""); |
| 37 | + exportEntries.push([`./${name}`, `./dist/${name}.js`]); |
| 38 | + } |
| 39 | + |
| 40 | + exportEntries.sort(([keyA], [keyB]) => { |
| 41 | + if (keyA === ".") return -1; // "." always first |
| 42 | + if (keyB === ".") return 1; |
| 43 | + if (keyA === "./package.json") return 1; // "./package.json" always last |
| 44 | + if (keyB === "./package.json") return -1; |
| 45 | + return keyA.localeCompare(keyB); // alphabetical sort for the rest |
| 46 | + }); |
| 47 | + |
| 48 | + for (const [key, value] of exportEntries) { |
| 49 | + newExports[key] = value; |
| 50 | + } |
| 51 | + |
| 52 | + await writeFile("./package.json", JSON.stringify({ ...pkg, exports: newExports }, null, 2), { |
| 53 | + encoding: "utf-8", |
| 54 | + }); |
| 55 | + console.log("exports updated successfully!"); |
| 56 | + |
| 57 | + await execAsync("npx eslint ./src/index.ts ./package.json --fix"); |
| 58 | +} |
| 59 | + |
| 60 | +run().catch((error) => { |
| 61 | + console.error(error); |
| 62 | + process.exit(1); |
| 63 | +}); |
0 commit comments