|
| 1 | +// @ts-check |
| 2 | +import { exec } from "child_process"; |
| 3 | +import { access, readFile, writeFile } from "fs/promises"; |
| 4 | +import { join } from "path"; |
| 5 | +import stripComments from "strip-comments"; |
| 6 | +import { promisify } from "util"; |
| 7 | + |
| 8 | +import { getAllFiles } from "./getAllFiles.mjs"; |
| 9 | +import { getDeclarationDirname } from "./getDeclarationDirname.mjs"; |
| 10 | +import { getDownlevelDirname } from "./getDownlevelDirname.mjs"; |
| 11 | + |
| 12 | +const execPromise = promisify(exec); |
| 13 | + |
| 14 | +export const downlevelWorkspace = async (workspacesDir, workspaceName) => { |
| 15 | + const workspaceDir = join(workspacesDir, workspaceName); |
| 16 | + const downlevelDirname = await getDownlevelDirname(workspaceDir); |
| 17 | + const declarationDirname = await getDeclarationDirname(workspaceDir); |
| 18 | + |
| 19 | + const declarationDir = join(workspaceDir, declarationDirname); |
| 20 | + try { |
| 21 | + await access(declarationDir); |
| 22 | + } catch (error) { |
| 23 | + throw new Error( |
| 24 | + `The types for "${workspaceName}" do not exist.\n` + |
| 25 | + `Please build types for workspace "${workspaceDir}" before running downlevel-dts script.` |
| 26 | + ); |
| 27 | + } |
| 28 | + |
| 29 | + const downlevelDir = join(declarationDir, downlevelDirname); |
| 30 | + // Create downlevel-dts folder if it doesn't exist |
| 31 | + try { |
| 32 | + await access(downlevelDir); |
| 33 | + } catch (error) { |
| 34 | + await execPromise(["yarn", "downlevel-dts"].join(" "), { cwd: workspaceDir }); |
| 35 | + } |
| 36 | + |
| 37 | + // Strip comments from downlevel-dts files |
| 38 | + try { |
| 39 | + await access(downlevelDir); |
| 40 | + const files = await getAllFiles(downlevelDir); |
| 41 | + for (const downlevelTypesFilepath of files) { |
| 42 | + try { |
| 43 | + const content = await readFile(downlevelTypesFilepath, "utf8"); |
| 44 | + await writeFile(downlevelTypesFilepath, stripComments(content)); |
| 45 | + } catch (error) { |
| 46 | + console.error(`Error while stripping comments from "${downlevelTypesFilepath.replace(process.cwd(), "")}"`); |
| 47 | + console.error(error); |
| 48 | + } |
| 49 | + } |
| 50 | + } catch (error) { |
| 51 | + // downlevelDir is not present, do nothing. |
| 52 | + } |
| 53 | +}; |
0 commit comments