#!/usr/bin/env node import { join as pathJoin, basename as pathBasename } from "path"; import { readEnvFromFile } from "./readEnvFromFile"; import * as fs from "fs"; import { getProjectRoot } from "../tools/getProjectRoot"; const targetProjectDirPath = process.cwd(); const doUseJs = process.argv[2]?.toLowerCase() === "js"; const thisModuleName = require(pathJoin(getProjectRoot(), "package.json"))["name"]; const thisScriptName = pathBasename(__filename).split(".")[0]; const targetProjectSrcDirPath = pathJoin(targetProjectDirPath, "src"); fs.mkdirSync(targetProjectSrcDirPath, { "recursive": true }); fs.writeFileSync( pathJoin(targetProjectSrcDirPath, `env.${doUseJs ? "js" : "ts"}`), Buffer.from( [ '/* ', `* Automatically generated by ${thisModuleName}.`, '* If you wish to declare a new environment variable declare it in the .env file (prefixed by REACT_APP_)', `* then run 'npx ${thisScriptName}${doUseJs ? " js" : ""}' at the root of your project.`, '* This file will be updated.', '*/', `import { getEnvVarValue } from "${thisModuleName}";`, '', 'export const envNames = [', Object.keys(readEnvFromFile({ targetProjectDirPath, "target": ".env" })) .map(envName => ` "${envName}"`) .join(",\n"), `]${doUseJs ? "" : " as const"};`, doUseJs ? '' : '\nexport type EnvName = typeof envNames[number];\n', `let env${doUseJs ? "" : ": Record | undefined"} = undefined;`, '', 'export function getEnv() {', '', ' if (env === undefined) {', ` env = {}${doUseJs ? "" : " as Record"};`, ' for (const envName of envNames) {', ' env[envName] = getEnvVarValue(envName);', ' }', ' }', '', ' return env;', '', '}', '' ].join("\n"), "utf8" ) );