@newcode-team/env 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -7
- package/dist/cli.mjs +14 -4
- package/dist/cli.mjs.map +1 -1
- package/dist/{config-DdWBrqcV.mjs → config-DOtqBeMb.mjs} +3 -7
- package/dist/config-DOtqBeMb.mjs.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/config-DdWBrqcV.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -39,7 +39,7 @@ Requires Node 24+.
|
|
|
39
39
|
| `newenv <command> [args]` | Run with the selected environment |
|
|
40
40
|
| `newenv use <name>` | Switch environment (`local` deletes `.envs/current`) |
|
|
41
41
|
| `newenv status` | Active environment and its files, never values |
|
|
42
|
-
| `newenv init` | Create `.envs/`, gitignore rules
|
|
42
|
+
| `newenv init` | Create `.envs/`, gitignore rules, `.envs/.env.local` and `newenv.config.ts` |
|
|
43
43
|
| `newenv -- <command>` | Run a program named `use`, `status` or `init` |
|
|
44
44
|
|
|
45
45
|
Options go before the command, and parsing stops at the first argument that isn't one: `newenv next dev --turbopack` passes `--turbopack` to Next.
|
|
@@ -56,10 +56,10 @@ Outside package scripts, run it with `pnpm newenv use staging` or `pnpm exec new
|
|
|
56
56
|
|
|
57
57
|
1. **Passthrough:** with a `passthrough` variable set, the command runs as is with the existing env. None by default.
|
|
58
58
|
2. **Root env files** (`.env`, `.env.local`, `.env.development`, `.env.production` and their `.local` variants): refused, with the `mv` command.
|
|
59
|
-
3. **Forbidden base keys** (`
|
|
59
|
+
3. **Forbidden base keys** (`forbiddenInBase`): refused in `.envs/.env`, since the base applies to every environment. None by default.
|
|
60
60
|
4. **Missing environment file:** refused, with a hint.
|
|
61
61
|
5. **Banner** on stderr outside local: a yellow badge, red for production, plus the script and files.
|
|
62
|
-
6. **Confirmation** for `confirmScripts
|
|
62
|
+
6. **Confirmation** for `confirmScripts`, matched on `npm_lifecycle_event`, and for `--confirm`: `y/N`, or typing the name for production. Without a TTY it aborts, so agents and CI can't run them by accident. Local never asks. No scripts by default.
|
|
63
63
|
7. **Runs** the command with inherited stdio, passes the exit code through and forwards signals.
|
|
64
64
|
|
|
65
65
|
### Switching
|
|
@@ -81,9 +81,10 @@ pnpm newenv init
|
|
|
81
81
|
Created .envs/
|
|
82
82
|
Updated .gitignore
|
|
83
83
|
Created .envs/.env.local from .envs/.env.example
|
|
84
|
+
Created newenv.config.ts
|
|
84
85
|
```
|
|
85
86
|
|
|
86
|
-
The example is the first of `.envs/.env.example`, `.example-env` and `.env.example`. Existing files are kept. The gitignore rules:
|
|
87
|
+
The example is the first of `.envs/.env.example`, `.example-env` and `.env.example`. Existing files are kept. No script or base key is guarded by default, so the config starts with `db:push`, `db:migrate`, `db:seed` and `DATABASE_URL` to edit. The gitignore rules:
|
|
87
88
|
|
|
88
89
|
```gitignore
|
|
89
90
|
# newenv
|
|
@@ -97,7 +98,7 @@ A `.env*` pattern also matches the `.envs` folder, and git can't re-include a fi
|
|
|
97
98
|
|
|
98
99
|
## Config
|
|
99
100
|
|
|
100
|
-
Optional. `newenv.config.ts`, `.mjs` or `.js` in the project root
|
|
101
|
+
Optional. `newenv.config.ts`, `.mjs` or `.js` in the project root. `newenv init` creates one:
|
|
101
102
|
|
|
102
103
|
```ts
|
|
103
104
|
import { defineConfig } from "@newcode-team/env";
|
|
@@ -116,8 +117,8 @@ export default defineConfig({
|
|
|
116
117
|
|---|---|---|
|
|
117
118
|
| `environments.<name>.color` | `red` for production, else `yellow` | Badge: `red`, `yellow`, `green`, `blue`, `magenta`, `cyan`, `gray` |
|
|
118
119
|
| `environments.<name>.confirm` | `"type-name"` for production, `false` for local, else `true` | `true`: y/N. `"type-name"`: type the name, and `use` asks first. `false`: never |
|
|
119
|
-
| `confirmScripts` | `[
|
|
120
|
-
| `forbiddenInBase` | `[
|
|
120
|
+
| `confirmScripts` | `[]` | Scripts that ask before running |
|
|
121
|
+
| `forbiddenInBase` | `[]` | Keys refused in `.envs/.env` |
|
|
121
122
|
| `passthrough` | `[]` | Variables that skip the files, e.g. `["VERCEL"]` on a host that provides the env |
|
|
122
123
|
| `example` | | Source for `newenv init` |
|
|
123
124
|
|
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { n as environmentSettings, r as loadConfig } from "./config-
|
|
2
|
+
import { n as environmentSettings, r as loadConfig } from "./config-DOtqBeMb.mjs";
|
|
3
3
|
import { appendFileSync, constants, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
import { Command } from "commander";
|
|
@@ -8,7 +8,7 @@ import { expand } from "dotenv-expand";
|
|
|
8
8
|
import { styleText } from "node:util";
|
|
9
9
|
import spawn from "cross-spawn";
|
|
10
10
|
// package.json
|
|
11
|
-
var version = "0.1.
|
|
11
|
+
var version = "0.1.2";
|
|
12
12
|
// src/env.ts
|
|
13
13
|
const envsDir = ".envs";
|
|
14
14
|
const baseFile = ".envs/.env";
|
|
@@ -175,6 +175,13 @@ const exampleFiles = [
|
|
|
175
175
|
".example-env",
|
|
176
176
|
".env.example"
|
|
177
177
|
];
|
|
178
|
+
const configTemplate = `import type { Config } from "@newcode-team/env";
|
|
179
|
+
|
|
180
|
+
export default {
|
|
181
|
+
confirmScripts: ["db:push", "db:migrate", "db:seed"],
|
|
182
|
+
forbiddenInBase: ["DATABASE_URL"],
|
|
183
|
+
} satisfies Config;
|
|
184
|
+
`;
|
|
178
185
|
const program = new Command("newenv").description("Run a command with the env files of the selected environment").usage("[options] <command> [args...]").version(version, "-v, --version", "Show version").helpOption("-h, --help", "Show help").enablePositionalOptions().passThroughOptions().option("--confirm", "Ask before running, as for confirmScripts").argument("[command...]", "Command to run. Put -- before one named use, status or init").configureOutput({ outputError: (message, write) => write(`newenv: ${message.replace(/^error: /, "")}`) }).action(async (command, options) => {
|
|
179
186
|
const [name, ...args] = command;
|
|
180
187
|
if (!name) return program.help({ error: argv.length > 0 });
|
|
@@ -233,7 +240,7 @@ if (argv[argv.findIndex((arg) => arg === "--" || !arg.startsWith("-"))] !== "--"
|
|
|
233
240
|
["Problem", problem]
|
|
234
241
|
].filter(([, value]) => value !== void 0).map(([label, value]) => `${label?.padEnd(12)} ${value}`).join("\n"));
|
|
235
242
|
});
|
|
236
|
-
program.command("init").description("Set up .envs/, the gitignore rules
|
|
243
|
+
program.command("init").description("Set up .envs/, the gitignore rules, .envs/.env.local and the config").action(async () => {
|
|
237
244
|
const config = await loadConfig(cwd);
|
|
238
245
|
const dir = join(cwd, envsDir);
|
|
239
246
|
const dirExists = existsSync(dir);
|
|
@@ -252,10 +259,13 @@ if (argv[argv.findIndex((arg) => arg === "--" || !arg.startsWith("-"))] !== "--"
|
|
|
252
259
|
if (example) copyFileSync(join(cwd, example), local, constants.COPYFILE_EXCL);
|
|
253
260
|
else writeFileSync(local, "", { flag: "wx" });
|
|
254
261
|
}
|
|
262
|
+
const configFile = config.file ?? "newenv.config.ts";
|
|
263
|
+
if (!config.file) writeFileSync(join(cwd, configFile), configTemplate, { flag: "wx" });
|
|
255
264
|
console.log([
|
|
256
265
|
`${dirExists ? "Exists " : "Created"} .envs/`,
|
|
257
266
|
`${gitignoreDone ? "Exists " : "Updated"} .gitignore`,
|
|
258
|
-
localExists ? "Exists .envs/.env.local" : `Created .envs/.env.local ${example ? `from ${example}` : "(empty, no example file)"}
|
|
267
|
+
localExists ? "Exists .envs/.env.local" : `Created .envs/.env.local ${example ? `from ${example}` : "(empty, no example file)"}`,
|
|
268
|
+
`${config.file ? "Exists " : "Created"} ${configFile}`
|
|
259
269
|
].join("\n"));
|
|
260
270
|
});
|
|
261
271
|
}
|
package/dist/cli.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.mjs","names":[],"sources":["../package.json","../src/env.ts","../src/prompt.ts","../src/run.ts","../src/cli.ts"],"sourcesContent":["","import { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { parse } from \"dotenv\";\nimport { expand } from \"dotenv-expand\";\nimport type { ResolvedConfig } from \"./config\";\n\nexport const envsDir = \".envs\";\nexport const baseFile = \".envs/.env\";\nexport const currentFile = \".envs/current\";\n\n// Frameworks like Next.js load these from the project root on their own, which would mix them\n// into every environment\nexport const rootEnvFiles = [\n \".env\",\n \".env.local\",\n \".env.development\",\n \".env.development.local\",\n \".env.production\",\n \".env.production.local\",\n];\n\n/**\n * The selected environment: the name in .envs/current, or local\n */\nexport function currentEnvironment(cwd: string): string {\n const file = join(cwd, currentFile);\n return (existsSync(file) && readFileSync(file, \"utf8\").trim()) || \"local\";\n}\n\n/**\n * The environments with a .envs/.env.<name> file\n */\nexport function listEnvironments(cwd: string): string[] {\n const dir = join(cwd, envsDir);\n return existsSync(dir)\n ? readdirSync(dir)\n .map((file) => /^\\.env\\.([\\w-]+)$/.exec(file)?.[1])\n .filter((name): name is string => name !== undefined && name !== \"example\")\n .toSorted()\n : [];\n}\n\n/**\n * Throws when root env files exist, the base holds forbidden keys or the environment file is missing\n */\nexport function checkFiles(cwd: string, config: ResolvedConfig, name: string): void {\n const rootFiles = rootEnvFiles.filter((file) => existsSync(join(cwd, file)));\n if (rootFiles.length > 0) {\n throw new Error(\n `${rootFiles.join(\", \")} in the project root. Move into .envs/: mv -n ${rootFiles.join(\" \")} .envs/`,\n );\n }\n\n const base = join(cwd, baseFile);\n const forbidden = existsSync(base)\n ? Object.keys(parse(readFileSync(base))).filter((key) => config.forbiddenInBase.includes(key))\n : [];\n if (forbidden.length > 0) {\n throw new Error(\n `${forbidden.join(\", \")} in the shared ${baseFile}. Move to .envs/.env.<name> for each environment.`,\n );\n }\n\n const envFile = `.envs/.env.${name}`;\n if (!existsSync(join(cwd, envFile))) {\n throw new Error(\n name === \"local\"\n ? `${envFile} not found. Create it with: newenv init`\n : `${envFile} not found. Switch back with: newenv use local`,\n );\n }\n}\n\n/**\n * Merges the shell env, the base and the environment file: the last one wins. Expands variables\n * over the merged env, the same way dotenv-cli does.\n */\nexport function loadEnv(\n cwd: string,\n name: string,\n shellEnv: NodeJS.ProcessEnv,\n): { env: Record<string, string>; files: string[] } {\n const files = [baseFile, `.envs/.env.${name}`].filter((file) => existsSync(join(cwd, file)));\n const env: Record<string, string> = Object.assign(\n {},\n shellEnv,\n ...files.map((file) => parse(readFileSync(join(cwd, file)))),\n );\n expand({ parsed: env, processEnv: env });\n return { env, files };\n}\n","import type { Readable, Writable } from \"node:stream\";\n\nexport interface Streams {\n input: Readable & { isTTY?: boolean };\n output: Writable;\n}\n\n/**\n * Asks y/N, or to type the name for `\"type-name\"`. Ctrl+C answers no. Throws without a TTY, so\n * agents and CI can't confirm by accident.\n */\nexport async function confirm(\n mode: true | \"type-name\",\n name: string,\n question: string,\n streams: Streams,\n): Promise<boolean> {\n if (!streams.input.isTTY) {\n throw new Error(`${question}: needs confirmation, no TTY. Aborted.`);\n }\n\n // Imported on demand: most runs never ask, and inquirer is the slowest dependency to load\n try {\n if (mode === \"type-name\") {\n const { default: input } = await import(\"@inquirer/input\");\n return (\n (await input({ message: `${question}? Type \"${name}\" to confirm:` }, streams)) === name\n );\n }\n const { default: confirmPrompt } = await import(\"@inquirer/confirm\");\n return await confirmPrompt({ message: `${question}?`, default: false }, streams);\n } catch (error) {\n if (error instanceof Error && error.name === \"ExitPromptError\") {\n return false;\n }\n throw error;\n }\n}\n","import { styleText } from \"node:util\";\nimport spawn from \"cross-spawn\";\nimport { type Color, environmentSettings, type ResolvedConfig } from \"./config\";\nimport { checkFiles, currentEnvironment, loadEnv } from \"./env\";\nimport { confirm, type Streams } from \"./prompt\";\n\nexport interface Context {\n cwd: string;\n env: NodeJS.ProcessEnv;\n config: ResolvedConfig;\n streams: Streams;\n}\n\nconst badgeStyles = {\n red: [\"bgRed\", \"white\", \"bold\"],\n yellow: [\"bgYellow\", \"black\"],\n green: [\"bgGreen\", \"black\"],\n blue: [\"bgBlue\", \"white\"],\n magenta: [\"bgMagenta\", \"white\"],\n cyan: [\"bgCyan\", \"black\"],\n gray: [\"bgGray\", \"white\"],\n} as const satisfies Record<Color, readonly string[]>;\n\nconst signals = [\"SIGINT\", \"SIGTERM\", \"SIGHUP\"] as const;\n\n/**\n * Checks the files, prints the banner, confirms and returns the env to run a command with\n */\nexport async function prepareRun(\n command: string,\n { cwd, env, config, streams }: Context,\n forceConfirm = false,\n): Promise<NodeJS.ProcessEnv> {\n if (config.passthrough.some((key) => env[key])) {\n return env;\n }\n\n const name = currentEnvironment(cwd);\n checkFiles(cwd, config, name);\n\n const loaded = loadEnv(cwd, name, env);\n const settings = environmentSettings(config, name);\n const script = env.npm_lifecycle_event ?? command;\n\n if (name !== \"local\") {\n const badge = styleText([...badgeStyles[settings.color]], ` ${name.toUpperCase()} `, {\n stream: streams.output,\n });\n streams.output.write(`${badge} ${script} uses ${loaded.files.join(\" + \")}\\n`);\n }\n\n const asks = forceConfirm || config.confirmScripts.includes(env.npm_lifecycle_event ?? \"\");\n if (\n asks &&\n settings.confirm &&\n !(await confirm(settings.confirm, name, `Run ${script} against ${name}`, streams))\n ) {\n throw new Error(\"Aborted.\");\n }\n\n return loaded.env;\n}\n\n/**\n * Runs a command with inherited stdio and forwards signals to it until it exits. In a terminal,\n * Ctrl+C and hangups already reach the whole foreground process group, the command included, so\n * only SIGTERM is forwarded there. newenv still catches the others, to exit after the command.\n */\nexport function spawnCommand(\n command: string,\n args: string[],\n env: NodeJS.ProcessEnv,\n): Promise<{ code: number | null; signal: NodeJS.Signals | null }> {\n return new Promise((resolve, reject) => {\n const child = spawn(command, args, { stdio: \"inherit\", env });\n const forward = (signal: NodeJS.Signals) => {\n if (signal === \"SIGTERM\" || !process.stdin.isTTY) {\n child.kill(signal);\n }\n };\n const stopForwarding = () => {\n signals.forEach((signal) => {\n process.off(signal, forward);\n });\n };\n signals.forEach((signal) => {\n process.on(signal, forward);\n });\n\n child.on(\"error\", (error) => {\n stopForwarding();\n reject(error);\n });\n child.on(\"exit\", (code, signal) => {\n stopForwarding();\n resolve({ code, signal });\n });\n });\n}\n","#!/usr/bin/env node\nimport {\n appendFileSync,\n constants,\n copyFileSync,\n existsSync,\n mkdirSync,\n readFileSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\nimport { Command } from \"commander\";\nimport { version } from \"../package.json\";\nimport { environmentSettings, loadConfig } from \"./config\";\nimport {\n baseFile,\n checkFiles,\n currentEnvironment,\n currentFile,\n envsDir,\n listEnvironments,\n} from \"./env\";\nimport { confirm } from \"./prompt\";\nimport { prepareRun, spawnCommand } from \"./run\";\n\nconst argv = process.argv.slice(2);\nconst cwd = process.cwd();\nconst streams = { input: process.stdin, output: process.stderr };\n\n// `.env*` patterns in existing gitignores also match the .envs folder, and git can't re-include a\n// file in an ignored folder. So the folder is re-included first, then its contents ignored.\nconst gitignoreBlock = [\"# newenv\", \"/.env*\", \"!/.envs/\", \"/.envs/*\", \"!/.envs/.env.example\"].join(\n \"\\n\",\n);\n\nconst exampleFiles = [\".envs/.env.example\", \".example-env\", \".env.example\"];\n\nconst program = new Command(\"newenv\")\n .description(\"Run a command with the env files of the selected environment\")\n .usage(\"[options] <command> [args...]\")\n .version(version, \"-v, --version\", \"Show version\")\n .helpOption(\"-h, --help\", \"Show help\")\n // Options after the command belong to the command\n .enablePositionalOptions()\n .passThroughOptions()\n .option(\"--confirm\", \"Ask before running, as for confirmScripts\")\n .argument(\"[command...]\", \"Command to run. Put -- before one named use, status or init\")\n .configureOutput({\n outputError: (message, write) => write(`newenv: ${message.replace(/^error: /, \"\")}`),\n })\n .action(async (command: string[], options: { confirm?: boolean }) => {\n const [name, ...args] = command;\n if (!name) {\n return program.help({ error: argv.length > 0 });\n }\n\n const config = await loadConfig(cwd);\n const env = await prepareRun(name, { cwd, env: process.env, config, streams }, options.confirm);\n const { code, signal } = await spawnCommand(name, args, env).catch(\n (error: NodeJS.ErrnoException) => {\n if (error.code !== \"ENOENT\") {\n throw error;\n }\n console.error(`newenv: command not found: ${name}`);\n return { code: 127, signal: null };\n },\n );\n if (signal) {\n process.kill(process.pid, signal);\n }\n process.exitCode = code ?? 1;\n });\n\n// Commander still matches subcommands after --, so `newenv -- status` gets none\nif (argv[argv.findIndex((arg) => arg === \"--\" || !arg.startsWith(\"-\"))] !== \"--\") {\n program\n .command(\"use\")\n .description(\"Switch environment\")\n .argument(\"<name>\", \"Environment, local deletes .envs/current\")\n .action(async (name: string) => {\n const envFile = `.envs/.env.${name}`;\n if (name === \"local\") {\n rmSync(join(cwd, currentFile), { force: true });\n console.log(\n existsSync(join(cwd, envFile))\n ? \"Switched to local.\"\n : `Switched to local. ${envFile} not found. Create it with: newenv init`,\n );\n return;\n }\n\n const environments = listEnvironments(cwd);\n if (!environments.includes(name)) {\n throw new Error(`${envFile} not found. Available: ${environments.join(\", \") || \"none\"}`);\n }\n\n const config = await loadConfig(cwd);\n if (\n environmentSettings(config, name).confirm === \"type-name\" &&\n !(await confirm(true, name, `Switch to ${name}`, streams))\n ) {\n throw new Error(\"Aborted.\");\n }\n\n writeFileSync(join(cwd, currentFile), `${name}\\n`);\n console.log(`Switched to ${name}.`);\n });\n\n program\n .command(\"status\")\n .description(\"Show the environment and its files\")\n .action(async () => {\n const config = await loadConfig(cwd);\n const name = currentEnvironment(cwd);\n const envFile = `.envs/.env.${name}`;\n const files = [\n ...(existsSync(join(cwd, baseFile)) ? [baseFile] : []),\n existsSync(join(cwd, envFile)) ? envFile : `${envFile} (missing)`,\n ];\n const passthrough = config.passthrough.filter((key) => process.env[key]);\n const problem = (() => {\n try {\n checkFiles(cwd, config, name);\n return undefined;\n } catch (error) {\n return (error as Error).message;\n }\n })();\n\n console.log(\n [\n [\"Environment\", name],\n [\"Files\", files.join(\" + \")],\n [\"Available\", listEnvironments(cwd).join(\", \") || \"none\"],\n [\"Config\", config.file],\n [\n \"Passthrough\",\n passthrough.length > 0 ? `${passthrough.join(\", \")} set, files ignored` : undefined,\n ],\n [\"Problem\", problem],\n ]\n .filter(([, value]) => value !== undefined)\n .map(([label, value]) => `${label?.padEnd(12)} ${value}`)\n .join(\"\\n\"),\n );\n });\n\n program\n .command(\"init\")\n .description(\"Set up .envs/, the gitignore rules and .envs/.env.local\")\n .action(async () => {\n const config = await loadConfig(cwd);\n const dir = join(cwd, envsDir);\n const dirExists = existsSync(dir);\n mkdirSync(dir, { recursive: true });\n\n const gitignorePath = join(cwd, \".gitignore\");\n const gitignore = existsSync(gitignorePath) ? readFileSync(gitignorePath, \"utf8\") : \"\";\n const gitignoreDone = gitignore.includes(gitignoreBlock);\n if (!gitignoreDone) {\n const separator = gitignore === \"\" ? \"\" : gitignore.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\";\n appendFileSync(gitignorePath, `${separator}${gitignoreBlock}\\n`);\n }\n\n const local = join(cwd, \".envs/.env.local\");\n const localExists = existsSync(local);\n const example = [config.example ?? [], exampleFiles]\n .flat()\n .find((file) => existsSync(join(cwd, file)));\n if (!localExists) {\n if (example) {\n copyFileSync(join(cwd, example), local, constants.COPYFILE_EXCL);\n } else {\n writeFileSync(local, \"\", { flag: \"wx\" });\n }\n }\n\n console.log(\n [\n `${dirExists ? \"Exists \" : \"Created\"} .envs/`,\n `${gitignoreDone ? \"Exists \" : \"Updated\"} .gitignore`,\n localExists\n ? \"Exists .envs/.env.local\"\n : `Created .envs/.env.local ${example ? `from ${example}` : \"(empty, no example file)\"}`,\n ].join(\"\\n\"),\n );\n });\n}\n\ntry {\n await program.parseAsync(argv, { from: \"user\" });\n} catch (error) {\n console.error(`newenv: ${error instanceof Error ? error.message : error}`);\n process.exitCode = 1;\n}\n"],"mappings":";;;;;;;;;;;;ACMA,MAAa,UAAU;AACvB,MAAa,WAAW;AACxB,MAAa,cAAc;AAI3B,MAAa,eAAe;CAC1B;CACA;CACA;CACA;CACA;CACA;AACF;;;;AAKA,SAAgB,mBAA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,UAAU,aAAa;QAE/D,cAAc,OAAO,IAAI,EAAE,MAAM,KAAK,CAAC;EAE3C;EAEA,QAAQ,IACN;GACE,GAAG,YAAY,YAAY,UAAU;GACrC,GAAG,gBAAgB,YAAY,UAAU;GACzC,cACI,6BACA,4BAA4B,UAAU,QAAQ,YAAY;EAChE,CAAC,CAAC,KAAK,IAAI,CACb;CACF,CAAC;AACL;AAEA,IAAI;CACF,MAAM,QAAQ,WAAW,MAAM,EAAE,MAAM,OAAO,CAAC;AACjD,SAAS,OAAO;CACd,QAAQ,MAAM,WAAW,iBAAiB,QAAQ,MAAM,UAAU,OAAO;CACzE,QAAQ,WAAW;AACrB"}
|
|
1
|
+
{"version":3,"file":"cli.mjs","names":[],"sources":["../package.json","../src/env.ts","../src/prompt.ts","../src/run.ts","../src/cli.ts"],"sourcesContent":["","import { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { parse } from \"dotenv\";\nimport { expand } from \"dotenv-expand\";\nimport type { ResolvedConfig } from \"./config\";\n\nexport const envsDir = \".envs\";\nexport const baseFile = \".envs/.env\";\nexport const currentFile = \".envs/current\";\n\n// Frameworks like Next.js load these from the project root on their own, which would mix them\n// into every environment\nexport const rootEnvFiles = [\n \".env\",\n \".env.local\",\n \".env.development\",\n \".env.development.local\",\n \".env.production\",\n \".env.production.local\",\n];\n\n/**\n * The selected environment: the name in .envs/current, or local\n */\nexport function currentEnvironment(cwd: string): string {\n const file = join(cwd, currentFile);\n return (existsSync(file) && readFileSync(file, \"utf8\").trim()) || \"local\";\n}\n\n/**\n * The environments with a .envs/.env.<name> file\n */\nexport function listEnvironments(cwd: string): string[] {\n const dir = join(cwd, envsDir);\n return existsSync(dir)\n ? readdirSync(dir)\n .map((file) => /^\\.env\\.([\\w-]+)$/.exec(file)?.[1])\n .filter((name): name is string => name !== undefined && name !== \"example\")\n .toSorted()\n : [];\n}\n\n/**\n * Throws when root env files exist, the base holds forbidden keys or the environment file is missing\n */\nexport function checkFiles(cwd: string, config: ResolvedConfig, name: string): void {\n const rootFiles = rootEnvFiles.filter((file) => existsSync(join(cwd, file)));\n if (rootFiles.length > 0) {\n throw new Error(\n `${rootFiles.join(\", \")} in the project root. Move into .envs/: mv -n ${rootFiles.join(\" \")} .envs/`,\n );\n }\n\n const base = join(cwd, baseFile);\n const forbidden = existsSync(base)\n ? Object.keys(parse(readFileSync(base))).filter((key) => config.forbiddenInBase.includes(key))\n : [];\n if (forbidden.length > 0) {\n throw new Error(\n `${forbidden.join(\", \")} in the shared ${baseFile}. Move to .envs/.env.<name> for each environment.`,\n );\n }\n\n const envFile = `.envs/.env.${name}`;\n if (!existsSync(join(cwd, envFile))) {\n throw new Error(\n name === \"local\"\n ? `${envFile} not found. Create it with: newenv init`\n : `${envFile} not found. Switch back with: newenv use local`,\n );\n }\n}\n\n/**\n * Merges the shell env, the base and the environment file: the last one wins. Expands variables\n * over the merged env, the same way dotenv-cli does.\n */\nexport function loadEnv(\n cwd: string,\n name: string,\n shellEnv: NodeJS.ProcessEnv,\n): { env: Record<string, string>; files: string[] } {\n const files = [baseFile, `.envs/.env.${name}`].filter((file) => existsSync(join(cwd, file)));\n const env: Record<string, string> = Object.assign(\n {},\n shellEnv,\n ...files.map((file) => parse(readFileSync(join(cwd, file)))),\n );\n expand({ parsed: env, processEnv: env });\n return { env, files };\n}\n","import type { Readable, Writable } from \"node:stream\";\n\nexport interface Streams {\n input: Readable & { isTTY?: boolean };\n output: Writable;\n}\n\n/**\n * Asks y/N, or to type the name for `\"type-name\"`. Ctrl+C answers no. Throws without a TTY, so\n * agents and CI can't confirm by accident.\n */\nexport async function confirm(\n mode: true | \"type-name\",\n name: string,\n question: string,\n streams: Streams,\n): Promise<boolean> {\n if (!streams.input.isTTY) {\n throw new Error(`${question}: needs confirmation, no TTY. Aborted.`);\n }\n\n // Imported on demand: most runs never ask, and inquirer is the slowest dependency to load\n try {\n if (mode === \"type-name\") {\n const { default: input } = await import(\"@inquirer/input\");\n return (\n (await input({ message: `${question}? Type \"${name}\" to confirm:` }, streams)) === name\n );\n }\n const { default: confirmPrompt } = await import(\"@inquirer/confirm\");\n return await confirmPrompt({ message: `${question}?`, default: false }, streams);\n } catch (error) {\n if (error instanceof Error && error.name === \"ExitPromptError\") {\n return false;\n }\n throw error;\n }\n}\n","import { styleText } from \"node:util\";\nimport spawn from \"cross-spawn\";\nimport { type Color, environmentSettings, type ResolvedConfig } from \"./config\";\nimport { checkFiles, currentEnvironment, loadEnv } from \"./env\";\nimport { confirm, type Streams } from \"./prompt\";\n\nexport interface Context {\n cwd: string;\n env: NodeJS.ProcessEnv;\n config: ResolvedConfig;\n streams: Streams;\n}\n\nconst badgeStyles = {\n red: [\"bgRed\", \"white\", \"bold\"],\n yellow: [\"bgYellow\", \"black\"],\n green: [\"bgGreen\", \"black\"],\n blue: [\"bgBlue\", \"white\"],\n magenta: [\"bgMagenta\", \"white\"],\n cyan: [\"bgCyan\", \"black\"],\n gray: [\"bgGray\", \"white\"],\n} as const satisfies Record<Color, readonly string[]>;\n\nconst signals = [\"SIGINT\", \"SIGTERM\", \"SIGHUP\"] as const;\n\n/**\n * Checks the files, prints the banner, confirms and returns the env to run a command with\n */\nexport async function prepareRun(\n command: string,\n { cwd, env, config, streams }: Context,\n forceConfirm = false,\n): Promise<NodeJS.ProcessEnv> {\n if (config.passthrough.some((key) => env[key])) {\n return env;\n }\n\n const name = currentEnvironment(cwd);\n checkFiles(cwd, config, name);\n\n const loaded = loadEnv(cwd, name, env);\n const settings = environmentSettings(config, name);\n const script = env.npm_lifecycle_event ?? command;\n\n if (name !== \"local\") {\n const badge = styleText([...badgeStyles[settings.color]], ` ${name.toUpperCase()} `, {\n stream: streams.output,\n });\n streams.output.write(`${badge} ${script} uses ${loaded.files.join(\" + \")}\\n`);\n }\n\n const asks = forceConfirm || config.confirmScripts.includes(env.npm_lifecycle_event ?? \"\");\n if (\n asks &&\n settings.confirm &&\n !(await confirm(settings.confirm, name, `Run ${script} against ${name}`, streams))\n ) {\n throw new Error(\"Aborted.\");\n }\n\n return loaded.env;\n}\n\n/**\n * Runs a command with inherited stdio and forwards signals to it until it exits. In a terminal,\n * Ctrl+C and hangups already reach the whole foreground process group, the command included, so\n * only SIGTERM is forwarded there. newenv still catches the others, to exit after the command.\n */\nexport function spawnCommand(\n command: string,\n args: string[],\n env: NodeJS.ProcessEnv,\n): Promise<{ code: number | null; signal: NodeJS.Signals | null }> {\n return new Promise((resolve, reject) => {\n const child = spawn(command, args, { stdio: \"inherit\", env });\n const forward = (signal: NodeJS.Signals) => {\n if (signal === \"SIGTERM\" || !process.stdin.isTTY) {\n child.kill(signal);\n }\n };\n const stopForwarding = () => {\n signals.forEach((signal) => {\n process.off(signal, forward);\n });\n };\n signals.forEach((signal) => {\n process.on(signal, forward);\n });\n\n child.on(\"error\", (error) => {\n stopForwarding();\n reject(error);\n });\n child.on(\"exit\", (code, signal) => {\n stopForwarding();\n resolve({ code, signal });\n });\n });\n}\n","#!/usr/bin/env node\nimport {\n appendFileSync,\n constants,\n copyFileSync,\n existsSync,\n mkdirSync,\n readFileSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\nimport { Command } from \"commander\";\nimport { version } from \"../package.json\";\nimport { environmentSettings, loadConfig } from \"./config\";\nimport {\n baseFile,\n checkFiles,\n currentEnvironment,\n currentFile,\n envsDir,\n listEnvironments,\n} from \"./env\";\nimport { confirm } from \"./prompt\";\nimport { prepareRun, spawnCommand } from \"./run\";\n\nconst argv = process.argv.slice(2);\nconst cwd = process.cwd();\nconst streams = { input: process.stdin, output: process.stderr };\n\n// `.env*` patterns in existing gitignores also match the .envs folder, and git can't re-include a\n// file in an ignored folder. So the folder is re-included first, then its contents ignored.\nconst gitignoreBlock = [\"# newenv\", \"/.env*\", \"!/.envs/\", \"/.envs/*\", \"!/.envs/.env.example\"].join(\n \"\\n\",\n);\n\nconst exampleFiles = [\".envs/.env.example\", \".example-env\", \".env.example\"];\n\n// newenv guards no script or base key by default, so init writes a starting point to edit. The\n// type import is erased, so the config also loads where the package can't be resolved.\nconst configTemplate = `import type { Config } from \"@newcode-team/env\";\n\nexport default {\n confirmScripts: [\"db:push\", \"db:migrate\", \"db:seed\"],\n forbiddenInBase: [\"DATABASE_URL\"],\n} satisfies Config;\n`;\n\nconst program = new Command(\"newenv\")\n .description(\"Run a command with the env files of the selected environment\")\n .usage(\"[options] <command> [args...]\")\n .version(version, \"-v, --version\", \"Show version\")\n .helpOption(\"-h, --help\", \"Show help\")\n // Options after the command belong to the command\n .enablePositionalOptions()\n .passThroughOptions()\n .option(\"--confirm\", \"Ask before running, as for confirmScripts\")\n .argument(\"[command...]\", \"Command to run. Put -- before one named use, status or init\")\n .configureOutput({\n outputError: (message, write) => write(`newenv: ${message.replace(/^error: /, \"\")}`),\n })\n .action(async (command: string[], options: { confirm?: boolean }) => {\n const [name, ...args] = command;\n if (!name) {\n return program.help({ error: argv.length > 0 });\n }\n\n const config = await loadConfig(cwd);\n const env = await prepareRun(name, { cwd, env: process.env, config, streams }, options.confirm);\n const { code, signal } = await spawnCommand(name, args, env).catch(\n (error: NodeJS.ErrnoException) => {\n if (error.code !== \"ENOENT\") {\n throw error;\n }\n console.error(`newenv: command not found: ${name}`);\n return { code: 127, signal: null };\n },\n );\n if (signal) {\n process.kill(process.pid, signal);\n }\n process.exitCode = code ?? 1;\n });\n\n// Commander still matches subcommands after --, so `newenv -- status` gets none\nif (argv[argv.findIndex((arg) => arg === \"--\" || !arg.startsWith(\"-\"))] !== \"--\") {\n program\n .command(\"use\")\n .description(\"Switch environment\")\n .argument(\"<name>\", \"Environment, local deletes .envs/current\")\n .action(async (name: string) => {\n const envFile = `.envs/.env.${name}`;\n if (name === \"local\") {\n rmSync(join(cwd, currentFile), { force: true });\n console.log(\n existsSync(join(cwd, envFile))\n ? \"Switched to local.\"\n : `Switched to local. ${envFile} not found. Create it with: newenv init`,\n );\n return;\n }\n\n const environments = listEnvironments(cwd);\n if (!environments.includes(name)) {\n throw new Error(`${envFile} not found. Available: ${environments.join(\", \") || \"none\"}`);\n }\n\n const config = await loadConfig(cwd);\n if (\n environmentSettings(config, name).confirm === \"type-name\" &&\n !(await confirm(true, name, `Switch to ${name}`, streams))\n ) {\n throw new Error(\"Aborted.\");\n }\n\n writeFileSync(join(cwd, currentFile), `${name}\\n`);\n console.log(`Switched to ${name}.`);\n });\n\n program\n .command(\"status\")\n .description(\"Show the environment and its files\")\n .action(async () => {\n const config = await loadConfig(cwd);\n const name = currentEnvironment(cwd);\n const envFile = `.envs/.env.${name}`;\n const files = [\n ...(existsSync(join(cwd, baseFile)) ? [baseFile] : []),\n existsSync(join(cwd, envFile)) ? envFile : `${envFile} (missing)`,\n ];\n const passthrough = config.passthrough.filter((key) => process.env[key]);\n const problem = (() => {\n try {\n checkFiles(cwd, config, name);\n return undefined;\n } catch (error) {\n return (error as Error).message;\n }\n })();\n\n console.log(\n [\n [\"Environment\", name],\n [\"Files\", files.join(\" + \")],\n [\"Available\", listEnvironments(cwd).join(\", \") || \"none\"],\n [\"Config\", config.file],\n [\n \"Passthrough\",\n passthrough.length > 0 ? `${passthrough.join(\", \")} set, files ignored` : undefined,\n ],\n [\"Problem\", problem],\n ]\n .filter(([, value]) => value !== undefined)\n .map(([label, value]) => `${label?.padEnd(12)} ${value}`)\n .join(\"\\n\"),\n );\n });\n\n program\n .command(\"init\")\n .description(\"Set up .envs/, the gitignore rules, .envs/.env.local and the config\")\n .action(async () => {\n const config = await loadConfig(cwd);\n const dir = join(cwd, envsDir);\n const dirExists = existsSync(dir);\n mkdirSync(dir, { recursive: true });\n\n const gitignorePath = join(cwd, \".gitignore\");\n const gitignore = existsSync(gitignorePath) ? readFileSync(gitignorePath, \"utf8\") : \"\";\n const gitignoreDone = gitignore.includes(gitignoreBlock);\n if (!gitignoreDone) {\n const separator = gitignore === \"\" ? \"\" : gitignore.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\";\n appendFileSync(gitignorePath, `${separator}${gitignoreBlock}\\n`);\n }\n\n const local = join(cwd, \".envs/.env.local\");\n const localExists = existsSync(local);\n const example = [config.example ?? [], exampleFiles]\n .flat()\n .find((file) => existsSync(join(cwd, file)));\n if (!localExists) {\n if (example) {\n copyFileSync(join(cwd, example), local, constants.COPYFILE_EXCL);\n } else {\n writeFileSync(local, \"\", { flag: \"wx\" });\n }\n }\n\n const configFile = config.file ?? \"newenv.config.ts\";\n if (!config.file) {\n writeFileSync(join(cwd, configFile), configTemplate, { flag: \"wx\" });\n }\n\n console.log(\n [\n `${dirExists ? \"Exists \" : \"Created\"} .envs/`,\n `${gitignoreDone ? \"Exists \" : \"Updated\"} .gitignore`,\n localExists\n ? \"Exists .envs/.env.local\"\n : `Created .envs/.env.local ${example ? `from ${example}` : \"(empty, no example file)\"}`,\n `${config.file ? \"Exists \" : \"Created\"} ${configFile}`,\n ].join(\"\\n\"),\n );\n });\n}\n\ntry {\n await program.parseAsync(argv, { from: \"user\" });\n} catch (error) {\n console.error(`newenv: ${error instanceof Error ? error.message : error}`);\n process.exitCode = 1;\n}\n"],"mappings":";;;;;;;;;;;;ACMA,MAAa,UAAU;AACvB,MAAa,WAAW;AACxB,MAAa,cAAc;AAI3B,MAAa,eAAe;CAC1B;CACA;CACA;CACA;CACA;CACA;AACF;;;;AAKA,SAAgB,mBAAmB,KAAqB;CACtD,MAAM,OAAO,KAAK,KAAK,WAAW;CAClC,OAAQ,WAAW,IAAI,KAAK,aAAa,MAAM,MAAM,CAAC,CAAC,KAAK,KAAM;AACpE;;;;AAKA,SAAgB,iBAAiB,KAAuB;CACtD,MAAM,MAAM,KAAK,KAAK,OAAO;CAC7B,OAAO,WAAW,GAAG,IACjB,YAAY,GAAG,CAAC,CACb,KAAK,SAAS,oBAAoB,KAAK,IAAI,CAAC,GAAG,EAAE,CAAC,CAClD,QAAQ,SAAyB,SAAS,KAAA,KAAa,SAAS,SAAS,CAAC,CAC1E,SAAS,IACZ,CAAC;AACP;;;;AAKA,SAAgB,WAAW,KAAa,QAAwB,MA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CAAC;AACL;AAEA,IAAI;CACF,MAAM,QAAQ,WAAW,MAAM,EAAE,MAAM,OAAO,CAAC;AACjD,SAAS,OAAO;CACd,QAAQ,MAAM,WAAW,iBAAiB,QAAQ,MAAM,UAAU,OAAO;CACzE,QAAQ,WAAW;AACrB"}
|
|
@@ -5,12 +5,8 @@ import { pathToFileURL } from "node:url";
|
|
|
5
5
|
const defineConfig = (config) => config;
|
|
6
6
|
const defaults = {
|
|
7
7
|
environments: {},
|
|
8
|
-
confirmScripts: [
|
|
9
|
-
|
|
10
|
-
"db:migrate",
|
|
11
|
-
"db:seed"
|
|
12
|
-
],
|
|
13
|
-
forbiddenInBase: ["DATABASE_URL"],
|
|
8
|
+
confirmScripts: [],
|
|
9
|
+
forbiddenInBase: [],
|
|
14
10
|
passthrough: []
|
|
15
11
|
};
|
|
16
12
|
const defaultEnvironments = {
|
|
@@ -45,4 +41,4 @@ function environmentSettings(config, name) {
|
|
|
45
41
|
}
|
|
46
42
|
export { environmentSettings as n, loadConfig as r, defineConfig as t };
|
|
47
43
|
|
|
48
|
-
//# sourceMappingURL=config-
|
|
44
|
+
//# sourceMappingURL=config-DOtqBeMb.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config-DOtqBeMb.mjs","names":[],"sources":["../src/config.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\nexport type Color = \"red\" | \"yellow\" | \"green\" | \"blue\" | \"magenta\" | \"cyan\" | \"gray\";\n\nexport interface EnvironmentConfig {\n /**\n * Badge color. Default: red for production, yellow for others\n */\n color?: Color;\n /**\n * Confirmation before `confirmScripts`: `true` asks y/N, `\"type-name\"` asks to type the\n * environment name and also guards `newenv use`. Default: `\"type-name\"` for production,\n * `false` for local, `true` for others\n */\n confirm?: boolean | \"type-name\";\n}\n\nexport interface Config {\n /**\n * Settings per environment name\n */\n environments?: Record<string, EnvironmentConfig>;\n /**\n * Scripts (`npm_lifecycle_event`) that ask before running. Default: none\n */\n confirmScripts?: string[];\n /**\n * Keys refused in the shared `.envs/.env`. Default: none\n */\n forbiddenInBase?: string[];\n /**\n * When one of these is set, commands run as is with the existing env, e.g. `VERCEL` on a host\n * that provides the env. Default: none\n */\n passthrough?: string[];\n /**\n * Source for `newenv init`. Default: the first of .envs/.env.example, .example-env, .env.example\n */\n example?: string;\n}\n\nexport type ResolvedConfig = Required<Omit<Config, \"example\">> & {\n example?: string;\n /**\n * The config file that was loaded\n */\n file?: string;\n};\n\nexport const defineConfig = (config: Config): Config => config;\n\nexport const defaults: ResolvedConfig = {\n environments: {},\n confirmScripts: [],\n forbiddenInBase: [],\n passthrough: [],\n};\n\nconst defaultEnvironments: Record<string, EnvironmentConfig> = {\n local: { confirm: false },\n production: { color: \"red\", confirm: \"type-name\" },\n};\n\nexport const configFiles = [\"newenv.config.ts\", \"newenv.config.mjs\", \"newenv.config.js\"];\n\nexport async function loadConfig(cwd: string): Promise<ResolvedConfig> {\n const file = configFiles.find((name) => existsSync(join(cwd, name)));\n if (!file) {\n return defaults;\n }\n\n const module = await import(pathToFileURL(join(cwd, file)).href);\n return { ...defaults, ...(module.default as Config), file };\n}\n\nexport function environmentSettings(\n config: ResolvedConfig,\n name: string,\n): Required<EnvironmentConfig> {\n return {\n color: \"yellow\",\n confirm: true,\n ...defaultEnvironments[name],\n ...config.environments[name],\n };\n}\n"],"mappings":";;;;AAmDA,MAAa,gBAAgB,WAA2B;AAExD,MAAa,WAA2B;CACtC,cAAc,CAAC;CACf,gBAAgB,CAAC;CACjB,iBAAiB,CAAC;CAClB,aAAa,CAAC;AAChB;AAEA,MAAM,sBAAyD;CAC7D,OAAO,EAAE,SAAS,MAAM;CACxB,YAAY;EAAE,OAAO;EAAO,SAAS;CAAY;AACnD;AAEA,MAAa,cAAc;CAAC;CAAoB;CAAqB;AAAkB;AAEvF,eAAsB,WAAW,KAAsC;CACrE,MAAM,OAAO,YAAY,MAAM,SAAS,WAAW,KAAK,KAAK,IAAI,CAAC,CAAC;CACnE,IAAI,CAAC,MACH,OAAO;CAGT,MAAM,SAAS,MAAM,OAAO,cAAc,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC;CAC3D,OAAO;EAAE,GAAG;EAAU,GAAI,OAAO;EAAoB;CAAK;AAC5D;AAEA,SAAgB,oBACd,QACA,MAC6B;CAC7B,OAAO;EACL,OAAO;EACP,SAAS;EACT,GAAG,oBAAoB;EACvB,GAAG,OAAO,aAAa;CACzB;AACF"}
|
package/dist/index.d.mts
CHANGED
|
@@ -17,11 +17,11 @@ interface Config {
|
|
|
17
17
|
*/
|
|
18
18
|
environments?: Record<string, EnvironmentConfig>;
|
|
19
19
|
/**
|
|
20
|
-
* Scripts (`npm_lifecycle_event`) that ask before running. Default:
|
|
20
|
+
* Scripts (`npm_lifecycle_event`) that ask before running. Default: none
|
|
21
21
|
*/
|
|
22
22
|
confirmScripts?: string[];
|
|
23
23
|
/**
|
|
24
|
-
* Keys refused in the shared `.envs/.env`. Default:
|
|
24
|
+
* Keys refused in the shared `.envs/.env`. Default: none
|
|
25
25
|
*/
|
|
26
26
|
forbiddenInBase?: string[];
|
|
27
27
|
/**
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as defineConfig } from "./config-
|
|
1
|
+
export { t as defineConfig } from "./config-DOtqBeMb.mjs";
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"config-DdWBrqcV.mjs","names":[],"sources":["../src/config.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\nexport type Color = \"red\" | \"yellow\" | \"green\" | \"blue\" | \"magenta\" | \"cyan\" | \"gray\";\n\nexport interface EnvironmentConfig {\n /**\n * Badge color. Default: red for production, yellow for others\n */\n color?: Color;\n /**\n * Confirmation before `confirmScripts`: `true` asks y/N, `\"type-name\"` asks to type the\n * environment name and also guards `newenv use`. Default: `\"type-name\"` for production,\n * `false` for local, `true` for others\n */\n confirm?: boolean | \"type-name\";\n}\n\nexport interface Config {\n /**\n * Settings per environment name\n */\n environments?: Record<string, EnvironmentConfig>;\n /**\n * Scripts (`npm_lifecycle_event`) that ask before running. Default: db:push, db:migrate, db:seed\n */\n confirmScripts?: string[];\n /**\n * Keys refused in the shared `.envs/.env`. Default: DATABASE_URL\n */\n forbiddenInBase?: string[];\n /**\n * When one of these is set, commands run as is with the existing env, e.g. `VERCEL` on a host\n * that provides the env. Default: none\n */\n passthrough?: string[];\n /**\n * Source for `newenv init`. Default: the first of .envs/.env.example, .example-env, .env.example\n */\n example?: string;\n}\n\nexport type ResolvedConfig = Required<Omit<Config, \"example\">> & {\n example?: string;\n /**\n * The config file that was loaded\n */\n file?: string;\n};\n\nexport const defineConfig = (config: Config): Config => config;\n\nexport const defaults: ResolvedConfig = {\n environments: {},\n confirmScripts: [\"db:push\", \"db:migrate\", \"db:seed\"],\n forbiddenInBase: [\"DATABASE_URL\"],\n passthrough: [],\n};\n\nconst defaultEnvironments: Record<string, EnvironmentConfig> = {\n local: { confirm: false },\n production: { color: \"red\", confirm: \"type-name\" },\n};\n\nexport const configFiles = [\"newenv.config.ts\", \"newenv.config.mjs\", \"newenv.config.js\"];\n\nexport async function loadConfig(cwd: string): Promise<ResolvedConfig> {\n const file = configFiles.find((name) => existsSync(join(cwd, name)));\n if (!file) {\n return defaults;\n }\n\n const module = await import(pathToFileURL(join(cwd, file)).href);\n return { ...defaults, ...(module.default as Config), file };\n}\n\nexport function environmentSettings(\n config: ResolvedConfig,\n name: string,\n): Required<EnvironmentConfig> {\n return {\n color: \"yellow\",\n confirm: true,\n ...defaultEnvironments[name],\n ...config.environments[name],\n };\n}\n"],"mappings":";;;;AAmDA,MAAa,gBAAgB,WAA2B;AAExD,MAAa,WAA2B;CACtC,cAAc,CAAC;CACf,gBAAgB;EAAC;EAAW;EAAc;CAAS;CACnD,iBAAiB,CAAC,cAAc;CAChC,aAAa,CAAC;AAChB;AAEA,MAAM,sBAAyD;CAC7D,OAAO,EAAE,SAAS,MAAM;CACxB,YAAY;EAAE,OAAO;EAAO,SAAS;CAAY;AACnD;AAEA,MAAa,cAAc;CAAC;CAAoB;CAAqB;AAAkB;AAEvF,eAAsB,WAAW,KAAsC;CACrE,MAAM,OAAO,YAAY,MAAM,SAAS,WAAW,KAAK,KAAK,IAAI,CAAC,CAAC;CACnE,IAAI,CAAC,MACH,OAAO;CAGT,MAAM,SAAS,MAAM,OAAO,cAAc,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC;CAC3D,OAAO;EAAE,GAAG;EAAU,GAAI,OAAO;EAAoB;CAAK;AAC5D;AAEA,SAAgB,oBACd,QACA,MAC6B;CAC7B,OAAO;EACL,OAAO;EACP,SAAS;EACT,GAAG,oBAAoB;EACvB,GAAG,OAAO,aAAa;CACzB;AACF"}
|