@dotenvx/dotenvx 2.32.2 → 2.32.4

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/CHANGELOG.md CHANGED
@@ -2,7 +2,20 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4
4
 
5
- [Unreleased](https://github.com/dotenvx/dotenvx/compare/v2.32.2...main)
5
+ [Unreleased](https://github.com/dotenvx/dotenvx/compare/v2.32.4...main)
6
+
7
+ ## [2.32.4](https://github.com/dotenvx/dotenvx/compare/v2.32.3...v2.32.4) (2026-10-01)
8
+
9
+ ### Changed
10
+
11
+ * Make `Envfile` the filename. Final decision. ([#1003](https://github.com/dotenvx/dotenvx/pull/1003))
12
+
13
+ ## [2.32.3](https://github.com/dotenvx/dotenvx/compare/v2.32.2...v2.32.3) (2026-09-30)
14
+
15
+ ### Changed
16
+
17
+ * Make `Dotenvspec` the filename ([#1002](https://github.com/dotenvx/dotenvx/pull/1002))
18
+ * Improve startup time for cli ([#1001](https://github.com/dotenvx/dotenvx/pull/1001))
6
19
 
7
20
  ## [2.32.2](https://github.com/dotenvx/dotenvx/compare/v2.32.1...v2.32.2) (2026-09-29)
8
21
 
package/README.md CHANGED
@@ -1305,9 +1305,9 @@ Hello String
1305
1305
  ```
1306
1306
 
1307
1307
  </details>
1308
- <details><summary>`run with Envspec redaction`</summary><br>
1308
+ <details><summary>`run with Envfile redaction`</summary><br>
1309
1309
 
1310
- Run any command with real environment variables while automatically redacting values selected by your Envspec from stdout and stderr.
1310
+ Run any command with real environment variables while automatically redacting values selected by your Envfile from stdout and stderr.
1311
1311
 
1312
1312
  ```sh
1313
1313
  $ echo "SECRET=super-secret-value" > .env
@@ -1319,9 +1319,9 @@ $ dotenvx run --quiet -- node index.js
1319
1319
  [REDACTED] visible-value
1320
1320
  ```
1321
1321
 
1322
- With an Envspec, all values are redacted by default. Use `redacted: false` on individual declarations to leave those values visible. `spec` generates these settings, including public-name exceptions. If an existing environment variable takes precedence, its effective value follows the same rules. Matching is exact, so transformed or derived values are not redacted.
1322
+ With an Envfile, all values are redacted by default. Use `redacted: false` on individual declarations to leave those values visible. `spec` generates these settings, including public-name exceptions. If an existing environment variable takes precedence, its effective value follows the same rules. Matching is exact, so transformed or derived values are not redacted.
1323
1323
 
1324
- Without an Envspec, `dotenvx run --redact -- yourcommand` redacts loaded values except recognized public names (containing `PUBLIC` or starting with `VITE`, case-sensitive). `_PLAIN` values are redacted too. Without either an Envspec or `--redact`, output is not redacted. An Envspec always takes precedence: its rules apply automatically, even when `--redact` is passed.
1324
+ Without an Envfile, `dotenvx run --redact -- yourcommand` redacts loaded values except recognized public names (containing `PUBLIC` or starting with `VITE`, case-sensitive). `_PLAIN` values are redacted too. Without either an Envfile or `--redact`, output is not redacted. An Envfile always takes precedence: its rules apply automatically, even when `--redact` is passed.
1325
1325
 
1326
1326
  When stdin, stdout, and stderr are attached to a terminal, dotenvx preserves interactive behavior on macOS and Linux systems with `script` available. Piped and redirected commands continue to use normal stdin, stdout, and stderr streams.
1327
1327
 
@@ -1567,12 +1567,14 @@ Hello production
1567
1567
  Available log levels are `error, warn, info, verbose, debug, silly` ([source](https://docs.npmjs.com/cli/v8/using-npm/logging#setting-log-levels))
1568
1568
 
1569
1569
  </details>
1570
- <details><summary>`run with an Envspec`</summary><br>
1570
+ <details><summary>`run with an Envfile`</summary><br>
1571
1571
 
1572
- When an `Envspec` is present, `run` and `check` validate the same requirements: required values, types, enums, ranges, and storage encryption. No validation flag is needed. `run` performs validation before starting your command.
1572
+ `Envfile` is like a Dockerfile for your secrets.
1573
+
1574
+ When an `Envfile` is present, `run` and `check` validate the same requirements: required values, types, enums, ranges, and storage encryption. No validation flag is needed. `run` performs validation before starting your command.
1573
1575
 
1574
1576
  ```ruby
1575
- # Envspec
1577
+ # Envfile
1576
1578
  env "DATABASE_URL", type: "url"
1577
1579
  env "API_KEY"
1578
1580
  env "SENTRY_DSN", optional: true
@@ -1583,9 +1585,11 @@ $ dotenvx run -- node index.js
1583
1585
  [INVALID_ENV] DATABASE_URL is required; API_KEY is required
1584
1586
  ```
1585
1587
 
1586
- Envspec validation failures, including unencrypted values, warn by default; `run --strict` stops before launching the command. A `strict true` setting in Envspec, at the root or in an active file block, also makes its validation failures fatal. `check` always exits with failure when validation fails. Strictness changes enforcement, not which rules are checked. Invalid Envspec syntax always stops execution.
1588
+ Envfile validation failures, including unencrypted values, warn by default; `run --strict` stops before launching the command. A `strict true` setting in Envfile, at the root or in an active file block, also makes its validation failures fatal. `check` always exits with failure when validation fails. Strictness changes enforcement, not which rules are checked. Invalid Envfile syntax always stops execution.
1589
+
1590
+ Envfile values default to `redacted: true`: `run` masks their values in child stdout/stderr and resolved-value debug output, while the child still receives the real values. Set `redacted: false` for values that may appear in output. This is independent of `encrypted: true`, which requires an encrypted source.
1587
1591
 
1588
- Envspec values default to `redacted: true`: `run` masks their values in child stdout/stderr and resolved-value debug output, while the child still receives the real values. Set `redacted: false` for values that may appear in output. This is independent of `encrypted: true`, which requires an encrypted source.
1592
+ The synchronous `dotenvx.config()` API also reads `Envfile` from the current working directory and validates the final resolved values using the same rules, including selected file blocks and storage encryption. Validation failures warn and are returned in `{ parsed, error }`; `config({ strict: true })` or an applicable Envfile `strict true` setting makes failures throw. `ignore: ['INVALID_ENV']` suppresses validation failures. Invalid Envfile syntax always throws before loading values. Envfile redaction applies to dotenvx's own resolved-value debug logs; application output and returned values retain their real values. Active proxy declarations throw before loading values because synchronous `config()` cannot start the proxy; use `dotenvx run -- yourcommand` for those policies.
1589
1593
 
1590
1594
  ```ruby
1591
1595
  file ".env.development" do
@@ -1598,15 +1602,17 @@ end
1598
1602
 
1599
1603
  `spec` infers `redacted: false` for names starting with `PUBLIC`, `VITE`, `NEXT_PUBLIC`, or `NUXT_PUBLIC`, or containing `PUBLIC` anywhere (case-sensitive). This affects visibility only; public names still require encryption unless explicitly exempted. Other names, including those ending in `_PLAIN`, remain redacted.
1600
1604
 
1601
- If an Envspec already exists, `spec` leaves it untouched and prints `○ Envspec already exists [edit or run: spec --overwrite]`. Use `spec --overwrite` to regenerate it from the selected inputs, replacing custom rules, comments, and blocks for files absent from this machine. Interactive overwrite runs show the full file-and-code checklist with the prompt `Recreate Envspec from .env files and code`. Noninteractive runs use `.env.example` and `.env`, or the file selected with `-f`. Input validation finishes before the old Envspec is replaced; cancelled selection leaves it untouched. Symlinked Envspecs cannot be overwritten.
1605
+ `dotenvx spec` always generates `Envfile`, including with `--overwrite` or `--stdout`.
1606
+
1607
+ If an Envfile already exists, `spec` leaves it untouched and prints `○ Envfile already exists [edit or run: spec --overwrite]`. Use `spec --overwrite` to regenerate it from the selected inputs, replacing custom rules, comments, and blocks for files absent from this machine. Interactive overwrite runs show the full file-and-code checklist with the prompt `Recreate Envfile from .env files and code`. Noninteractive runs use `.env.example` and `.env`, or the file selected with `-f`. Input validation finishes before the old Envfile is replaced; cancelled selection leaves it untouched. Symlinked Envfiles cannot be overwritten.
1602
1608
 
1603
- Use `dotenvx spec --stdout` to print the generated Envspec without writing it, or `dotenvx spec --stdout -f .env.production` to select an input file. This works even when an Envspec already exists; `--stdout` leaves it untouched even with `--overwrite`. Prompts and progress stay on stderr so stdout contains only the generated content.
1609
+ Use `dotenvx spec --stdout` to print the generated Envfile without writing it, or `dotenvx spec --stdout -f .env.production` to select an input file. This works even when an Envfile already exists; `--stdout` leaves it untouched even with `--overwrite`. Prompts and progress stay on stderr so stdout contains only the generated content.
1604
1610
 
1605
1611
  Root and file-level `redacted` settings are not supported. Use per-key `redacted: false` to permit output visibility. When selected file policies disagree about a variable, redaction wins. `check` shows individual issues or a compact success summary without displaying values.
1606
1612
 
1607
1613
 
1608
1614
  </details>
1609
- <details><summary>`run with Envspec file rules`</summary><br>
1615
+ <details><summary>`run with Envfile file rules`</summary><br>
1610
1616
 
1611
1617
  Use exact file blocks to override rules for selected files:
1612
1618
 
@@ -1623,14 +1629,14 @@ end
1623
1629
 
1624
1630
  Both `dotenvx run -f .env.production -- node index.js` and `dotenvx check -f .env.production` use the production rules. Block declarations inherit top-level options and override only the options they specify. A block's `encrypted` directive applies to all inherited and newly declared variables; a per-variable `encrypted:` option inside that block overrides it.
1625
1631
 
1626
- Paths in file blocks are relative to the Envspec. They match the selected paths exactly after path normalization (`./.env.production` matches `.env.production`); they are not basename matches or globs. Directory inputs and `DOTENV_FILE` use their resolved file paths.
1632
+ Paths in file blocks are relative to the Envfile. They match the selected paths exactly after path normalization (`./.env.production` matches `.env.production`); they are not basename matches or globs. Directory inputs and `DOTENV_FILE` use their resolved file paths.
1627
1633
 
1628
1634
  When no file block matches, top-level rules apply. When one or more blocks match, each matching block's inherited rules must hold for the final resolved environment. Shell values, fallback files, and `--overload` cannot bypass them. A selected missing file still activates its block. Multiple matching blocks cannot cancel each other's restrictions; conflicting proxy domains are rejected. Blocks cannot be nested, and duplicate declarations within one scope or duplicate file blocks are errors.
1629
1635
 
1630
1636
  </details>
1631
1637
  <details><summary>`check`</summary><br>
1632
1638
 
1633
- Validate the final resolved environment against your Envspec, using the same loader and precedence as `run`:
1639
+ Validate the final resolved environment against your Envfile, using the same loader and precedence as `run`:
1634
1640
 
1635
1641
  ```sh
1636
1642
  $ dotenvx check -f .env.local -f .env
@@ -1640,7 +1646,7 @@ $ dotenvx check -f .env.production
1640
1646
  ☠ TOKEN_SECRET not encrypted (.env.production:4)
1641
1647
  ```
1642
1648
 
1643
- Envspec `file` blocks define policy; they do not select files to load. By default, `check` uses the same `.env` selection as `run`, including configured paths and private-key-based filename inference. Use repeated `-f` flags or `--convention` to select layers. `DOTENV_FILE` and its aliases are also supported.
1649
+ Envfile `file` blocks define policy; they do not select files to load. By default, `check` uses the same `.env` selection as `run`, including configured paths and private-key-based filename inference. Use repeated `-f` flags or `--convention` to select layers. `DOTENV_FILE` and its aliases are also supported.
1644
1650
 
1645
1651
  All selected sources are merged before validation. The first file wins by default, existing shell values take precedence, and `--overload` lets later sources override earlier values. Partial files can satisfy the schema together. Encryption requirements apply to the source of the winning value, not to every overridden assignment on disk. Each selected file block's inherited rules must hold for the final environment, just as with `run`.
1646
1652
 
@@ -1649,9 +1655,9 @@ Missing files explicitly selected with `-f` or `DOTENV_FILE` (and its aliases) f
1649
1655
  On interactive terminals, a single progress line updates with the key being checked. CI and redirected output have no animation. All check output goes to stderr. Success names the loaded sources; validation failures use one diagnostic per issue with the winning source location where available. Shell and inline overrides are identified separately. Failed checks exit with code 1.
1650
1656
 
1651
1657
  </details>
1652
- <details><summary>`protect with an Envspec`</summary><br>
1658
+ <details><summary>`protect with an Envfile`</summary><br>
1653
1659
 
1654
- The Git protection filter reads `Envspec` in the same directory as the file being staged. Encryption is required by default. Keys explicitly marked `encrypted: false` may be committed as plaintext:
1660
+ The Git protection filter reads `Envfile` in the same directory as the file being staged. Encryption is required by default. Keys explicitly marked `encrypted: false` may be committed as plaintext:
1655
1661
 
1656
1662
  ```ruby
1657
1663
  env "BASE_URL", encrypted: false
@@ -1660,11 +1666,11 @@ env "TOKEN_SECRET"
1660
1666
 
1661
1667
  This permits plaintext `BASE_URL` while requiring `TOKEN_SECRET` and undeclared keys to be encrypted. Only keys explicitly marked `encrypted: false` may remain plaintext. `redacted` only controls output visibility.
1662
1668
 
1663
- Without an Envspec, protection keeps its existing rules, including exemptions for `.env.example`, `.env.vault`, and `.env.x`. A `_PLAIN` suffix alone does not permit plaintext through Git protection.
1669
+ Without an Envfile, protection keeps its existing rules, including exemptions for `.env.example`, `.env.vault`, and `.env.x`. A `_PLAIN` suffix alone does not permit plaintext through Git protection.
1664
1670
 
1665
1671
  Protection inspects every assignment in the incoming Git blob, including duplicates. It does not merge files, use shell overrides, or decrypt values. Empty values, public encryption keys, and `op://` / `bw://` references remain allowed. Private-key files (`.env.keys*`) and nonempty plaintext `DOTENV_PRIVATE_KEY` values remain blocked even with `encrypted: false`.
1666
1672
 
1667
- The policy is read from the working-tree Envspec beside the staged file, even if that policy itself is unstaged. Parent directories are not searched. Invalid or unreadable policies block staging with an error. Envspec encryption rules also apply to otherwise exempt files such as `.env.example`.
1673
+ The policy is read from the working-tree Envfile beside the staged file, even if that policy itself is unstaged. Parent directories are not searched. Invalid or unreadable policies block staging with an error. Envfile encryption rules also apply to otherwise exempt files such as `.env.example`.
1668
1674
 
1669
1675
  Accepted blobs pass through byte-for-byte. This integration applies to Git protection, not `protect --docker`.
1670
1676
 
@@ -2272,7 +2278,7 @@ $ dotenvx set HELLO_PLAIN World
2272
2278
  set HELLO_PLAIN (.env)
2273
2279
  ```
2274
2280
 
2275
- Keys ending in `_PLAIN` are not encrypted by `dotenvx set`. `dotenvx encrypt` also skips these keys when there is no Envspec; with an Envspec, its encryption rules take precedence.
2281
+ Keys ending in `_PLAIN` are not encrypted by `dotenvx set`. `dotenvx encrypt` also skips these keys when there is no Envfile; with an Envfile, its encryption rules take precedence.
2276
2282
 
2277
2283
  </details>
2278
2284
  <details><summary>`set KEY value --no-native`</summary><br>
@@ -2331,7 +2337,7 @@ $ dotenvx del HELLO -f .env.production
2331
2337
 
2332
2338
  Encrypt the contents of a `.env` file to an encrypted `.env` file.
2333
2339
 
2334
- When the current directory contains an Envspec, `encrypt` encrypts all keys except those explicitly marked `encrypted: false` in the applicable declarations. Values with effective `encrypted: false` remain unchanged, including any existing ciphertext. Undeclared keys require encryption too; both `run` and `check` validate loaded keys and their shell overrides without checking unrelated host environment variables. `run` warns on validation failures by default and refuses to launch when strictness is enabled; `check` exits with failure. The policy applies even with `--key` or `--stdout`; `--exclude-key` can further narrow the selection. If no values need encryption, no keypair is generated. Invalid Envspecs fail rather than falling back to encrypting everything. The Envspec itself is never modified.
2340
+ When the current directory contains an Envfile, `encrypt` encrypts all keys except those explicitly marked `encrypted: false` in the applicable declarations. Values with effective `encrypted: false` remain unchanged, including any existing ciphertext. Undeclared keys require encryption too; both `run` and `check` validate loaded keys and their shell overrides without checking unrelated host environment variables. `run` warns on validation failures by default and refuses to launch when strictness is enabled; `check` exits with failure. The policy applies even with `--key` or `--stdout`; `--exclude-key` can further narrow the selection. If no values need encryption, no keypair is generated. Invalid Envfiles fail rather than falling back to encrypting everything. The Envfile itself is never modified.
2335
2341
 
2336
2342
  ```sh
2337
2343
  $ echo "HELLO=World" > .env
@@ -3286,7 +3292,7 @@ INVALID_PUBLIC_KEY= # a public key is malformed or otherwise invalid
3286
3292
  MALFORMED_ENCRYPTED_DATA= # the encrypted value is malformed
3287
3293
  MISPAIRED_PRIVATE_KEY= # a private key does not match the existing public key
3288
3294
  MISSING_DIRECTORY= # the requested directory does not exist
3289
- ENVSPEC_REQUIRED= # the required Envspec does not exist
3295
+ ENVSPEC_REQUIRED= # the required Envfile does not exist
3290
3296
  MISSING_ENV_FILE= # a requested environment file does not exist
3291
3297
  MISSING_ENV_FILES= # no .env* files were found
3292
3298
  MISSING_ENV_KEYS_FILE= # the requested .env.keys file does not exist
@@ -3298,8 +3304,8 @@ MISSING_REQUIRED= # validation detail for which required variables are missing;
3298
3304
  MISSING_VALUE= # no value was supplied for a key
3299
3305
  NOT_FOUND= # a private key was not found in the native secret store
3300
3306
  PRECOMMIT_HOOK_MODIFY_FAILED= # dotenvx could not update the pre-commit hook
3301
- INVALID_ENV= # resolved values do not satisfy Envspec rules
3302
- MALFORMED_ENVSPEC= # Envspec syntax or configuration is invalid
3307
+ INVALID_ENV= # resolved values do not satisfy Envfile rules
3308
+ MALFORMED_ENVSPEC= # Envfile syntax or configuration is invalid
3303
3309
  WRONG_PRIVATE_KEY= # the supplied private key cannot decrypt the value
3304
3310
  ```
3305
3311
 
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "2.32.2",
2
+ "version": "2.32.4",
3
3
  "name": "@dotenvx/dotenvx",
4
4
  "description": "a secure dotenv–from the creator of `dotenv`",
5
5
  "author": "@motdotla",
@@ -34,7 +34,7 @@ async function check () {
34
34
  checked.push(...readableFilepaths)
35
35
  if (processedEnvs.some(row => row.type === 'env' && Object.keys(row.parsed || {}).length)) checked.push('--env')
36
36
  if (checked.length === 0 && [...schema.redactionRules.keys()].some(key => processEnv[key] !== undefined)) checked.push('shell environment')
37
- const location = diagnosticLocations(processedEnvs, checked.join(', ') || 'Envspec')
37
+ const location = diagnosticLocations(processedEnvs, checked.join(', ') || 'Envfile')
38
38
  for (const row of processedEnvs) {
39
39
  for (const error of row.errors || []) {
40
40
  if (ignore.includes(error.code)) continue
@@ -17,12 +17,12 @@ module.exports = async function spec () {
17
17
  let spinner
18
18
 
19
19
  try {
20
- const existing = stdout ? undefined : fs.lstatSync('Envspec', { throwIfNoEntry: false })
20
+ const existing = stdout ? undefined : fs.lstatSync('Envfile', { throwIfNoEntry: false })
21
21
  if (existing && !overwrite) {
22
- logger.info('○ Envspec already exists [edit or run: spec --overwrite]')
22
+ logger.info('○ Envfile already exists [edit or run: spec --overwrite]')
23
23
  return
24
24
  }
25
- if (existing && !existing.isFile()) throw new Error('Cannot replace Envspec: expected a regular file')
25
+ if (existing && !existing.isFile()) throw new Error('Cannot replace Envfile: expected a regular file')
26
26
 
27
27
  let envFiles
28
28
  let sourceKeys = []
@@ -33,8 +33,8 @@ module.exports = async function spec () {
33
33
  if (interactive && !envFile) {
34
34
  const candidates = discoverEnvFiles()
35
35
  const selected = await prompts.multiselect({
36
- message: existing ? 'Recreate Envspec from .env files and code' : 'Create Envspec from .env files and code',
37
- submitLabel: existing ? 'Recreate Envspec' : 'Create Envspec',
36
+ message: existing ? 'Recreate Envfile from .env files and code' : 'Create Envfile from .env files and code',
37
+ submitLabel: existing ? 'Recreate Envfile' : 'Create Envfile',
38
38
  choices: [...candidates, { name: 'code ./**/* (env references)', value: '__scan_source' }],
39
39
  initial: [...candidates, '__scan_source']
40
40
  })
@@ -56,9 +56,9 @@ module.exports = async function spec () {
56
56
  return
57
57
  }
58
58
  if (created) {
59
- logger.success(replaced ? '◈ recreated (Envspec)' : '◈ created (Envspec)')
59
+ logger.success(replaced ? '◈ recreated (Envfile)' : '◈ created (Envfile)')
60
60
  logger.help('⮕ next run [dotenvx check]')
61
- } else logger.info('○ Envspec already exists [edit or run: spec --overwrite]')
61
+ } else logger.info('○ Envfile already exists [edit or run: spec --overwrite]')
62
62
  } catch (error) {
63
63
  if (spinner) spinner.stop()
64
64
  catchAndLog(error)
@@ -78,7 +78,7 @@ program.command('run')
78
78
  .option('--ignore <errorCodes...>', 'error code(s) to ignore (example: --ignore=MISSING_ENV_FILE)')
79
79
  .option('--token <token>', 'set Armor ⛨ token')
80
80
  .option('--mask [characters]', 'inject masked values, optionally setting visible characters')
81
- .option('--redact', 'redact injected values except public keys (Envspec rules take precedence)', false)
81
+ .option('--redact', 'redact injected values except public keys (Envfile rules take precedence)', false)
82
82
  .option('--lock-password <password>', 'password to unlock private keys (defaults to DOTENVX_LOCK_PASSWORD)')
83
83
  .option('--no-armor', 'disable Dotenvx Armor features')
84
84
  .option('--no-native', 'disable OS secret store features')
@@ -226,9 +226,9 @@ program.command('ls', { hidden: true })
226
226
 
227
227
  // dotenvx spec
228
228
  program.command('spec', { hidden: true })
229
- .description('create an Envspec')
229
+ .description('create an Envfile')
230
230
  .option('--stdout', 'send to stdout')
231
- .option('--overwrite', 'replace existing Envspec, including custom rules, comments, and missing-file blocks')
231
+ .option('--overwrite', 'replace existing Envfile, including custom rules, comments, and missing-file blocks')
232
232
  .option('-f, --env-file <path>', 'file to read variable names from')
233
233
  .action(function () {
234
234
  return commandAction(require('./actions/init')).apply(this, arguments)
@@ -236,7 +236,7 @@ program.command('spec', { hidden: true })
236
236
 
237
237
  // dotenvx check
238
238
  program.command('check', { hidden: true })
239
- .description('check Envspec rules against .env file(s)')
239
+ .description('check Envfile rules against .env file(s)')
240
240
  .option('-e, --env <strings...>', 'environment variable(s) set as string (example: "HELLO=World")', collectEnvs('env'), [])
241
241
  .option('-f, --env-file <path>', 'path(s) to your env file(s)', collectEnvs('envFile'), [])
242
242
  .option('-fk, --env-keys-file <path>', 'path(s) to your .env.keys file(s) (default: same path as your env file)', collectEnvKeys)
@@ -336,7 +336,7 @@ function hiddenSubcommands (name) {
336
336
  program.command('hidden')
337
337
  .allowExcessArguments(false)
338
338
  .description('hidden features')
339
- .addHelpText('after', () => `\nHidden Commands:\n update update dotenvx\n feedback [message] send feedback to dotenvx\n protect protect secrets and private keys from code commits\n ls [directory] print all .env files in a tree structure\n genexample [directory] generate .env.example\n lock ⊡ lock private keys with a local passphrase\n native ⌥ move private keys in/out of your OS secret store\n 1password □ move private keys in/out of 1Password\n bitwarden □ move private keys in/out of Bitwarden\n armor ⛨ move private keys in/out of Dotenvx Armor [www.dotenvx.com/armor]\n curl ⛨ call authenticated api Dotenvx Armor [www.dotenvx.com/armor]\n\nBeta Commands:\n spec create an Envspec\n check check Envspec rules against .env file(s)\n${hiddenSubcommands('primitives')}\n\nDeprecated Commands:\n gitignore deprecated. use [dotenvx protect]\n precommit [directory] deprecated. use [dotenvx protect]\n prebuild [directory] deprecated. use [dotenvx protect --docker]\n\nRun directly: dotenvx <command>`)
339
+ .addHelpText('after', () => `\nHidden Commands:\n update update dotenvx\n feedback [message] send feedback to dotenvx\n protect protect secrets and private keys from code commits\n ls [directory] print all .env files in a tree structure\n genexample [directory] generate .env.example\n lock ⊡ lock private keys with a local passphrase\n native ⌥ move private keys in/out of your OS secret store\n 1password □ move private keys in/out of 1Password\n bitwarden □ move private keys in/out of Bitwarden\n armor ⛨ move private keys in/out of Dotenvx Armor [www.dotenvx.com/armor]\n curl ⛨ call authenticated api Dotenvx Armor [www.dotenvx.com/armor]\n\nBeta Commands:\n spec create an Envfile\n check check Envfile rules against .env file(s)\n${hiddenSubcommands('primitives')}\n\nDeprecated Commands:\n gitignore deprecated. use [dotenvx protect]\n precommit [directory] deprecated. use [dotenvx protect]\n prebuild [directory] deprecated. use [dotenvx protect --docker]\n\nRun directly: dotenvx <command>`)
340
340
  .action(function () { this.outputHelp() })
341
341
 
342
342
  // dotenvx update
@@ -11,7 +11,7 @@ module.exports = function discoverEnvFiles ({ directory = process.cwd() } = {})
11
11
  function walk (current) {
12
12
  const entries = fs.readdirSync(current, { withFileTypes: true })
13
13
  // Stop at nested packages and initialized projects, including symlinked markers.
14
- if (current !== root && entries.some(entry => entry.name === 'Envspec' || entry.name === 'package.json')) return
14
+ if (current !== root && entries.some(entry => ['Envfile', 'Envspec', 'Dotenvspec', 'package.json'].includes(entry.name))) return
15
15
  for (const entry of entries) {
16
16
  const filename = path.join(current, entry.name)
17
17
  if (entry.isDirectory()) {
@@ -4,7 +4,7 @@ const { ignore } = require('@dotenvx/tooling')
4
4
  const extractEnvKeys = require('./extractEnvKeys')
5
5
 
6
6
  const ignoredDirectories = new Set(['.git', 'node_modules', 'dist', 'build', '.next', 'vendor', '.venv', 'coverage', '__pycache__'])
7
- const projectMarkers = new Set(['package.json', 'Envspec', '.env.schema'])
7
+ const projectMarkers = new Set(['package.json', 'Envfile', 'Envspec', 'Dotenvspec', '.env.schema'])
8
8
  const languages = {
9
9
  js: 'js',
10
10
  mjs: 'js',
@@ -2,7 +2,7 @@ Document
2
2
  = _ entries:((FileBlock / Declaration / Strict) _)* {
3
3
  const items = entries.map(item => item[0]);
4
4
  const settings = items.filter(item => item.strict !== undefined && !item.file);
5
- if (settings.length > 1) error("Duplicate Envspec setting: strict");
5
+ if (settings.length > 1) error("Duplicate Envfile setting: strict");
6
6
  return { ...settings[0], declarations: items.filter(item => item.name), files: items.filter(item => item.file) };
7
7
  }
8
8
 
@@ -10,7 +10,7 @@ FileBlock
10
10
  = "file" [ \t]+ file:Filename [ \t]+ "do" [ \t]* Comment? Newline _ entries:((Declaration / Strict) _)* "end" [ \t]* Comment? (Newline / !.) {
11
11
  const items = entries.map(item => item[0]);
12
12
  const settings = items.filter(item => item.strict !== undefined);
13
- if (settings.length > 1) error("Duplicate Envspec setting: strict");
13
+ if (settings.length > 1) error("Duplicate Envfile setting: strict");
14
14
  return { file, ...settings[0], declarations: items.filter(item => item.name) };
15
15
  }
16
16
 
@@ -26,10 +26,10 @@ Declaration
26
26
  const declaration = { name };
27
27
  const seen = new Set();
28
28
  for (const option of options) {
29
- if (seen.has(option.key)) error(`Duplicate Envspec option: ${option.key}`);
29
+ if (seen.has(option.key)) error(`Duplicate Envfile option: ${option.key}`);
30
30
  if ((option.key === "optional" && seen.has("required")) ||
31
31
  (option.key === "required" && seen.has("optional"))) {
32
- error("Cannot combine required and optional in an Envspec declaration");
32
+ error("Cannot combine required and optional in a Envfile declaration");
33
33
  }
34
34
  seen.add(option.key);
35
35
  if (option.key === "optional") declaration.required = !option.value;
@@ -288,13 +288,13 @@ function peg$parse(input, options) {
288
288
  function peg$f0(entries) {
289
289
  const items = entries.map(item => item[0]);
290
290
  const settings = items.filter(item => item.strict !== undefined && !item.file);
291
- if (settings.length > 1) error("Duplicate Envspec setting: strict");
291
+ if (settings.length > 1) error("Duplicate Envfile setting: strict");
292
292
  return { ...settings[0], declarations: items.filter(item => item.name), files: items.filter(item => item.file) };
293
293
  }
294
294
  function peg$f1(file, entries) {
295
295
  const items = entries.map(item => item[0]);
296
296
  const settings = items.filter(item => item.strict !== undefined);
297
- if (settings.length > 1) error("Duplicate Envspec setting: strict");
297
+ if (settings.length > 1) error("Duplicate Envfile setting: strict");
298
298
  return { file, ...settings[0], declarations: items.filter(item => item.name) };
299
299
  }
300
300
  function peg$f2(value) { return { strict: value }; }
@@ -304,10 +304,10 @@ function peg$parse(input, options) {
304
304
  const declaration = { name };
305
305
  const seen = new Set();
306
306
  for (const option of options) {
307
- if (seen.has(option.key)) error(`Duplicate Envspec option: ${option.key}`);
307
+ if (seen.has(option.key)) error(`Duplicate Envfile option: ${option.key}`);
308
308
  if ((option.key === "optional" && seen.has("required")) ||
309
309
  (option.key === "required" && seen.has("optional"))) {
310
- error("Cannot combine required and optional in an Envspec declaration");
310
+ error("Cannot combine required and optional in an Envfile declaration");
311
311
  }
312
312
  seen.add(option.key);
313
313
  if (option.key === "optional") declaration.required = !option.value;
@@ -6,6 +6,7 @@ const Errors = require('../../helpers/errors')
6
6
  const isValidUrl = require('../../helpers/isValidUrl')
7
7
  const isValidEmail = require('../../helpers/isValidEmail')
8
8
  const formatEnvspecSyntaxError = require('./formatEnvspecSyntaxError')
9
+ const resolveEnvspecPath = require('./resolveEnvspecPath')
9
10
 
10
11
  function compileDeclarations (declarations) {
11
12
  const proxyRules = new Map()
@@ -21,7 +22,7 @@ function compileDeclarations (declarations) {
21
22
  for (const input of declarations) {
22
23
  const declaration = { ...input }
23
24
  if (input.type) declaredTypes.set(input.name, input.type)
24
- if (names.has(declaration.name)) throw new Errors({ message: `Duplicate Envspec declaration: ${declaration.name}` }).malformedEnvspec()
25
+ if (names.has(declaration.name)) throw new Errors({ message: `Duplicate Envfile declaration: ${declaration.name}` }).malformedEnvspec()
25
26
  names.add(declaration.name)
26
27
  redactionRules.set(declaration.name, declaration.redacted !== false)
27
28
  encryptionRules.set(declaration.name, declaration.encrypted !== false)
@@ -35,35 +36,35 @@ function compileDeclarations (declarations) {
35
36
  if (declaration.type) types.set(declaration.name, declaration.type)
36
37
  if (declaration.min !== undefined || declaration.max !== undefined) {
37
38
  if (declaration.type !== 'integer') {
38
- throw new Errors({ message: `Invalid Envspec range for ${declaration.name}: min and max require type: "integer" or "port".` }).malformedEnvspec()
39
+ throw new Errors({ message: `Invalid Envfile range for ${declaration.name}: min and max require type: "integer" or "port".` }).malformedEnvspec()
39
40
  }
40
41
  if (declaration.min !== undefined && declaration.max !== undefined && BigInt(declaration.min) > BigInt(declaration.max)) {
41
- throw new Errors({ message: `Invalid Envspec range for ${declaration.name}: min must be less than or equal to max.` }).malformedEnvspec()
42
+ throw new Errors({ message: `Invalid Envfile range for ${declaration.name}: min must be less than or equal to max.` }).malformedEnvspec()
42
43
  }
43
44
  ranges.set(declaration.name, { min: declaration.min, max: declaration.max })
44
45
  }
45
46
  if (declaration.enum) {
46
47
  if (declaration.type === 'integer' && declaration.enum.some(value => !/^[+-]?\d+$/.test(value.trim()))) {
47
- throw new Errors({ message: `Invalid Envspec enum for ${declaration.name}: expected integer choices.` }).malformedEnvspec()
48
+ throw new Errors({ message: `Invalid Envfile enum for ${declaration.name}: expected integer choices.` }).malformedEnvspec()
48
49
  }
49
50
  if (declaration.type === 'boolean' && declaration.enum.some(value => !['true', 'false', '1', '0'].includes(value))) {
50
- throw new Errors({ message: `Invalid Envspec enum for ${declaration.name}: expected true, false, 1, or 0 choices.` }).malformedEnvspec()
51
+ throw new Errors({ message: `Invalid Envfile enum for ${declaration.name}: expected true, false, 1, or 0 choices.` }).malformedEnvspec()
51
52
  }
52
53
  if (declaration.type === 'url' && declaration.enum.some(value => !isValidUrl(value))) {
53
- throw new Errors({ message: `Invalid Envspec enum for ${declaration.name}: expected URL choices.` }).malformedEnvspec()
54
+ throw new Errors({ message: `Invalid Envfile enum for ${declaration.name}: expected URL choices.` }).malformedEnvspec()
54
55
  }
55
56
  if (declaration.type === 'email' && declaration.enum.some(value => !isValidEmail(value))) {
56
- throw new Errors({ message: `Invalid Envspec enum for ${declaration.name}: expected email choices.` }).malformedEnvspec()
57
+ throw new Errors({ message: `Invalid Envfile enum for ${declaration.name}: expected email choices.` }).malformedEnvspec()
57
58
  }
58
59
  if (declaration.type === 'ip' && declaration.enum.some(value => isIP(value) === 0)) {
59
- throw new Errors({ message: `Invalid Envspec enum for ${declaration.name}: expected IPv4 or IPv6 choices.` }).malformedEnvspec()
60
+ throw new Errors({ message: `Invalid Envfile enum for ${declaration.name}: expected IPv4 or IPv6 choices.` }).malformedEnvspec()
60
61
  }
61
62
  enums.set(declaration.name, declaration.enum)
62
63
  }
63
64
  if (declaration.proxy) {
64
65
  const host = declaration.proxy.domain.toLowerCase()
65
66
  if (host.length > 253 || isIP(host) || !/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(host)) {
66
- throw new Errors({ message: `Invalid Envspec proxy host for ${declaration.name}: expected a DNS hostname without a scheme, port, path or wildcard.` }).malformedEnvspec()
67
+ throw new Errors({ message: `Invalid Envfile proxy host for ${declaration.name}: expected a DNS hostname without a scheme, port, path or wildcard.` }).malformedEnvspec()
67
68
  }
68
69
  proxyRules.set(declaration.name, host)
69
70
  }
@@ -71,12 +72,16 @@ function compileDeclarations (declarations) {
71
72
  return { exists: true, proxyRules, requiredKeys, types, declaredTypes, enums, ranges, encryptedKeys, redactionRules, encryptionRules }
72
73
  }
73
74
 
74
- module.exports = function readEnvspec (filepath = path.resolve('Envspec'), envFiles = ['.env']) {
75
+ module.exports = function readEnvspec (filepath, envFiles = ['.env']) {
76
+ if (filepath === undefined) filepath = resolveEnvspecPath()
75
77
  let src
76
78
  try {
77
79
  src = fs.readFileSync(filepath, 'utf8')
78
80
  } catch (error) {
79
- if (error.code === 'ENOENT') return { ...compileDeclarations([]), exists: false }
81
+ if (error.code === 'ENOENT') {
82
+ if (fs.lstatSync(filepath, { throwIfNoEntry: false })) throw new Error(`Cannot read ${path.basename(filepath)}: ${filepath}`)
83
+ return { ...compileDeclarations([]), exists: false }
84
+ }
80
85
  throw error
81
86
  }
82
87
 
@@ -99,12 +104,12 @@ module.exports = function readEnvspec (filepath = path.resolve('Envspec'), envFi
99
104
  throw new Errors({ message: `File blocks require an exact filename: ${block.file}` }).malformedEnvspec()
100
105
  }
101
106
  const file = path.resolve(path.dirname(filepath), block.file)
102
- if (seen.has(file)) throw new Errors({ message: `Duplicate Envspec file block: ${block.file}` }).malformedEnvspec()
107
+ if (seen.has(file)) throw new Errors({ message: `Duplicate Envfile file block: ${block.file}` }).malformedEnvspec()
103
108
  seen.add(file)
104
109
  const merged = new Map(base.map(item => [item.name, { ...item }]))
105
110
  const names = new Set()
106
111
  for (const item of block.declarations) {
107
- if (names.has(item.name)) throw new Errors({ message: `Duplicate Envspec declaration in ${block.file}: ${item.name}` }).malformedEnvspec()
112
+ if (names.has(item.name)) throw new Errors({ message: `Duplicate Envfile declaration in ${block.file}: ${item.name}` }).malformedEnvspec()
108
113
  names.add(item.name)
109
114
  merged.set(item.name, {
110
115
  ...defaults,
@@ -124,7 +129,7 @@ module.exports = function readEnvspec (filepath = path.resolve('Envspec'), envFi
124
129
  for (const schema of active) {
125
130
  for (const [key, host] of schema.proxyRules) {
126
131
  if (proxyRules.has(key) && proxyRules.get(key) !== host) {
127
- throw new Errors({ message: `Conflicting Envspec proxy domains for ${key} in selected file blocks` }).malformedEnvspec()
132
+ throw new Errors({ message: `Conflicting Envfile proxy domains for ${key} in selected file blocks` }).malformedEnvspec()
128
133
  }
129
134
  proxyRules.set(key, host)
130
135
  }
@@ -0,0 +1,11 @@
1
+ const fs = require('node:fs')
2
+ const path = require('node:path')
3
+
4
+ // A present but broken policy must fail, never fall back to a weaker policy.
5
+ module.exports = function resolveEnvspecPath (directory = process.cwd()) {
6
+ for (const filename of ['Envfile', 'Envspec', 'Dotenvspec']) {
7
+ const candidate = path.resolve(directory, filename)
8
+ if (fs.lstatSync(candidate, { throwIfNoEntry: false })) return candidate
9
+ }
10
+ return path.resolve(directory, 'Envfile')
11
+ }
@@ -10,7 +10,7 @@ function declaration (item) {
10
10
  function renderFile (file) {
11
11
  const quote = file.filename.includes('"') ? "'" : '"'
12
12
  if (file.filename.includes(quote) || /[\r\n\0*?[\]{}]/.test(file.filename)) {
13
- throw new Error(`Unsupported Envspec filename: ${file.filename}`)
13
+ throw new Error(`Unsupported Envfile filename: ${file.filename}`)
14
14
  }
15
15
  const lines = [`file ${quote}${file.filename}${quote} do`]
16
16
  lines.push(...file.declarations.map(item => ` ${declaration(item)}`), 'end')
@@ -26,5 +26,5 @@ module.exports = function renderEnvspec (document) {
26
26
  if (document.codeDeclarations.length) {
27
27
  sections.push('# additionally found in code\n' + document.codeDeclarations.map(declaration).join('\n'))
28
28
  }
29
- return '# Envspec (safe to commit)\n# ------------------------\n\n' + sections.join('\n\n') + (sections.length ? '\n' : '')
29
+ return '# Envfile (safe to commit)\n# ------------------------\n\n' + sections.join('\n\n') + (sections.length ? '\n' : '')
30
30
  }
@@ -2,13 +2,14 @@ const fs = require('node:fs')
2
2
  const path = require('node:path')
3
3
  const { execFileSync } = require('node:child_process')
4
4
  const readEnvspec = require('../parsing/readEnvspec')
5
+ const resolveEnvspecPath = require('../parsing/resolveEnvspecPath')
5
6
  const plaintextKeys = require('../../helpers/plaintextKeys')
6
7
 
7
8
  function readPolicy (policyPath, file) {
8
9
  const schema = readEnvspec(policyPath, [file])
9
10
  if (!schema.exists) {
10
11
  // A dangling policy symlink is a broken policy, not an absent policy.
11
- if (fs.lstatSync(policyPath, { throwIfNoEntry: false })) throw new Error(`Cannot read Envspec: ${policyPath}`)
12
+ if (fs.lstatSync(policyPath, { throwIfNoEntry: false })) throw new Error(`Cannot read Envfile: ${policyPath}`)
12
13
  return null
13
14
  }
14
15
  return schema
@@ -18,7 +19,7 @@ function readPolicy (policyPath, file) {
18
19
  module.exports = function protectEnvspec (filepath, content) {
19
20
  const file = path.resolve(filepath)
20
21
  const directory = path.dirname(file)
21
- let schema = readPolicy(path.join(directory, 'Envspec'), file)
22
+ let schema = readPolicy(resolveEnvspecPath(directory), file)
22
23
  if (!schema) {
23
24
  let root
24
25
  try {
@@ -31,7 +32,7 @@ module.exports = function protectEnvspec (filepath, content) {
31
32
  // Outside a Git working tree, only an adjacent policy can apply.
32
33
  return null
33
34
  }
34
- if (path.resolve(root) !== directory) schema = readPolicy(path.join(root, 'Envspec'), file)
35
+ if (path.resolve(root) !== directory) schema = readPolicy(resolveEnvspecPath(root), file)
35
36
  }
36
37
  if (!schema) return null
37
38
 
@@ -234,7 +234,7 @@ class Errors {
234
234
  }
235
235
 
236
236
  envspecRequired () {
237
- const e = new Error('[ENVSPEC_REQUIRED] check requires an Envspec')
237
+ const e = new Error('[ENVSPEC_REQUIRED] check requires an Envfile')
238
238
  e.code = 'ENVSPEC_REQUIRED'
239
239
  e.help = 'fix: run [dotenvx spec]'
240
240
  e.messageWithHelp = `${e.message}. ${e.help}`
package/src/lib/main.d.ts CHANGED
@@ -110,6 +110,7 @@ export interface DotenvConfigOptions {
110
110
 
111
111
  /**
112
112
  * Throw immediately if an error is encountered - like a missing .env file.
113
+ * Includes Envfile validation failures. Envfile strict settings also enforce throwing.
113
114
  * @default false
114
115
  * @example require('@dotenvx/dotenvx').config({ strict: true })
115
116
  */
@@ -255,6 +256,10 @@ export interface DotenvPopulateInput {
255
256
 
256
257
  /**
257
258
  * Loads `.env` file contents into process.env by default.
259
+ * Reads Envfile from the current directory and validates the final resolved environment.
260
+ * Falls back to Envspec, then Dotenvspec, when earlier filenames are absent.
261
+ * Validation failures warn and return an error, or throw when strictness is enabled.
262
+ * Invalid Envfile syntax and active proxy rules always throw; use run for proxy support.
258
263
  *
259
264
  * @see https://dotenvx.com/docs
260
265
  *
package/src/lib/main.js CHANGED
@@ -30,6 +30,10 @@ const normalizeDotenvConfigIgnore = require('./helpers/normalizeDotenvConfigIgno
30
30
  const normalizeDotenvConfigPath = require('./helpers/normalizeDotenvConfigPath')
31
31
  const mask = require('./helpers/mask')
32
32
  const maskProcessedEnvs = require('./helpers/maskProcessedEnvs')
33
+ const readEnvspec = require('./envspec/parsing/readEnvspec')
34
+ const validateEnvspec = require('./envspec/validation/validateEnvspec')
35
+ const redactedValues = require('./helpers/redactedValues')
36
+ const { redactOutput } = require('./helpers/redactOutput')
33
37
 
34
38
  function uniqueInjectedKeys (processedEnvs) {
35
39
  const result = new Set()
@@ -75,11 +79,18 @@ const config = function (options = {}, events) {
75
79
  const noArmor = resolveNoArmor(options)
76
80
  const noNative = resolveNoNative(options)
77
81
 
82
+ let fatal = false
83
+ let sensitiveValues = []
78
84
  try {
79
85
  let envs = normalizeDotenvConfigPath(buildConfigEnvs(options))
80
86
  if (!options.envs) {
81
87
  envs = determine(envs, processEnv)
82
88
  }
89
+ const schema = readEnvspec(undefined, envs.filter(env => env.type === 'envFile').map(env => env.value))
90
+ if (schema.proxyRules.size > 0) {
91
+ fatal = true
92
+ throw new Error('Envfile proxy is not supported by synchronous config(). Use dotenvx run -- yourcommand.')
93
+ }
83
94
  const {
84
95
  processedEnvs,
85
96
  readableFilepaths
@@ -97,6 +108,9 @@ const config = function (options = {}, events) {
97
108
  token: options.token
98
109
  })
99
110
 
111
+ const validationError = validateEnvspec(schema, processEnv, processedEnvs)
112
+ sensitiveValues = redactedValues(processedEnvs, schema, processEnv)
113
+
100
114
  if (options.mask !== undefined) {
101
115
  const showChar = options.mask === true ? 6 : options.mask
102
116
  maskProcessedEnvs(processedEnvs, processEnv, showChar)
@@ -116,7 +130,13 @@ const config = function (options = {}, events) {
116
130
  continue // ignore error
117
131
  }
118
132
 
119
- if (strict) throw error // throw if strict and not ignored
133
+ const policyStrict = processedEnv.type === 'envFile'
134
+ ? (schema.strictByFile?.get(path.resolve(processedEnv.filepath)) ?? schema.strict)
135
+ : schema.strict
136
+ if (strict || policyStrict) {
137
+ fatal = true
138
+ throw error
139
+ }
120
140
 
121
141
  lastError = error // surface later in { error }
122
142
 
@@ -133,18 +153,30 @@ const config = function (options = {}, events) {
133
153
  Object.assign(parsedAll, processedEnv.existed || {}) // existed 'wins'
134
154
 
135
155
  // debug parsed
136
- logger.debug(processedEnv.parsed)
156
+ logger.debug(redactOutput(processedEnv.parsed, sensitiveValues))
137
157
 
138
158
  // verbose/debug injected key/value
139
159
  for (const [key, value] of Object.entries(processedEnv.injected || {})) {
140
160
  logger.verbose(`${key} set`)
141
- logger.debug(`${key} set to ${value}`)
161
+ logger.debug(redactOutput(`${key} set to ${value}`, sensitiveValues))
142
162
  }
143
163
 
144
164
  // verbose/debug existed key/value
145
165
  for (const [key, value] of Object.entries(processedEnv.existed || {})) {
146
166
  logger.verbose(`${key} pre-exists (protip: use --overload to override)`)
147
- logger.debug(`${key} pre-exists as ${value} (protip: use --overload to override)`)
167
+ logger.debug(redactOutput(`${key} pre-exists as ${value} (protip: use --overload to override)`, sensitiveValues))
168
+ }
169
+ }
170
+
171
+ if (validationError) {
172
+ if (ignore.includes(validationError.code)) {
173
+ logger.verbose(`ignored: ${validationError.message}`)
174
+ } else if (strict || validationError.diagnostics?.some(diagnostic => diagnostic.strict)) {
175
+ fatal = true
176
+ throw validationError
177
+ } else {
178
+ logger.warn(validationError.messageWithHelp || validationError.message)
179
+ lastError = validationError
148
180
  }
149
181
  }
150
182
 
@@ -163,9 +195,9 @@ const config = function (options = {}, events) {
163
195
  }
164
196
  } catch (error) {
165
197
  if (events) events.fail(error)
166
- if (strict) throw error // throw immediately if strict
198
+ if (strict || fatal || error.code === 'MALFORMED_ENVSPEC') throw error
167
199
 
168
- logger.error(error.messageWithHelp || error.message)
200
+ logger.error(redactOutput(error.messageWithHelp || error.message, sensitiveValues))
169
201
 
170
202
  return { parsed: {}, error }
171
203
  }
@@ -15,10 +15,10 @@ function declaration (name) {
15
15
  }
16
16
 
17
17
  module.exports = function init ({ directory = process.cwd(), envFile, envFiles, sourceKeys = [], overwrite = false, stdout = false, onFile = () => {} } = {}) {
18
- const target = path.resolve(directory, 'Envspec')
18
+ const target = path.resolve(directory, 'Envfile')
19
19
  const existing = stdout ? undefined : fs.lstatSync(target, { throwIfNoEntry: false })
20
20
  if (existing && !overwrite) return { created: false }
21
- if (existing && !existing.isFile()) throw new Error(`Cannot replace Envspec: expected a regular file (${target})`)
21
+ if (existing && !existing.isFile()) throw new Error(`Cannot replace Envfile: expected a regular file (${target})`)
22
22
  const seen = new Set()
23
23
 
24
24
  const sources = []
@@ -61,7 +61,7 @@ module.exports = function init ({ directory = process.cwd(), envFile, envFiles,
61
61
  const addedFromSource = names.size - inputCount
62
62
  const keys = [...names]
63
63
  const invalid = keys.filter(key => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
64
- if (invalid.length) throw new Error(`Unsupported Envspec variable names: ${invalid.join(', ')}`)
64
+ if (invalid.length) throw new Error(`Unsupported Envfile variable names: ${invalid.join(', ')}`)
65
65
 
66
66
  const document = normalizeEnvspec({ files, codeDeclarations })
67
67
  const content = renderEnvspec(document)
@@ -26,7 +26,7 @@ module.exports = async function validate ({ envs = [], options = {}, processEnv
26
26
  const session = new Session()
27
27
  const proxyToken = options.token || processEnv.DOTENVX_TOKEN
28
28
  const noArmor = options.armor === false || (!proxyToken && (await session.noArmor()))
29
- if (schema.proxyRules.size > 0 && noArmor) throw new Error('Envspec proxy requires Armor. Enable Armor and authenticate before running.')
29
+ if (schema.proxyRules.size > 0 && noArmor) throw new Error('Envfile proxy requires Armor. Enable Armor and authenticate before running.')
30
30
  const proxyCredentials = noArmor ? undefined : []
31
31
  const { processedEnvs, readableFilepaths } = await envsResolver({
32
32
  envs,
@@ -48,7 +48,7 @@ module.exports = async function validate ({ envs = [], options = {}, processEnv
48
48
  let proxyError
49
49
  for (const name of schema.proxyRules.keys()) {
50
50
  if (processEnv[name] !== undefined && !(proxyCredentials || []).some(credential => credential.name === name && credential.placeholder === processEnv[name])) {
51
- proxyError = new Error(`Envspec proxy requires an encrypted ${name} loaded from an env file. Remove plaintext or shell overrides, or use --overload.`)
51
+ proxyError = new Error(`Envfile proxy requires an encrypted ${name} loaded from an env file. Remove plaintext or shell overrides, or use --overload.`)
52
52
  break
53
53
  }
54
54
  }
@@ -1,6 +1,5 @@
1
1
  const fsx = require('./../helpers/fsx')
2
2
  const path = require('path')
3
- const fs = require('node:fs')
4
3
  const { encrypted, encrypt, scan, upsert, publickeys, keypair } = require('@dotenvx/primitives')
5
4
 
6
5
  const TYPE_ENV_FILE = 'envFile'
@@ -53,11 +52,7 @@ async function encryptTransform (options = {}) {
53
52
  const row = { keys: [], type: TYPE_ENV_FILE, filepath, envFilepath, changed: false }
54
53
 
55
54
  try {
56
- const policyPath = path.resolve('Envspec')
57
- const schema = readEnvspec(policyPath, [filepath])
58
- if (!schema.exists && fs.lstatSync(policyPath, { throwIfNoEntry: false })) {
59
- throw new Error(`Cannot read Envspec: ${policyPath}`)
60
- }
55
+ const schema = readEnvspec(undefined, [filepath])
61
56
  const fileExists = await fsx.exists(filepath)
62
57
  if (!fileExists && !noCreate) {
63
58
  row.envSrc = SAMPLE_ENV_KIT