@newcode-team/env 0.1.2 → 0.2.0
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 +69 -12
- package/dist/cli.mjs +161 -206
- package/dist/cli.mjs.map +1 -1
- package/dist/environment-N9SRYkh6.mjs +203 -0
- package/dist/environment-N9SRYkh6.mjs.map +1 -0
- package/dist/index.d.mts +63 -3
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +11 -24
- package/dist/config-DOtqBeMb.mjs +0 -44
- package/dist/config-DOtqBeMb.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
Per-environment env files for any command, with switching and guards. Only reads files: no secrets service, no encryption, no syncing.
|
|
4
4
|
|
|
5
5
|
```bash
|
|
6
|
-
pnpm add -D @newcode-team/env
|
|
6
|
+
pnpm add -D @newcode-team/env @newcode-team/config
|
|
7
7
|
```
|
|
8
8
|
|
|
9
9
|
```json
|
|
@@ -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, `.envs/.env.local` and `
|
|
42
|
+
| `newenv init` | Create `.envs/`, gitignore rules, `.envs/.env.local` and `newcode.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.
|
|
@@ -81,10 +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
|
|
84
|
+
Created newcode.config.ts
|
|
85
85
|
```
|
|
86
86
|
|
|
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
|
|
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 `env` section starts with `db:push`, `db:migrate`, `db:seed` and `DATABASE_URL` to edit. An existing `newcode.config.ts` is never changed: without an `env` section, `init` prints the section to add. The gitignore rules:
|
|
88
88
|
|
|
89
89
|
```gitignore
|
|
90
90
|
# newenv
|
|
@@ -96,23 +96,60 @@ The example is the first of `.envs/.env.example`, `.example-env` and `.env.examp
|
|
|
96
96
|
|
|
97
97
|
A `.env*` pattern also matches the `.envs` folder, and git can't re-include a file in an ignored folder. So the folder is re-included first, then its contents ignored, except the example.
|
|
98
98
|
|
|
99
|
+
## Use in scripts
|
|
100
|
+
|
|
101
|
+
The same loading and checks as the CLI, for scripts that need another environment, e.g. a db sync from staging to local:
|
|
102
|
+
|
|
103
|
+
```ts
|
|
104
|
+
import * as newenv from "@newcode-team/env";
|
|
105
|
+
|
|
106
|
+
const staging = await newenv.loadEnvironment("staging");
|
|
107
|
+
const local = await newenv.loadEnvironment("local");
|
|
108
|
+
const from = staging.require("DATABASE_URL");
|
|
109
|
+
const to = local.require("DATABASE_URL", "S3_BUCKET");
|
|
110
|
+
|
|
111
|
+
if (!(await newenv.confirmEnvironment("local", "Overwrite local with staging"))) {
|
|
112
|
+
process.exit(1);
|
|
113
|
+
}
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Named imports work too: `import { loadEnvironment } from "@newcode-team/env"`.
|
|
117
|
+
|
|
118
|
+
| Function | Returns |
|
|
119
|
+
|---|---|
|
|
120
|
+
| `currentEnvironment()` | Name in `.envs/current`, or `local` |
|
|
121
|
+
| `listEnvironments()` | Names with a `.envs/.env.<name>` file, sorted |
|
|
122
|
+
| `loadEnvironment(name?)` | `{ name, files, values, settings, require }`. The current environment without a name |
|
|
123
|
+
| `confirmEnvironment(name, question)` | `true` when confirmed. Follows `environments.<name>.confirm`, throws without a TTY |
|
|
124
|
+
|
|
125
|
+
- Only `.envs/.env` and `.envs/.env.<name>` by default, not the shell. A script often runs with another environment in `process.env`, which must not fill in keys the file lacks. Pass `{ shell: process.env }` to merge like the CLI.
|
|
126
|
+
- Never writes to `process.env`.
|
|
127
|
+
- `require(...keys)` returns the keys, and throws when one is missing or empty.
|
|
128
|
+
- Refusals throw an `EnvironmentError` with the CLI's messages. With a `passthrough` variable set, `loadEnvironment()` returns `process.env`, and a named environment throws.
|
|
129
|
+
- Every function takes `{ cwd }`, default `process.cwd()`.
|
|
130
|
+
|
|
99
131
|
## Config
|
|
100
132
|
|
|
101
|
-
Optional. `
|
|
133
|
+
Optional. The `env` section of `newcode.config.ts`, the config file all NewCode tools share. It's found by [`@newcode-team/config`](../config): the first `newcode.config.ts`, `.mjs` or `.js` from the current folder up to the git root. `newenv init` creates one:
|
|
102
134
|
|
|
103
135
|
```ts
|
|
104
|
-
import { defineConfig } from "@newcode-team/
|
|
136
|
+
import { defineConfig } from "@newcode-team/config";
|
|
137
|
+
import { env } from "@newcode-team/env";
|
|
105
138
|
|
|
106
139
|
export default defineConfig({
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
140
|
+
env: env({
|
|
141
|
+
environments: {
|
|
142
|
+
staging: { color: "yellow", confirm: true },
|
|
143
|
+
production: { color: "red", confirm: "type-name" },
|
|
144
|
+
},
|
|
145
|
+
confirmScripts: ["db:push", "db:migrate", "db:seed"],
|
|
146
|
+
forbiddenInBase: ["DATABASE_URL"],
|
|
147
|
+
}),
|
|
113
148
|
});
|
|
114
149
|
```
|
|
115
150
|
|
|
151
|
+
`env()` returns the section as is. Importing it types the section and adds the `env` key to the config, so a typo is an error. Without a file or an `env` section, every key has its default. `newenv.config.ts` from 0.1 is no longer read: move it into the `env` section.
|
|
152
|
+
|
|
116
153
|
| Key | Default | Does |
|
|
117
154
|
|---|---|---|
|
|
118
155
|
| `environments.<name>.color` | `red` for production, else `yellow` | Badge: `red`, `yellow`, `green`, `blue`, `magenta`, `cyan`, `gray` |
|
|
@@ -147,6 +184,26 @@ setopt PROMPT_SUBST
|
|
|
147
184
|
|
|
148
185
|
## Development
|
|
149
186
|
|
|
187
|
+
Part of the [NewCode tools](../..) monorepo, laid out like `@newcode-team/sync`:
|
|
188
|
+
|
|
189
|
+
```
|
|
190
|
+
src/
|
|
191
|
+
cli.ts the newenv program, registers the commands
|
|
192
|
+
index.ts the public API
|
|
193
|
+
commands/
|
|
194
|
+
run/ command.ts (newenv <command>), helpers.ts (banner, confirmation)
|
|
195
|
+
use/ command.ts
|
|
196
|
+
status/ command.ts
|
|
197
|
+
init/ command.ts, templates.ts
|
|
198
|
+
lib/ config, environment (loading and the script API), errors, processes, prompts
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
- `command.ts` registers the command. Simple logic used once stays inline.
|
|
202
|
+
- `helpers.ts` holds logic that is complex, reused or tested on its own.
|
|
203
|
+
- `lib/` never imports from `commands/`.
|
|
204
|
+
|
|
205
|
+
From the repository root:
|
|
206
|
+
|
|
150
207
|
```bash
|
|
151
208
|
pnpm build # tsdown, with publint and attw
|
|
152
209
|
pnpm test # Vitest, builds dist/ first for the CLI tests
|
package/dist/cli.mjs
CHANGED
|
@@ -1,127 +1,83 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { n as environmentSettings, r as loadConfig } from "./config-DOtqBeMb.mjs";
|
|
3
|
-
import { appendFileSync, constants, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
-
import { join } from "node:path";
|
|
5
2
|
import { Command } from "commander";
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
3
|
+
import { appendFileSync, constants, copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { join, relative } from "node:path";
|
|
5
|
+
import { loadConfig } from "@newcode-team/config";
|
|
6
|
+
import { _ as loadEnvConfig, a as currentEnvironment, c as listEnvironments, d as confirm, f as terminal, g as environmentSettings, m as errorMessage, n as checkFiles, o as currentFile, p as EnvironmentError, r as checkKnown, s as envsDir, t as baseFile, u as resolveEnvironment, v as resolveConfig } from "./environment-N9SRYkh6.mjs";
|
|
9
7
|
import spawn from "cross-spawn";
|
|
8
|
+
import { styleText } from "node:util";
|
|
10
9
|
// package.json
|
|
11
|
-
var version = "0.
|
|
12
|
-
// src/
|
|
13
|
-
const
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
"
|
|
18
|
-
"
|
|
19
|
-
|
|
20
|
-
".env.development.local",
|
|
21
|
-
".env.production",
|
|
22
|
-
".env.production.local"
|
|
23
|
-
];
|
|
24
|
-
/**
|
|
25
|
-
* The selected environment: the name in .envs/current, or local
|
|
26
|
-
*/
|
|
27
|
-
function currentEnvironment(cwd) {
|
|
28
|
-
const file = join(cwd, currentFile);
|
|
29
|
-
return existsSync(file) && readFileSync(file, "utf8").trim() || "local";
|
|
30
|
-
}
|
|
31
|
-
/**
|
|
32
|
-
* The environments with a .envs/.env.<name> file
|
|
33
|
-
*/
|
|
34
|
-
function listEnvironments(cwd) {
|
|
35
|
-
const dir = join(cwd, envsDir);
|
|
36
|
-
return existsSync(dir) ? readdirSync(dir).map((file) => /^\.env\.([\w-]+)$/.exec(file)?.[1]).filter((name) => name !== void 0 && name !== "example").toSorted() : [];
|
|
37
|
-
}
|
|
38
|
-
/**
|
|
39
|
-
* Throws when root env files exist, the base holds forbidden keys or the environment file is missing
|
|
40
|
-
*/
|
|
41
|
-
function checkFiles(cwd, config, name) {
|
|
42
|
-
const rootFiles = rootEnvFiles.filter((file) => existsSync(join(cwd, file)));
|
|
43
|
-
if (rootFiles.length > 0) throw new Error(`${rootFiles.join(", ")} in the project root. Move into .envs/: mv -n ${rootFiles.join(" ")} .envs/`);
|
|
44
|
-
const base = join(cwd, baseFile);
|
|
45
|
-
const forbidden = existsSync(base) ? Object.keys(parse(readFileSync(base))).filter((key) => config.forbiddenInBase.includes(key)) : [];
|
|
46
|
-
if (forbidden.length > 0) throw new Error(`${forbidden.join(", ")} in the shared ${baseFile}. Move to .envs/.env.<name> for each environment.`);
|
|
47
|
-
const envFile = `.envs/.env.${name}`;
|
|
48
|
-
if (!existsSync(join(cwd, envFile))) throw new Error(name === "local" ? `${envFile} not found. Create it with: newenv init` : `${envFile} not found. Switch back with: newenv use local`);
|
|
49
|
-
}
|
|
10
|
+
var version = "0.2.0";
|
|
11
|
+
// src/commands/init/templates.ts
|
|
12
|
+
const gitignoreBlock = [
|
|
13
|
+
"# newenv",
|
|
14
|
+
"/.env*",
|
|
15
|
+
"!/.envs/",
|
|
16
|
+
"/.envs/*",
|
|
17
|
+
"!/.envs/.env.example"
|
|
18
|
+
].join("\n");
|
|
50
19
|
/**
|
|
51
|
-
*
|
|
52
|
-
* over the merged env, the same way dotenv-cli does.
|
|
20
|
+
* Where .envs/.env.local is copied from: the first that exists, after the configured `example`
|
|
53
21
|
*/
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
22
|
+
const exampleFiles = [
|
|
23
|
+
".envs/.env.example",
|
|
24
|
+
".example-env",
|
|
25
|
+
".env.example"
|
|
26
|
+
];
|
|
27
|
+
const envSection = ` env: env({
|
|
28
|
+
confirmScripts: ["db:push", "db:migrate", "db:seed"],
|
|
29
|
+
forbiddenInBase: ["DATABASE_URL"],
|
|
30
|
+
}),`;
|
|
31
|
+
const configTemplate = `import { defineConfig } from "@newcode-team/config";
|
|
32
|
+
import { env } from "@newcode-team/env";
|
|
33
|
+
|
|
34
|
+
export default defineConfig({
|
|
35
|
+
${envSection}
|
|
36
|
+
});
|
|
37
|
+
`;
|
|
38
|
+
// src/commands/init/command.ts
|
|
67
39
|
/**
|
|
68
|
-
*
|
|
69
|
-
*
|
|
40
|
+
* `newenv init`: sets up .envs/, the gitignore rules, .envs/.env.local and newcode.config.ts.
|
|
41
|
+
* Existing files are kept: an existing config only gets the section to add printed
|
|
70
42
|
*/
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
43
|
+
function initCommand(program) {
|
|
44
|
+
program.command("init").description("Set up .envs/, the gitignore rules, .envs/.env.local and the config").action(async () => {
|
|
45
|
+
const cwd = process.cwd();
|
|
46
|
+
const loaded = await loadConfig({ cwd });
|
|
47
|
+
const config = resolveConfig(loaded.env, loaded.file);
|
|
48
|
+
const dirExists = existsSync(join(cwd, envsDir));
|
|
49
|
+
mkdirSync(join(cwd, envsDir), { recursive: true });
|
|
50
|
+
const gitignorePath = join(cwd, ".gitignore");
|
|
51
|
+
const gitignore = existsSync(gitignorePath) ? readFileSync(gitignorePath, "utf8") : "";
|
|
52
|
+
const gitignoreDone = gitignore.includes(gitignoreBlock);
|
|
53
|
+
if (!gitignoreDone) {
|
|
54
|
+
const separator = gitignore === "" ? "" : gitignore.endsWith("\n") ? "\n" : "\n\n";
|
|
55
|
+
appendFileSync(gitignorePath, `${separator}${gitignoreBlock}\n`);
|
|
77
56
|
}
|
|
78
|
-
const
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
57
|
+
const local = join(cwd, ".envs/.env.local");
|
|
58
|
+
const localExists = existsSync(local);
|
|
59
|
+
const example = [config.example ?? [], exampleFiles].flat().find((file) => existsSync(join(cwd, file)));
|
|
60
|
+
if (!localExists) {
|
|
61
|
+
if (example) copyFileSync(join(cwd, example), local, constants.COPYFILE_EXCL);
|
|
62
|
+
else writeFileSync(local, "", { flag: "wx" });
|
|
63
|
+
}
|
|
64
|
+
if (!loaded.file) writeFileSync(join(cwd, "newcode.config.ts"), configTemplate, { flag: "wx" });
|
|
65
|
+
const configFile = loaded.file ? relative(cwd, loaded.file) : "newcode.config.ts";
|
|
66
|
+
console.log([
|
|
67
|
+
`${dirExists ? "Exists " : "Created"} .envs/`,
|
|
68
|
+
`${gitignoreDone ? "Exists " : "Updated"} .gitignore`,
|
|
69
|
+
localExists ? "Exists .envs/.env.local" : `Created .envs/.env.local ${example ? `from ${example}` : "(empty, no example file)"}`,
|
|
70
|
+
!loaded.file ? `Created ${configFile}` : loaded.env ? `Exists ${configFile}` : `Exists ${configFile} without an env section. Add it:\n\nimport { env } from "@newcode-team/env";\n\n${envSection}`
|
|
71
|
+
].join("\n"));
|
|
72
|
+
});
|
|
87
73
|
}
|
|
88
|
-
// src/
|
|
89
|
-
const badgeStyles = {
|
|
90
|
-
red: [
|
|
91
|
-
"bgRed",
|
|
92
|
-
"white",
|
|
93
|
-
"bold"
|
|
94
|
-
],
|
|
95
|
-
yellow: ["bgYellow", "black"],
|
|
96
|
-
green: ["bgGreen", "black"],
|
|
97
|
-
blue: ["bgBlue", "white"],
|
|
98
|
-
magenta: ["bgMagenta", "white"],
|
|
99
|
-
cyan: ["bgCyan", "black"],
|
|
100
|
-
gray: ["bgGray", "white"]
|
|
101
|
-
};
|
|
74
|
+
// src/lib/process.ts
|
|
102
75
|
const signals = [
|
|
103
76
|
"SIGINT",
|
|
104
77
|
"SIGTERM",
|
|
105
78
|
"SIGHUP"
|
|
106
79
|
];
|
|
107
80
|
/**
|
|
108
|
-
* Checks the files, prints the banner, confirms and returns the env to run a command with
|
|
109
|
-
*/
|
|
110
|
-
async function prepareRun(command, { cwd, env, config, streams }, forceConfirm = false) {
|
|
111
|
-
if (config.passthrough.some((key) => env[key])) return env;
|
|
112
|
-
const name = currentEnvironment(cwd);
|
|
113
|
-
checkFiles(cwd, config, name);
|
|
114
|
-
const loaded = loadEnv(cwd, name, env);
|
|
115
|
-
const settings = environmentSettings(config, name);
|
|
116
|
-
const script = env.npm_lifecycle_event ?? command;
|
|
117
|
-
if (name !== "local") {
|
|
118
|
-
const badge = styleText([...badgeStyles[settings.color]], ` ${name.toUpperCase()} `, { stream: streams.output });
|
|
119
|
-
streams.output.write(`${badge} ${script} uses ${loaded.files.join(" + ")}\n`);
|
|
120
|
-
}
|
|
121
|
-
if ((forceConfirm || config.confirmScripts.includes(env.npm_lifecycle_event ?? "")) && settings.confirm && !await confirm(settings.confirm, name, `Run ${script} against ${name}`, streams)) throw new Error("Aborted.");
|
|
122
|
-
return loaded.env;
|
|
123
|
-
}
|
|
124
|
-
/**
|
|
125
81
|
* Runs a command with inherited stdio and forwards signals to it until it exits. In a terminal,
|
|
126
82
|
* Ctrl+C and hangups already reach the whole foreground process group, the command included, so
|
|
127
83
|
* only SIGTERM is forwarded there. newenv still catches the others, to exit after the command.
|
|
@@ -156,123 +112,122 @@ function spawnCommand(command, args, env) {
|
|
|
156
112
|
});
|
|
157
113
|
});
|
|
158
114
|
}
|
|
159
|
-
// src/
|
|
160
|
-
const
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
115
|
+
// src/commands/run/helpers.ts
|
|
116
|
+
const badgeStyles = {
|
|
117
|
+
red: [
|
|
118
|
+
"bgRed",
|
|
119
|
+
"white",
|
|
120
|
+
"bold"
|
|
121
|
+
],
|
|
122
|
+
yellow: ["bgYellow", "black"],
|
|
123
|
+
green: ["bgGreen", "black"],
|
|
124
|
+
blue: ["bgBlue", "white"],
|
|
125
|
+
magenta: ["bgMagenta", "white"],
|
|
126
|
+
cyan: ["bgCyan", "black"],
|
|
127
|
+
gray: ["bgGray", "white"]
|
|
165
128
|
};
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
if (argv[argv.findIndex((arg) => arg === "--" || !arg.startsWith("-"))] !== "--") {
|
|
206
|
-
program.command("use").description("Switch environment").argument("<name>", "Environment, local deletes .envs/current").action(async (name) => {
|
|
207
|
-
const envFile = `.envs/.env.${name}`;
|
|
208
|
-
if (name === "local") {
|
|
209
|
-
rmSync(join(cwd, currentFile), { force: true });
|
|
210
|
-
console.log(existsSync(join(cwd, envFile)) ? "Switched to local." : `Switched to local. ${envFile} not found. Create it with: newenv init`);
|
|
211
|
-
return;
|
|
212
|
-
}
|
|
213
|
-
const environments = listEnvironments(cwd);
|
|
214
|
-
if (!environments.includes(name)) throw new Error(`${envFile} not found. Available: ${environments.join(", ") || "none"}`);
|
|
215
|
-
const config = await loadConfig(cwd);
|
|
216
|
-
if (environmentSettings(config, name).confirm === "type-name" && !await confirm(true, name, `Switch to ${name}`, streams)) throw new Error("Aborted.");
|
|
217
|
-
writeFileSync(join(cwd, currentFile), `${name}\n`);
|
|
218
|
-
console.log(`Switched to ${name}.`);
|
|
129
|
+
/**
|
|
130
|
+
* Checks the files, prints the banner, confirms and returns the env to run a command with
|
|
131
|
+
*/
|
|
132
|
+
async function prepareRun(command, { cwd, env, config, streams }, forceConfirm = false) {
|
|
133
|
+
if (config.passthrough.some((key) => env[key])) return env;
|
|
134
|
+
const { name, files, values, settings } = resolveEnvironment(cwd, config, currentEnvironment({ cwd }), env);
|
|
135
|
+
const script = env.npm_lifecycle_event ?? command;
|
|
136
|
+
if (name !== "local") {
|
|
137
|
+
const badge = styleText([...badgeStyles[settings.color]], ` ${name.toUpperCase()} `, { stream: streams.output });
|
|
138
|
+
streams.output.write(`${badge} ${script} uses ${files.join(" + ")}\n`);
|
|
139
|
+
}
|
|
140
|
+
if ((forceConfirm || config.confirmScripts.includes(env.npm_lifecycle_event ?? "")) && !await confirm(settings.confirm, name, `Run ${script} against ${name}`, streams)) throw new EnvironmentError("Aborted.");
|
|
141
|
+
return values;
|
|
142
|
+
}
|
|
143
|
+
// src/commands/run/command.ts
|
|
144
|
+
/**
|
|
145
|
+
* `newenv [options] <command> [args...]`: the program's own action
|
|
146
|
+
*/
|
|
147
|
+
function runCommand(program) {
|
|
148
|
+
program.usage("[options] <command> [args...]").enablePositionalOptions().passThroughOptions().option("--confirm", "Ask before running, as for confirmScripts").argument("[command...]", "Command to run. Put -- before one named use, status or init").action(async (command, options) => {
|
|
149
|
+
const [name, ...args] = command;
|
|
150
|
+
if (!name) program.help({ error: process.argv.length > 2 });
|
|
151
|
+
const cwd = process.cwd();
|
|
152
|
+
const config = await loadEnvConfig(cwd);
|
|
153
|
+
const { code, signal } = await spawnCommand(name, args, await prepareRun(name, {
|
|
154
|
+
cwd,
|
|
155
|
+
env: process.env,
|
|
156
|
+
config,
|
|
157
|
+
streams: terminal
|
|
158
|
+
}, options.confirm)).catch((error) => {
|
|
159
|
+
if (error.code !== "ENOENT") throw error;
|
|
160
|
+
console.error(`newenv: command not found: ${name}`);
|
|
161
|
+
return {
|
|
162
|
+
code: 127,
|
|
163
|
+
signal: null
|
|
164
|
+
};
|
|
165
|
+
});
|
|
166
|
+
if (signal) process.kill(process.pid, signal);
|
|
167
|
+
process.exitCode = code ?? 1;
|
|
219
168
|
});
|
|
169
|
+
}
|
|
170
|
+
// src/commands/status/command.ts
|
|
171
|
+
/**
|
|
172
|
+
* `newenv status`: the environment and its files, never values
|
|
173
|
+
*/
|
|
174
|
+
function statusCommand(program) {
|
|
220
175
|
program.command("status").description("Show the environment and its files").action(async () => {
|
|
221
|
-
const
|
|
222
|
-
const
|
|
176
|
+
const cwd = process.cwd();
|
|
177
|
+
const config = await loadEnvConfig(cwd);
|
|
178
|
+
const name = currentEnvironment({ cwd });
|
|
223
179
|
const envFile = `.envs/.env.${name}`;
|
|
224
180
|
const files = [...existsSync(join(cwd, ".envs/.env")) ? [baseFile] : [], existsSync(join(cwd, envFile)) ? envFile : `${envFile} (missing)`];
|
|
225
181
|
const passthrough = config.passthrough.filter((key) => process.env[key]);
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
}
|
|
233
|
-
})();
|
|
182
|
+
let problem;
|
|
183
|
+
try {
|
|
184
|
+
checkFiles(cwd, config, name);
|
|
185
|
+
} catch (error) {
|
|
186
|
+
problem = errorMessage(error);
|
|
187
|
+
}
|
|
234
188
|
console.log([
|
|
235
189
|
["Environment", name],
|
|
236
190
|
["Files", files.join(" + ")],
|
|
237
|
-
["Available", listEnvironments(cwd).join(", ") || "none"],
|
|
238
|
-
["Config", config.file],
|
|
191
|
+
["Available", listEnvironments({ cwd }).join(", ") || "none"],
|
|
192
|
+
["Config", config.file && relative(cwd, config.file)],
|
|
239
193
|
["Passthrough", passthrough.length > 0 ? `${passthrough.join(", ")} set, files ignored` : void 0],
|
|
240
194
|
["Problem", problem]
|
|
241
195
|
].filter(([, value]) => value !== void 0).map(([label, value]) => `${label?.padEnd(12)} ${value}`).join("\n"));
|
|
242
196
|
});
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
const
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
const localExists = existsSync(local);
|
|
257
|
-
const example = [config.example ?? [], exampleFiles].flat().find((file) => existsSync(join(cwd, file)));
|
|
258
|
-
if (!localExists) {
|
|
259
|
-
if (example) copyFileSync(join(cwd, example), local, constants.COPYFILE_EXCL);
|
|
260
|
-
else writeFileSync(local, "", { flag: "wx" });
|
|
197
|
+
}
|
|
198
|
+
// src/commands/use/command.ts
|
|
199
|
+
/**
|
|
200
|
+
* `newenv use <name>`
|
|
201
|
+
*/
|
|
202
|
+
function useCommand(program) {
|
|
203
|
+
program.command("use").description("Switch environment").argument("<name>", "Environment, local deletes .envs/current").action(async (name) => {
|
|
204
|
+
const cwd = process.cwd();
|
|
205
|
+
const envFile = `.envs/.env.${name}`;
|
|
206
|
+
if (name === "local") {
|
|
207
|
+
rmSync(join(cwd, currentFile), { force: true });
|
|
208
|
+
console.log(existsSync(join(cwd, envFile)) ? "Switched to local." : `Switched to local. ${envFile} not found. Create it with: newenv init`);
|
|
209
|
+
return;
|
|
261
210
|
}
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
localExists ? "Exists .envs/.env.local" : `Created .envs/.env.local ${example ? `from ${example}` : "(empty, no example file)"}`,
|
|
268
|
-
`${config.file ? "Exists " : "Created"} ${configFile}`
|
|
269
|
-
].join("\n"));
|
|
211
|
+
checkKnown(cwd, name);
|
|
212
|
+
const config = await loadEnvConfig(cwd);
|
|
213
|
+
if (environmentSettings(config, name).confirm === "type-name" && !await confirm(true, name, `Switch to ${name}`, terminal)) throw new EnvironmentError("Aborted.");
|
|
214
|
+
writeFileSync(join(cwd, currentFile), `${name}\n`);
|
|
215
|
+
console.log(`Switched to ${name}.`);
|
|
270
216
|
});
|
|
271
217
|
}
|
|
218
|
+
// src/cli.ts
|
|
219
|
+
const argv = process.argv.slice(2);
|
|
220
|
+
const program = new Command("newenv").description("Run a command with the env files of the selected environment").version(version, "-v, --version", "Show version").helpOption("-h, --help", "Show help").configureOutput({ outputError: (message, write) => write(`newenv: ${message.replace(/^error: /, "")}`) });
|
|
221
|
+
runCommand(program);
|
|
222
|
+
if (argv[argv.findIndex((arg) => arg === "--" || !arg.startsWith("-"))] !== "--") {
|
|
223
|
+
useCommand(program);
|
|
224
|
+
statusCommand(program);
|
|
225
|
+
initCommand(program);
|
|
226
|
+
}
|
|
272
227
|
try {
|
|
273
228
|
await program.parseAsync(argv, { from: "user" });
|
|
274
229
|
} catch (error) {
|
|
275
|
-
console.error(`newenv: ${error
|
|
230
|
+
console.error(`newenv: ${errorMessage(error)}`);
|
|
276
231
|
process.exitCode = 1;
|
|
277
232
|
}
|
|
278
233
|
export {};
|
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\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,MAAoB;CAClF,MAAM,YAAY,aAAa,QAAQ,SAAS,WAAW,KAAK,KAAK,IAAI,CAAC,CAAC;CAC3E,IAAI,UAAU,SAAS,GACrB,MAAM,IAAI,MACR,GAAG,UAAU,KAAK,IAAI,E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;CACzE,QAAQ,WAAW;AACrB"}
|
|
1
|
+
{"version":3,"file":"cli.mjs","names":[],"sources":["../package.json","../src/commands/init/templates.ts","../src/commands/init/command.ts","../src/lib/process.ts","../src/commands/run/helpers.ts","../src/commands/run/command.ts","../src/commands/status/command.ts","../src/commands/use/command.ts","../src/cli.ts"],"sourcesContent":["","// `.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.\nexport const gitignoreBlock = [\n \"# newenv\",\n \"/.env*\",\n \"!/.envs/\",\n \"/.envs/*\",\n \"!/.envs/.env.example\",\n].join(\"\\n\");\n\n/**\n * Where .envs/.env.local is copied from: the first that exists, after the configured `example`\n */\nexport const 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\nexport const envSection = ` env: env({\n confirmScripts: [\"db:push\", \"db:migrate\", \"db:seed\"],\n forbiddenInBase: [\"DATABASE_URL\"],\n }),`;\n\nexport const configTemplate = `import { defineConfig } from \"@newcode-team/config\";\nimport { env } from \"@newcode-team/env\";\n\nexport default defineConfig({\n${envSection}\n});\n`;\n","import {\n appendFileSync,\n constants,\n copyFileSync,\n existsSync,\n mkdirSync,\n readFileSync,\n writeFileSync,\n} from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport { loadConfig } from \"@newcode-team/config\";\nimport type { Command } from \"commander\";\nimport { resolveConfig } from \"../../lib/config\";\nimport { envsDir } from \"../../lib/environment\";\nimport { configTemplate, envSection, exampleFiles, gitignoreBlock } from \"./templates\";\n\n/**\n * `newenv init`: sets up .envs/, the gitignore rules, .envs/.env.local and newcode.config.ts.\n * Existing files are kept: an existing config only gets the section to add printed\n */\nexport function initCommand(program: Command): void {\n program\n .command(\"init\")\n .description(\"Set up .envs/, the gitignore rules, .envs/.env.local and the config\")\n .action(async () => {\n const cwd = process.cwd();\n const loaded = await loadConfig({ cwd });\n const config = resolveConfig(loaded.env, loaded.file);\n\n const dirExists = existsSync(join(cwd, envsDir));\n mkdirSync(join(cwd, envsDir), { 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 // An existing config is the project's: init only says what to add\n if (!loaded.file) {\n writeFileSync(join(cwd, \"newcode.config.ts\"), configTemplate, { flag: \"wx\" });\n }\n const configFile = loaded.file ? relative(cwd, loaded.file) : \"newcode.config.ts\";\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 !loaded.file\n ? `Created ${configFile}`\n : loaded.env\n ? `Exists ${configFile}`\n : `Exists ${configFile} without an env section. Add it:\\n\\nimport { env } from \"@newcode-team/env\";\\n\\n${envSection}`,\n ].join(\"\\n\"),\n );\n });\n}\n","import spawn from \"cross-spawn\";\n\nconst signals = [\"SIGINT\", \"SIGTERM\", \"SIGHUP\"] as const;\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","import { styleText } from \"node:util\";\nimport type { Color, ResolvedConfig } from \"../../lib/config\";\nimport { currentEnvironment, resolveEnvironment } from \"../../lib/environment\";\nimport { EnvironmentError } from \"../../lib/errors\";\nimport { confirm, type Streams } from \"../../lib/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\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, files, values, settings } = resolveEnvironment(\n cwd,\n config,\n currentEnvironment({ cwd }),\n env,\n );\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 ${files.join(\" + \")}\\n`);\n }\n\n const asks = forceConfirm || config.confirmScripts.includes(env.npm_lifecycle_event ?? \"\");\n if (asks && !(await confirm(settings.confirm, name, `Run ${script} against ${name}`, streams))) {\n throw new EnvironmentError(\"Aborted.\");\n }\n\n return values;\n}\n","import type { Command } from \"commander\";\nimport { loadEnvConfig } from \"../../lib/config\";\nimport { spawnCommand } from \"../../lib/process\";\nimport { terminal } from \"../../lib/prompt\";\nimport { prepareRun } from \"./helpers\";\n\n/**\n * `newenv [options] <command> [args...]`: the program's own action\n */\nexport function runCommand(program: Command): void {\n program\n .usage(\"[options] <command> [args...]\")\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 .action(async (command: string[], options: { confirm?: boolean }) => {\n const [name, ...args] = command;\n if (!name) {\n // Help without arguments, an error with only options\n program.help({ error: process.argv.length > 2 });\n }\n\n const cwd = process.cwd();\n const config = await loadEnvConfig(cwd);\n const env = await prepareRun(\n name,\n { cwd, env: process.env, config, streams: terminal },\n options.confirm,\n );\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","import { existsSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport type { Command } from \"commander\";\nimport { loadEnvConfig } from \"../../lib/config\";\nimport { baseFile, checkFiles, currentEnvironment, listEnvironments } from \"../../lib/environment\";\nimport { errorMessage } from \"../../lib/errors\";\n\n/**\n * `newenv status`: the environment and its files, never values\n */\nexport function statusCommand(program: Command): void {\n program\n .command(\"status\")\n .description(\"Show the environment and its files\")\n .action(async () => {\n const cwd = process.cwd();\n const config = await loadEnvConfig(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 let problem: string | undefined;\n try {\n checkFiles(cwd, config, name);\n } catch (error) {\n problem = errorMessage(error);\n }\n\n console.log(\n [\n [\"Environment\", name],\n [\"Files\", files.join(\" + \")],\n [\"Available\", listEnvironments({ cwd }).join(\", \") || \"none\"],\n [\"Config\", config.file && relative(cwd, 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","import { existsSync, rmSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { Command } from \"commander\";\nimport { environmentSettings, loadEnvConfig } from \"../../lib/config\";\nimport { checkKnown, currentFile } from \"../../lib/environment\";\nimport { EnvironmentError } from \"../../lib/errors\";\nimport { confirm, terminal } from \"../../lib/prompt\";\n\n/**\n * `newenv use <name>`\n */\nexport function useCommand(program: Command): void {\n program\n .command(\"use\")\n .description(\"Switch environment\")\n .argument(\"<name>\", \"Environment, local deletes .envs/current\")\n .action(async (name: string) => {\n const cwd = process.cwd();\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 checkKnown(cwd, name);\n const config = await loadEnvConfig(cwd);\n if (\n environmentSettings(config, name).confirm === \"type-name\" &&\n !(await confirm(true, name, `Switch to ${name}`, terminal))\n ) {\n throw new EnvironmentError(\"Aborted.\");\n }\n\n writeFileSync(join(cwd, currentFile), `${name}\\n`);\n console.log(`Switched to ${name}.`);\n });\n}\n","#!/usr/bin/env node\nimport { Command } from \"commander\";\nimport { version } from \"../package.json\";\nimport { initCommand } from \"./commands/init/command\";\nimport { runCommand } from \"./commands/run/command\";\nimport { statusCommand } from \"./commands/status/command\";\nimport { useCommand } from \"./commands/use/command\";\nimport { errorMessage } from \"./lib/errors\";\n\nconst argv = process.argv.slice(2);\n\nconst program = new Command(\"newenv\")\n .description(\"Run a command with the env files of the selected environment\")\n .version(version, \"-v, --version\", \"Show version\")\n .helpOption(\"-h, --help\", \"Show help\")\n .configureOutput({\n outputError: (message, write) => write(`newenv: ${message.replace(/^error: /, \"\")}`),\n });\n\nrunCommand(program);\n// Commander still matches subcommands after --, so `newenv -- status` gets none\nif (argv[argv.findIndex((arg) => arg === \"--\" || !arg.startsWith(\"-\"))] !== \"--\") {\n useCommand(program);\n statusCommand(program);\n initCommand(program);\n}\n\ntry {\n await program.parseAsync(argv, { from: \"user\" });\n} catch (error) {\n console.error(`newenv: ${errorMessage(error)}`);\n process.exitCode = 1;\n}\n"],"mappings":";;;;;;;;;;;ACEA,MAAa,iBAAiB;CAC5B;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;;;;AAKX,MAAa,eAAe;CAAC;CAAsB;CAAgB;AAAc;AAGjF,MAAa,aAAa;;;;AAK1B,MAAa,iBAAiB;;;;EAI5B,WAAW;;;;;;;;ACLb,SAAgB,YAAY,SAAwB;CAClD,QACG,QAAQ,MAAM,CAAC,CACf,YAAY,qEAAqE,CAAC,CAClF,OAAO,YAAY;EAClB,MAAM,MAAM,QAAQ,IAAI;EACxB,MAAM,SAAS,MAAM,WAAW,EAAE,IAAI,CAAC;EACvC,MAAM,SAAS,cAAc,OAAO,KAAK,OAAO,IAAI;EAEpD,MAAM,YAAY,WAAW,KAAK,KAAK,OAAO,CAAC;EAC/C,UAAU,KAAK,KAAK,OAAO,GAAG,EAAE,WAAW,KAAK,CAAC;EAEjD,MAAM,gBAAgB,KAAK,KAAK,YAAY;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AAC,YAAY,eAC9C,CAAE,MAAM,QAAQ,MAAM,MAAM,aAAa,QAAQ,QAAQ,GAEzD,MAAM,IAAI,iBAAiB,UAAU;EAGvC,cAAc,KAAK,KAAK,WAAW,GAAG,GAAG,KAAK,GAAG;EACjD,QAAQ,IAAI,eAAe,KAAK,EAAE;CACpC,CAAC;AACL;;AChCA,MAAM,OAAO,QAAQ,KAAK,MAAM,CAAC;AAEjC,MAAM,UAAU,IAAI,QAAQ,QAAQ,CAAC,CAClC,YAAY,8DAA8D,CAAC,CAC3E,QAAQ,SAAS,iBAAiB,cAAc,CAAC,CACjD,WAAW,cAAc,WAAW,CAAC,CACrC,gBAAgB,EACf,cAAc,SAAS,UAAU,MAAM,WAAW,QAAQ,QAAQ,YAAY,EAAE,GAAG,EACrF,CAAC;AAEH,WAAW,OAAO;AAElB,IAAI,KAAK,KAAK,WAAW,QAAQ,QAAQ,QAAQ,CAAC,IAAI,WAAW,GAAG,CAAC,OAAO,MAAM;CAChF,WAAW,OAAO;CAClB,cAAc,OAAO;CACrB,YAAY,OAAO;AACrB;AAEA,IAAI;CACF,MAAM,QAAQ,WAAW,MAAM,EAAE,MAAM,OAAO,CAAC;AACjD,SAAS,OAAO;CACd,QAAQ,MAAM,WAAW,aAAa,KAAK,GAAG;CAC9C,QAAQ,WAAW;AACrB"}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { existsSync, readFileSync, readdirSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { parse } from "dotenv";
|
|
4
|
+
import { expand } from "dotenv-expand";
|
|
5
|
+
import { loadConfig } from "@newcode-team/config";
|
|
6
|
+
// src/lib/config.ts
|
|
7
|
+
/**
|
|
8
|
+
* The `env` section of newcode.config.ts. Returns its input: it types the section and adds `env`
|
|
9
|
+
* to `Config`
|
|
10
|
+
*/
|
|
11
|
+
const env = (section) => section;
|
|
12
|
+
const defaults = {
|
|
13
|
+
environments: {},
|
|
14
|
+
confirmScripts: [],
|
|
15
|
+
forbiddenInBase: [],
|
|
16
|
+
passthrough: []
|
|
17
|
+
};
|
|
18
|
+
const defaultEnvironments = {
|
|
19
|
+
local: { confirm: false },
|
|
20
|
+
production: {
|
|
21
|
+
color: "red",
|
|
22
|
+
confirm: "type-name"
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* The section with the defaults filled in
|
|
27
|
+
*/
|
|
28
|
+
function resolveConfig(section, file) {
|
|
29
|
+
return {
|
|
30
|
+
...defaults,
|
|
31
|
+
...section,
|
|
32
|
+
file
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* The `env` section of the project's newcode.config.ts, found from cwd up, with the defaults
|
|
37
|
+
*/
|
|
38
|
+
async function loadEnvConfig(cwd) {
|
|
39
|
+
const { env: section, file } = await loadConfig({ cwd });
|
|
40
|
+
return resolveConfig(section, file);
|
|
41
|
+
}
|
|
42
|
+
function environmentSettings(config, name) {
|
|
43
|
+
return {
|
|
44
|
+
color: "yellow",
|
|
45
|
+
confirm: true,
|
|
46
|
+
...defaultEnvironments[name],
|
|
47
|
+
...config.environments[name]
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
// src/lib/errors.ts
|
|
51
|
+
/**
|
|
52
|
+
* A refusal: root env files, forbidden base keys, a missing or unknown environment, missing keys,
|
|
53
|
+
* an abort
|
|
54
|
+
*/
|
|
55
|
+
var EnvironmentError = class extends Error {
|
|
56
|
+
name = "EnvironmentError";
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* What the command prints for an error. Ctrl+C on a prompt is an abort
|
|
60
|
+
*/
|
|
61
|
+
function errorMessage(error) {
|
|
62
|
+
if (error instanceof Error) return error.name === "ExitPromptError" ? "Aborted." : error.message;
|
|
63
|
+
return String(error);
|
|
64
|
+
}
|
|
65
|
+
// src/lib/prompt.ts
|
|
66
|
+
/**
|
|
67
|
+
* Prompts read the terminal and write to stderr, so stdout stays the command's
|
|
68
|
+
*/
|
|
69
|
+
const terminal = {
|
|
70
|
+
input: process.stdin,
|
|
71
|
+
output: process.stderr
|
|
72
|
+
};
|
|
73
|
+
/**
|
|
74
|
+
* Asks y/N, or to type the name for `"type-name"`. `false` answers yes without asking. Ctrl+C
|
|
75
|
+
* answers no. Throws without a TTY, so agents and CI can't confirm by accident.
|
|
76
|
+
*/
|
|
77
|
+
async function confirm(mode, name, question, streams) {
|
|
78
|
+
if (!mode) return true;
|
|
79
|
+
if (!streams.input.isTTY) throw new EnvironmentError(`${question}: needs confirmation, no TTY. Aborted.`);
|
|
80
|
+
try {
|
|
81
|
+
if (mode === "type-name") {
|
|
82
|
+
const { default: input } = await import("@inquirer/input");
|
|
83
|
+
return await input({ message: `${question}? Type "${name}" to confirm:` }, streams) === name;
|
|
84
|
+
}
|
|
85
|
+
const { default: confirmPrompt } = await import("@inquirer/confirm");
|
|
86
|
+
return await confirmPrompt({
|
|
87
|
+
message: `${question}?`,
|
|
88
|
+
default: false
|
|
89
|
+
}, streams);
|
|
90
|
+
} catch (error) {
|
|
91
|
+
if (error instanceof Error && error.name === "ExitPromptError") return false;
|
|
92
|
+
throw error;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
// src/lib/environment.ts
|
|
96
|
+
const envsDir = ".envs";
|
|
97
|
+
const baseFile = ".envs/.env";
|
|
98
|
+
const currentFile = ".envs/current";
|
|
99
|
+
const rootEnvFiles = [
|
|
100
|
+
".env",
|
|
101
|
+
".env.local",
|
|
102
|
+
".env.development",
|
|
103
|
+
".env.development.local",
|
|
104
|
+
".env.production",
|
|
105
|
+
".env.production.local"
|
|
106
|
+
];
|
|
107
|
+
/**
|
|
108
|
+
* The selected environment: the name in .envs/current, or local
|
|
109
|
+
*/
|
|
110
|
+
function currentEnvironment({ cwd = process.cwd() } = {}) {
|
|
111
|
+
const file = join(cwd, currentFile);
|
|
112
|
+
return existsSync(file) && readFileSync(file, "utf8").trim() || "local";
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* The environments with a .envs/.env.<name> file, without example, sorted
|
|
116
|
+
*/
|
|
117
|
+
function listEnvironments({ cwd = process.cwd() } = {}) {
|
|
118
|
+
const dir = join(cwd, envsDir);
|
|
119
|
+
return existsSync(dir) ? readdirSync(dir).map((file) => /^\.env\.([\w-]+)$/.exec(file)?.[1]).filter((name) => name !== void 0 && name !== "example").toSorted() : [];
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Throws when the environment has no .envs/.env.<name> file, listing the ones that do
|
|
123
|
+
*/
|
|
124
|
+
function checkKnown(cwd, name) {
|
|
125
|
+
const environments = listEnvironments({ cwd });
|
|
126
|
+
if (!environments.includes(name)) throw new EnvironmentError(`.envs/.env.${name} not found. Available: ${environments.join(", ") || "none"}`);
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Throws when root env files exist, the base holds forbidden keys or the environment file is missing
|
|
130
|
+
*/
|
|
131
|
+
function checkFiles(cwd, config, name) {
|
|
132
|
+
const rootFiles = rootEnvFiles.filter((file) => existsSync(join(cwd, file)));
|
|
133
|
+
if (rootFiles.length > 0) throw new EnvironmentError(`${rootFiles.join(", ")} in the project root. Move into .envs/: mv -n ${rootFiles.join(" ")} .envs/`);
|
|
134
|
+
const base = join(cwd, baseFile);
|
|
135
|
+
const forbidden = existsSync(base) ? Object.keys(parse(readFileSync(base))).filter((key) => config.forbiddenInBase.includes(key)) : [];
|
|
136
|
+
if (forbidden.length > 0) throw new EnvironmentError(`${forbidden.join(", ")} in the shared ${baseFile}. Move to .envs/.env.<name> for each environment.`);
|
|
137
|
+
const envFile = `.envs/.env.${name}`;
|
|
138
|
+
if (!existsSync(join(cwd, envFile))) throw new EnvironmentError(name === "local" ? `${envFile} not found. Create it with: newenv init` : `${envFile} not found. Switch back with: newenv use local`);
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Merges the shell env when given, the base and the environment file: the last one wins. Expands
|
|
142
|
+
* variables over the merged env, the same way dotenv-cli does. Never touches process.env.
|
|
143
|
+
*/
|
|
144
|
+
function loadEnv(cwd, name, shell) {
|
|
145
|
+
const files = [baseFile, `.envs/.env.${name}`].filter((file) => existsSync(join(cwd, file)));
|
|
146
|
+
const env = Object.assign(Object.fromEntries(Object.entries(shell ?? {}).filter(([, value]) => value !== void 0)), ...files.map((file) => parse(readFileSync(join(cwd, file)))));
|
|
147
|
+
expand({
|
|
148
|
+
parsed: env,
|
|
149
|
+
processEnv: env
|
|
150
|
+
});
|
|
151
|
+
return {
|
|
152
|
+
env,
|
|
153
|
+
files
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
function createEnvironment(name, files, values, settings) {
|
|
157
|
+
return {
|
|
158
|
+
name,
|
|
159
|
+
files,
|
|
160
|
+
values,
|
|
161
|
+
settings,
|
|
162
|
+
require(...keys) {
|
|
163
|
+
const missing = keys.filter((key) => !values[key]);
|
|
164
|
+
if (missing.length > 0) throw new EnvironmentError(`${missing.join(", ")} missing in environment "${name}" (${files.join(", ") || "passthrough"})`);
|
|
165
|
+
return Object.fromEntries(keys.map((key) => [key, values[key]]));
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Checks the files and loads the environment. The CLI and loadEnvironment share it.
|
|
171
|
+
*/
|
|
172
|
+
function resolveEnvironment(cwd, config, name, shell) {
|
|
173
|
+
checkFiles(cwd, config, name);
|
|
174
|
+
const { env, files } = loadEnv(cwd, name, shell);
|
|
175
|
+
return createEnvironment(name, files, env, environmentSettings(config, name));
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Loads an environment with the CLI's checks, the current one without a name. Only the env files
|
|
179
|
+
* by default. With `shell`, merges shell, base and environment file like the CLI does. Never
|
|
180
|
+
* writes to process.env.
|
|
181
|
+
*/
|
|
182
|
+
async function loadEnvironment(name, { cwd = process.cwd(), shell } = {}) {
|
|
183
|
+
const config = await loadEnvConfig(cwd);
|
|
184
|
+
const host = shell ?? process.env;
|
|
185
|
+
const passthrough = config.passthrough.filter((key) => host[key]);
|
|
186
|
+
if (passthrough.length > 0) {
|
|
187
|
+
if (name !== void 0) throw new EnvironmentError(`Can't load ${name}: ${passthrough.join(", ")} set, files ignored (passthrough).`);
|
|
188
|
+
const current = currentEnvironment({ cwd });
|
|
189
|
+
return createEnvironment(current, [], Object.fromEntries(Object.entries(host).filter((entry) => entry[1] !== void 0)), environmentSettings(config, current));
|
|
190
|
+
}
|
|
191
|
+
if (name !== void 0) checkKnown(cwd, name);
|
|
192
|
+
return resolveEnvironment(cwd, config, name ?? currentEnvironment({ cwd }), shell);
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Asks like the CLI does for confirmScripts, following environments.<name>.confirm: false answers
|
|
196
|
+
* yes without asking, true asks y/N, "type-name" asks to type the name. Throws without a TTY.
|
|
197
|
+
*/
|
|
198
|
+
async function confirmEnvironment(name, question, { cwd = process.cwd() } = {}) {
|
|
199
|
+
return confirm(environmentSettings(await loadEnvConfig(cwd), name).confirm, name, question, terminal);
|
|
200
|
+
}
|
|
201
|
+
export { loadEnvConfig as _, currentEnvironment as a, listEnvironments as c, confirm as d, terminal as f, environmentSettings as g, env as h, confirmEnvironment as i, loadEnvironment as l, errorMessage as m, checkFiles as n, currentFile as o, EnvironmentError as p, checkKnown as r, envsDir as s, baseFile as t, resolveEnvironment as u, resolveConfig as v };
|
|
202
|
+
|
|
203
|
+
//# sourceMappingURL=environment-N9SRYkh6.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"environment-N9SRYkh6.mjs","names":[],"sources":["../src/lib/config.ts","../src/lib/errors.ts","../src/lib/prompt.ts","../src/lib/environment.ts"],"sourcesContent":["import { loadConfig } from \"@newcode-team/config\";\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\n/**\n * The `env` section of newcode.config.ts\n */\nexport interface EnvConfig {\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<EnvConfig, \"example\">> & {\n example?: string;\n /**\n * The config file that was loaded\n */\n file?: string;\n};\n\ndeclare module \"@newcode-team/config\" {\n interface Config {\n env?: EnvConfig;\n }\n}\n\n/**\n * The `env` section of newcode.config.ts. Returns its input: it types the section and adds `env`\n * to `Config`\n */\nexport const env = (section: EnvConfig): EnvConfig => section;\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\n/**\n * The section with the defaults filled in\n */\nexport function resolveConfig(section: EnvConfig | undefined, file?: string): ResolvedConfig {\n return { ...defaults, ...section, file };\n}\n\n/**\n * The `env` section of the project's newcode.config.ts, found from cwd up, with the defaults\n */\nexport async function loadEnvConfig(cwd: string): Promise<ResolvedConfig> {\n const { env: section, file } = await loadConfig({ cwd });\n return resolveConfig(section, 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","/**\n * A refusal: root env files, forbidden base keys, a missing or unknown environment, missing keys,\n * an abort\n */\nexport class EnvironmentError extends Error {\n override name = \"EnvironmentError\";\n}\n\n/**\n * What the command prints for an error. Ctrl+C on a prompt is an abort\n */\nexport function errorMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.name === \"ExitPromptError\" ? \"Aborted.\" : error.message;\n }\n return String(error);\n}\n","import type { Readable, Writable } from \"node:stream\";\nimport { EnvironmentError } from \"./errors\";\n\nexport interface Streams {\n input: Readable & { isTTY?: boolean };\n output: Writable;\n}\n\n/**\n * Prompts read the terminal and write to stderr, so stdout stays the command's\n */\nexport const terminal: Streams = { input: process.stdin, output: process.stderr };\n\n/**\n * Asks y/N, or to type the name for `\"type-name\"`. `false` answers yes without asking. Ctrl+C\n * answers no. Throws without a TTY, so agents and CI can't confirm by accident.\n */\nexport async function confirm(\n mode: boolean | \"type-name\",\n name: string,\n question: string,\n streams: Streams,\n): Promise<boolean> {\n if (!mode) {\n return true;\n }\n if (!streams.input.isTTY) {\n throw new EnvironmentError(`${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 { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { parse } from \"dotenv\";\nimport { expand } from \"dotenv-expand\";\nimport {\n type EnvironmentConfig,\n environmentSettings,\n loadEnvConfig,\n type ResolvedConfig,\n} from \"./config\";\nimport { EnvironmentError } from \"./errors\";\nimport { confirm, terminal } from \"./prompt\";\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\nexport interface Environment {\n name: string;\n /**\n * The files that were loaded, relative to cwd\n */\n files: string[];\n values: Record<string, string>;\n settings: Required<EnvironmentConfig>;\n /**\n * The given keys. Throws an `EnvironmentError` when one is missing or empty\n */\n require<const Key extends string>(...keys: Key[]): Record<Key, string>;\n}\n\n/**\n * The selected environment: the name in .envs/current, or local\n */\nexport function currentEnvironment({ cwd = process.cwd() }: { 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, without example, sorted\n */\nexport function listEnvironments({ cwd = process.cwd() }: { 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 the environment has no .envs/.env.<name> file, listing the ones that do\n */\nexport function checkKnown(cwd: string, name: string): void {\n const environments = listEnvironments({ cwd });\n if (!environments.includes(name)) {\n throw new EnvironmentError(\n `.envs/.env.${name} not found. Available: ${environments.join(\", \") || \"none\"}`,\n );\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 EnvironmentError(\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 EnvironmentError(\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 EnvironmentError(\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 when given, the base and the environment file: the last one wins. Expands\n * variables over the merged env, the same way dotenv-cli does. Never touches process.env.\n */\nexport function loadEnv(\n cwd: string,\n name: string,\n shell?: Record<string, string | undefined>,\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 Object.fromEntries(Object.entries(shell ?? {}).filter(([, value]) => value !== undefined)),\n ...files.map((file) => parse(readFileSync(join(cwd, file)))),\n );\n expand({ parsed: env, processEnv: env });\n return { env, files };\n}\n\nfunction createEnvironment(\n name: string,\n files: string[],\n values: Record<string, string>,\n settings: Required<EnvironmentConfig>,\n): Environment {\n return {\n name,\n files,\n values,\n settings,\n require<const Key extends string>(...keys: Key[]): Record<Key, string> {\n const missing = keys.filter((key) => !values[key]);\n if (missing.length > 0) {\n throw new EnvironmentError(\n `${missing.join(\", \")} missing in environment \"${name}\" (${files.join(\", \") || \"passthrough\"})`,\n );\n }\n return Object.fromEntries(keys.map((key) => [key, values[key]])) as Record<Key, string>;\n },\n };\n}\n\n/**\n * Checks the files and loads the environment. The CLI and loadEnvironment share it.\n */\nexport function resolveEnvironment(\n cwd: string,\n config: ResolvedConfig,\n name: string,\n shell?: Record<string, string | undefined>,\n): Environment {\n checkFiles(cwd, config, name);\n const { env, files } = loadEnv(cwd, name, shell);\n return createEnvironment(name, files, env, environmentSettings(config, name));\n}\n\n/**\n * Loads an environment with the CLI's checks, the current one without a name. Only the env files\n * by default. With `shell`, merges shell, base and environment file like the CLI does. Never\n * writes to process.env.\n */\nexport async function loadEnvironment(\n name?: string,\n { cwd = process.cwd(), shell }: { cwd?: string; shell?: Record<string, string | undefined> } = {},\n): Promise<Environment> {\n const config = await loadEnvConfig(cwd);\n const host = shell ?? process.env;\n const passthrough = config.passthrough.filter((key) => host[key]);\n\n if (passthrough.length > 0) {\n if (name !== undefined) {\n throw new EnvironmentError(\n `Can't load ${name}: ${passthrough.join(\", \")} set, files ignored (passthrough).`,\n );\n }\n const current = currentEnvironment({ cwd });\n return createEnvironment(\n current,\n [],\n Object.fromEntries(\n Object.entries(host).filter((entry): entry is [string, string] => entry[1] !== undefined),\n ),\n environmentSettings(config, current),\n );\n }\n\n if (name !== undefined) {\n checkKnown(cwd, name);\n }\n return resolveEnvironment(cwd, config, name ?? currentEnvironment({ cwd }), shell);\n}\n\n/**\n * Asks like the CLI does for confirmScripts, following environments.<name>.confirm: false answers\n * yes without asking, true asks y/N, \"type-name\" asks to type the name. Throws without a TTY.\n */\nexport async function confirmEnvironment(\n name: string,\n question: string,\n { cwd = process.cwd() }: { cwd?: string } = {},\n): Promise<boolean> {\n const config = await loadEnvConfig(cwd);\n return confirm(environmentSettings(config, name).confirm, name, question, terminal);\n}\n"],"mappings":";;;;;;;;;;AA8DA,MAAa,OAAO,YAAkC;AAEtD,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;;;;AAKA,SAAgB,cAAc,SAAgC,MAA+B;CAC3F,OAAO;EAAE,GAAG;EAAU,GAAG;EAAS;CAAK;AACzC;;;;AAKA,eAAsB,cAAc,KAAsC;CACxE,MAAM,EAAE,KAAK,SAAS,SAAS,MAAM,WAAW,EAAE,IAAI,CAAC;CACvD,O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AAI,SAAS,KAAA,GACX,MAAM,IAAI,iBACR,cAAc,KAAK,IAAI,YAAY,KAAK,IAAI,EAAE,mCAChD;EAEF,MAAM,UAAU,mBAAmB,EAAE,IAAI,CAAC;EAC1C,OAAO,kBACL,SACA,CAAC,GACD,OAAO,YACL,OAAO,QAAQ,IAAI,CAAC,CAAC,QAAQ,UAAqC,MAAM,OAAO,KAAA,CAAS,CAC1F,GACA,oBAAoB,QAAQ,OAAO,CACrC;CACF;CAEA,IAAI,SAAS,KAAA,GACX,WAAW,KAAK,IAAI;CAEtB,OAAO,mBAAmB,KAAK,QAAQ,QAAQ,mBAAmB,EAAE,IAAI,CAAC,GAAG,KAAK;AACnF;;;;;AAMA,eAAsB,mBACpB,MACA,UACA,EAAE,MAAM,QAAQ,IAAI,MAAwB,CAAC,GAC3B;CAElB,OAAO,QAAQ,oBAAoB,MADd,cAAc,GAAG,GACK,IAAI,CAAC,CAAC,SAAS,MAAM,UAAU,QAAQ;AACpF"}
|
package/dist/index.d.mts
CHANGED
|
@@ -11,7 +11,10 @@ interface EnvironmentConfig {
|
|
|
11
11
|
*/
|
|
12
12
|
confirm?: boolean | "type-name";
|
|
13
13
|
}
|
|
14
|
-
|
|
14
|
+
/**
|
|
15
|
+
* The `env` section of newcode.config.ts
|
|
16
|
+
*/
|
|
17
|
+
interface EnvConfig {
|
|
15
18
|
/**
|
|
16
19
|
* Settings per environment name
|
|
17
20
|
*/
|
|
@@ -34,6 +37,63 @@ interface Config {
|
|
|
34
37
|
*/
|
|
35
38
|
example?: string;
|
|
36
39
|
}
|
|
37
|
-
|
|
38
|
-
|
|
40
|
+
declare module "@newcode-team/config" {
|
|
41
|
+
interface Config {
|
|
42
|
+
env?: EnvConfig;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* The `env` section of newcode.config.ts. Returns its input: it types the section and adds `env`
|
|
47
|
+
* to `Config`
|
|
48
|
+
*/
|
|
49
|
+
export declare const env: (section: EnvConfig) => EnvConfig;
|
|
50
|
+
interface Environment {
|
|
51
|
+
name: string;
|
|
52
|
+
/**
|
|
53
|
+
* The files that were loaded, relative to cwd
|
|
54
|
+
*/
|
|
55
|
+
files: string[];
|
|
56
|
+
values: Record<string, string>;
|
|
57
|
+
settings: Required<EnvironmentConfig>;
|
|
58
|
+
/**
|
|
59
|
+
* The given keys. Throws an `EnvironmentError` when one is missing or empty
|
|
60
|
+
*/
|
|
61
|
+
require<const Key extends string>(...keys: Key[]): Record<Key, string>;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* The selected environment: the name in .envs/current, or local
|
|
65
|
+
*/
|
|
66
|
+
export declare function currentEnvironment({ cwd }?: {
|
|
67
|
+
cwd?: string;
|
|
68
|
+
}): string;
|
|
69
|
+
/**
|
|
70
|
+
* The environments with a .envs/.env.<name> file, without example, sorted
|
|
71
|
+
*/
|
|
72
|
+
export declare function listEnvironments({ cwd }?: {
|
|
73
|
+
cwd?: string;
|
|
74
|
+
}): string[];
|
|
75
|
+
/**
|
|
76
|
+
* Loads an environment with the CLI's checks, the current one without a name. Only the env files
|
|
77
|
+
* by default. With `shell`, merges shell, base and environment file like the CLI does. Never
|
|
78
|
+
* writes to process.env.
|
|
79
|
+
*/
|
|
80
|
+
export declare function loadEnvironment(name?: string, { cwd, shell }?: {
|
|
81
|
+
cwd?: string;
|
|
82
|
+
shell?: Record<string, string | undefined>;
|
|
83
|
+
}): Promise<Environment>;
|
|
84
|
+
/**
|
|
85
|
+
* Asks like the CLI does for confirmScripts, following environments.<name>.confirm: false answers
|
|
86
|
+
* yes without asking, true asks y/N, "type-name" asks to type the name. Throws without a TTY.
|
|
87
|
+
*/
|
|
88
|
+
export declare function confirmEnvironment(name: string, question: string, { cwd }?: {
|
|
89
|
+
cwd?: string;
|
|
90
|
+
}): Promise<boolean>;
|
|
91
|
+
/**
|
|
92
|
+
* A refusal: root env files, forbidden base keys, a missing or unknown environment, missing keys,
|
|
93
|
+
* an abort
|
|
94
|
+
*/
|
|
95
|
+
export declare class EnvironmentError extends Error {
|
|
96
|
+
name: string;
|
|
97
|
+
}
|
|
98
|
+
export type { Color, EnvConfig, Environment, EnvironmentConfig };
|
|
39
99
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/config.ts"],"mappings":"A,
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/lib/config.ts","../src/lib/environment.ts","../src/lib/errors.ts"],"mappings":"A,KAEY;UAEK;;;;EAIf,QAAQ;;;;;;EAMR;;;;;UAMe;;;;EAIf,eAAe,eAAe;;;;EAI9B;;;;EAIA;;;;;EAKA;;;;EAIA;;;YAYU;IACR,MAAM;;;;;;;qBAQG,MAAO,SAAS,cAAY;UClCxB;EACf;;;;EAIA;EACA,QAAQ;EACR,UAAU,SAAS;;;;EAInB,cAAc,uBAAuB,MAAM,QAAQ,OAAO;;;;;wBAM5C,qBAAqB;EAAyB;;;;;wBAQ9C,mBAAmB;EAAyB;;;;;;;wBAiHtC,gBACpB,iBACE,KAAqB;EAAW;EAAc,QAAQ;IACvD,QAAQ;;;;;wBAgCW,mBACpB,cACA,oBACE;EAAyB;IAC1B;;;;;qBCzMU,yBAAyB;EAC3B"}
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { p as EnvironmentError, i as confirmEnvironment, a as currentEnvironment, h as env, c as listEnvironments, l as loadEnvironment } from "./environment-N9SRYkh6.mjs";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@newcode-team/env",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Per-environment env files for any command, with switching and guards",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -8,10 +8,11 @@
|
|
|
8
8
|
"author": "NewCode",
|
|
9
9
|
"repository": {
|
|
10
10
|
"type": "git",
|
|
11
|
-
"url": "git+https://github.com/NewCodeDevelopment/
|
|
11
|
+
"url": "git+https://github.com/NewCodeDevelopment/tools.git",
|
|
12
|
+
"directory": "packages/env"
|
|
12
13
|
},
|
|
13
|
-
"homepage": "https://github.com/NewCodeDevelopment/
|
|
14
|
-
"bugs": "https://github.com/NewCodeDevelopment/
|
|
14
|
+
"homepage": "https://github.com/NewCodeDevelopment/tools/tree/main/packages/env#readme",
|
|
15
|
+
"bugs": "https://github.com/NewCodeDevelopment/tools/issues",
|
|
15
16
|
"keywords": [
|
|
16
17
|
"env",
|
|
17
18
|
"dotenv",
|
|
@@ -31,18 +32,18 @@
|
|
|
31
32
|
},
|
|
32
33
|
"devDependencies": {
|
|
33
34
|
"@arethetypeswrong/core": "^0.18.5",
|
|
34
|
-
"@
|
|
35
|
+
"@newcode-team/config": "0.2.0",
|
|
35
36
|
"@types/cross-spawn": "^6.0.6",
|
|
36
37
|
"@types/node": "^24.19.2",
|
|
37
38
|
"dotenv-cli": "11.0.0",
|
|
38
|
-
"oxfmt": "0.78.0",
|
|
39
|
-
"oxlint": "1.93.0",
|
|
40
39
|
"publint": "^0.3.25",
|
|
41
40
|
"tsdown": "^0.23.7",
|
|
42
41
|
"typescript": "5.9.3",
|
|
43
42
|
"unrun": "^0.3.1",
|
|
44
|
-
"vitest": "^5.1.0"
|
|
45
|
-
|
|
43
|
+
"vitest": "^5.1.0"
|
|
44
|
+
},
|
|
45
|
+
"peerDependencies": {
|
|
46
|
+
"@newcode-team/config": "^0.2.0"
|
|
46
47
|
},
|
|
47
48
|
"publishConfig": {
|
|
48
49
|
"access": "public"
|
|
@@ -57,17 +58,6 @@
|
|
|
57
58
|
".": "./dist/index.mjs",
|
|
58
59
|
"./package.json": "./package.json"
|
|
59
60
|
},
|
|
60
|
-
"devEngines": {
|
|
61
|
-
"packageManager": {
|
|
62
|
-
"name": "pnpm",
|
|
63
|
-
"version": "11.27.0"
|
|
64
|
-
},
|
|
65
|
-
"runtime": {
|
|
66
|
-
"name": "node",
|
|
67
|
-
"version": "^24.x",
|
|
68
|
-
"onFail": "download"
|
|
69
|
-
}
|
|
70
|
-
},
|
|
71
61
|
"scripts": {
|
|
72
62
|
"dev": "tsdown --config tsdown.config.ts --config-loader unrun --watch --no-clean",
|
|
73
63
|
"build": "tsdown --config tsdown.config.ts --config-loader unrun --no-clean",
|
|
@@ -79,9 +69,6 @@
|
|
|
79
69
|
"typecheck": "tsc --noEmit",
|
|
80
70
|
"test": "vitest",
|
|
81
71
|
"test:ci": "vitest run",
|
|
82
|
-
"
|
|
83
|
-
"version-packages": "changeset version",
|
|
84
|
-
"release": "pnpm build:release && changeset publish",
|
|
85
|
-
"clean": "rm -rf node_modules && rm -rf dist"
|
|
72
|
+
"clean": "rm -rf .turbo && rm -rf node_modules && rm -rf dist"
|
|
86
73
|
}
|
|
87
74
|
}
|
package/dist/config-DOtqBeMb.mjs
DELETED
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
import { existsSync } from "node:fs";
|
|
2
|
-
import { join } from "node:path";
|
|
3
|
-
import { pathToFileURL } from "node:url";
|
|
4
|
-
// src/config.ts
|
|
5
|
-
const defineConfig = (config) => config;
|
|
6
|
-
const defaults = {
|
|
7
|
-
environments: {},
|
|
8
|
-
confirmScripts: [],
|
|
9
|
-
forbiddenInBase: [],
|
|
10
|
-
passthrough: []
|
|
11
|
-
};
|
|
12
|
-
const defaultEnvironments = {
|
|
13
|
-
local: { confirm: false },
|
|
14
|
-
production: {
|
|
15
|
-
color: "red",
|
|
16
|
-
confirm: "type-name"
|
|
17
|
-
}
|
|
18
|
-
};
|
|
19
|
-
const configFiles = [
|
|
20
|
-
"newenv.config.ts",
|
|
21
|
-
"newenv.config.mjs",
|
|
22
|
-
"newenv.config.js"
|
|
23
|
-
];
|
|
24
|
-
async function loadConfig(cwd) {
|
|
25
|
-
const file = configFiles.find((name) => existsSync(join(cwd, name)));
|
|
26
|
-
if (!file) return defaults;
|
|
27
|
-
const module = await import(pathToFileURL(join(cwd, file)).href);
|
|
28
|
-
return {
|
|
29
|
-
...defaults,
|
|
30
|
-
...module.default,
|
|
31
|
-
file
|
|
32
|
-
};
|
|
33
|
-
}
|
|
34
|
-
function environmentSettings(config, name) {
|
|
35
|
-
return {
|
|
36
|
-
color: "yellow",
|
|
37
|
-
confirm: true,
|
|
38
|
-
...defaultEnvironments[name],
|
|
39
|
-
...config.environments[name]
|
|
40
|
-
};
|
|
41
|
-
}
|
|
42
|
-
export { environmentSettings as n, loadConfig as r, defineConfig as t };
|
|
43
|
-
|
|
44
|
-
//# sourceMappingURL=config-DOtqBeMb.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
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"}
|