dotenv-key-diff 0.0.0-stage → 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ali Dakoumi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,70 @@
1
- # Temporary Holding Version
1
+ # dotenv-key-diff
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Compare the variable names in `.env.example` with `.env` to catch missing or stale configuration keys. Values are never displayed.
4
+
5
+ ## Use it from the command line
6
+
7
+ ```sh
8
+ npx dotenv-key-diff
9
+ ```
10
+
11
+ By default, it reads `.env.example` and `.env` from the current directory. You can choose other files and produce JSON for scripts or CI:
12
+
13
+ ```sh
14
+ npx dotenv-key-diff --example .env.example --env .env.local
15
+ npx dotenv-key-diff --json
16
+ ```
17
+
18
+ Exit codes: `0` when keys match, `1` when keys are missing or extra, and `2` when an option or file is invalid. The tool compares key names only; it does not validate values or load them into your process.
19
+
20
+ ## Rebuild an example file
21
+
22
+ Generate an example from your local environment file, with every value blank:
23
+
24
+ ```sh
25
+ npx dotenv-key-diff --rebuild
26
+ npx dotenv-key-diff --rebuild --env .env.local --example .env.example
27
+ ```
28
+
29
+ The command creates the example only if it does not already exist. To replace an existing example, first back it up, then use `--rebuild --force`. Rebuilding replaces the entire file: existing comments, example values, and keys not in the source are removed. It refuses to overwrite the input file or a symbolic-link destination, and refuses an input with no valid keys. It never copies values or comments from the input. Key names themselves may reveal sensitive information, so review the generated file before committing it.
30
+
31
+ `--json` applies only to comparison; it cannot be combined with `--rebuild`. Rebuild exits with `0` on success or `2` on invalid arguments or file errors.
32
+
33
+ ## Use it as a library
34
+
35
+ ```js
36
+ import { compareEnv, parseEnvKeys, rebuildEnvExample } from "dotenv-key-diff"
37
+
38
+ const result = compareEnv(
39
+ "DATABASE_URL=\nPUBLIC_API_URL=\n",
40
+ "DATABASE_URL=postgres://...\n",
41
+ )
42
+
43
+ console.log(result.missing) // ["PUBLIC_API_URL"]
44
+ ```
45
+
46
+ `compareEnv(exampleSource, envSource)` returns `missing`, `extra`, and `shared` key arrays. `parseEnvKeys(source)` returns unique valid environment variable names in the order they first appear. Blank lines, comments, and malformed assignments are ignored; `export KEY=value` and multiline quoted values are supported. `rebuildEnvExample(source)` returns a string of unique `KEY=` lines, or an empty string when there are no keys. It does not write files.
47
+
48
+ ## Development
49
+
50
+ Requires Node.js 20 or newer. There are no runtime or development dependencies.
51
+
52
+ ```sh
53
+ npm run check
54
+ ```
55
+
56
+ This runs the unit suite, checks JavaScript syntax, and verifies that the npm package tarball contains the expected files. There are no runtime or development dependencies.
57
+
58
+ ## Interactive playground
59
+
60
+ Run the browser-only comparison playground with:
61
+
62
+ ```sh
63
+ npm run preview
64
+ ```
65
+
66
+ Open `http://localhost:4173`. The page imports the package source directly, compares only key names, and keeps all input in browser memory. The preview server only serves the playground page and library module; it does not expose the rest of the repository. The playground is included in the GitHub repository, not in the published npm package.
67
+
68
+ ## License
69
+
70
+ MIT
@@ -0,0 +1,157 @@
1
+ #!/usr/bin/env node
2
+ import { randomUUID } from "node:crypto"
3
+ import { lstat, readFile, rename, stat, unlink, writeFile } from "node:fs/promises"
4
+ import { basename, dirname, join, resolve } from "node:path"
5
+ import { compareEnv, rebuildEnvExample } from "../src/index.js"
6
+
7
+ const usage = `Usage: dotenv-key-diff [options]
8
+
9
+ Compare the keys in .env.example and .env without printing their values.
10
+
11
+ Options:
12
+ --example <path> Template file (default: .env.example)
13
+ --env <path> Local environment file (default: .env)
14
+ --json Print a machine-readable JSON report
15
+ --rebuild Create an example file with blank values from the env file
16
+ --force Replace an existing example file (only with --rebuild)
17
+ --help Show this help
18
+
19
+ Exit codes:
20
+ 0 Keys match, or example rebuilt
21
+ 1 Missing or extra keys found
22
+ 2 Invalid arguments or file operation failed`
23
+
24
+ function parseArgs(args) {
25
+ const options = { example: ".env.example", env: ".env", json: false, rebuild: false, force: false, help: false }
26
+
27
+ for (let index = 0; index < args.length; index += 1) {
28
+ const arg = args[index]
29
+
30
+ if (arg === "--example" || arg === "--env") {
31
+ const value = args[index + 1]
32
+ if (!value || value.startsWith("--")) {
33
+ throw new Error(`Expected a file path after ${arg}`)
34
+ }
35
+ options[arg === "--example" ? "example" : "env"] = value
36
+ index += 1
37
+ } else if (arg === "--json") {
38
+ options.json = true
39
+ } else if (arg === "--rebuild") {
40
+ options.rebuild = true
41
+ } else if (arg === "--force") {
42
+ options.force = true
43
+ } else if (arg === "--help" || arg === "-h") {
44
+ options.help = true
45
+ } else {
46
+ throw new Error(`Unknown option: ${arg}`)
47
+ }
48
+ }
49
+
50
+ if (options.force && !options.rebuild) throw new Error("--force requires --rebuild")
51
+ if (options.rebuild && options.json) throw new Error("--json cannot be combined with --rebuild")
52
+
53
+ return options
54
+ }
55
+
56
+ async function rebuild(options) {
57
+ const source = await readFile(options.env, "utf8")
58
+ const example = rebuildEnvExample(source)
59
+ if (!example) throw new Error("No valid keys found in the environment file; nothing was written")
60
+ if (resolve(options.env) === resolve(options.example)) {
61
+ throw new Error("The input and example paths must be different")
62
+ }
63
+
64
+ if (!options.force) {
65
+ try {
66
+ await writeFile(options.example, example, { flag: "wx", mode: 0o600 })
67
+ } catch (error) {
68
+ if (error.code === "EEXIST") throw new Error("Example already exists; back it up and use --force to replace it")
69
+ throw error
70
+ }
71
+ } else {
72
+ const sourceStats = await stat(options.env)
73
+ try {
74
+ const destination = await lstat(options.example)
75
+ if (destination.isSymbolicLink()) throw new Error("Refusing to replace a symbolic-link destination")
76
+ if (!destination.isFile()) throw new Error("Example destination must be a regular file")
77
+ if (sourceStats.dev === destination.dev && sourceStats.ino === destination.ino) {
78
+ throw new Error("The input and example paths refer to the same file")
79
+ }
80
+ } catch (error) {
81
+ if (error.code !== "ENOENT") throw error
82
+ }
83
+
84
+ const temporary = join(dirname(resolve(options.example)), `.${basename(options.example)}.${randomUUID()}.tmp`)
85
+ try {
86
+ await writeFile(temporary, example, { flag: "wx", mode: 0o600 })
87
+ await rename(temporary, options.example)
88
+ } finally {
89
+ await unlink(temporary).catch((error) => {
90
+ if (error.code !== "ENOENT") throw error
91
+ })
92
+ }
93
+ }
94
+ process.stdout.write(`Rebuilt ${options.example} with blank values.\n`)
95
+ }
96
+
97
+ async function main(args) {
98
+ let options
99
+
100
+ try {
101
+ options = parseArgs(args)
102
+ } catch (error) {
103
+ process.stderr.write(`dotenv-key-diff: ${error.message}\n\n${usage}\n`)
104
+ return 2
105
+ }
106
+
107
+ if (options.help) {
108
+ process.stdout.write(`${usage}\n`)
109
+ return 0
110
+ }
111
+
112
+ if (options.rebuild) {
113
+ try {
114
+ await rebuild(options)
115
+ return 0
116
+ } catch (error) {
117
+ process.stderr.write(`dotenv-key-diff: ${error.message}\n`)
118
+ return 2
119
+ }
120
+ }
121
+
122
+ let exampleSource
123
+ let envSource
124
+
125
+ try {
126
+ ;[exampleSource, envSource] = await Promise.all([
127
+ readFile(options.example, "utf8"),
128
+ readFile(options.env, "utf8"),
129
+ ])
130
+ } catch (error) {
131
+ process.stderr.write(`dotenv-key-diff: ${error.message}\n`)
132
+ return 2
133
+ }
134
+
135
+ const { missing, extra, shared } = compareEnv(exampleSource, envSource)
136
+ const matches = missing.length === 0 && extra.length === 0
137
+
138
+ if (options.json) {
139
+ process.stdout.write(
140
+ `${JSON.stringify({ example: options.example, env: options.env, matches, missing, extra, shared }, null, 2)}\n`,
141
+ )
142
+ } else if (matches) {
143
+ process.stdout.write("Environment keys match.\n")
144
+ } else {
145
+ if (missing.length) {
146
+ process.stdout.write(`Missing from ${options.env}: ${missing.join(", ")}\n`)
147
+ }
148
+ if (extra.length) {
149
+ process.stdout.write(`Not in ${options.example}: ${extra.join(", ")}\n`)
150
+ }
151
+ process.stdout.write(`${shared.length} shared key${shared.length === 1 ? "" : "s"}.\n`)
152
+ }
153
+
154
+ return matches ? 0 : 1
155
+ }
156
+
157
+ process.exitCode = await main(process.argv.slice(2))
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
2
  "name": "dotenv-key-diff",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Compare and rebuild .env.example keys without exposing values",
5
+ "type": "module",
6
+ "engines": {
7
+ "node": ">=20"
8
+ },
9
+ "types": "./src/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./src/index.d.ts",
13
+ "import": "./src/index.js"
14
+ }
15
+ },
16
+ "bin": {
17
+ "dotenv-key-diff": "./bin/dotenv-diff.js"
18
+ },
19
+ "files": [
20
+ "bin/",
21
+ "src/"
22
+ ],
23
+ "scripts": {
24
+ "test": "node --test",
25
+ "check": "npm test && node --check src/index.js && node --check bin/dotenv-diff.js && node --check scripts/preview-server.js && npm pack --dry-run",
26
+ "preview": "node scripts/preview-server.js"
27
+ },
28
+ "license": "MIT"
29
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ export type EnvComparison = {
2
+ missing: string[]
3
+ extra: string[]
4
+ shared: string[]
5
+ }
6
+
7
+ export function parseEnvKeys(source: string): string[]
8
+
9
+ export function rebuildEnvExample(envSource: string): string
10
+
11
+ export function compareEnv(exampleSource: string, envSource: string): EnvComparison
package/src/index.js ADDED
@@ -0,0 +1,66 @@
1
+ const ENV_KEY_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/
2
+
3
+ export function parseEnvKeys(source) {
4
+ if (typeof source !== "string") {
5
+ throw new TypeError("Expected environment file contents to be a string")
6
+ }
7
+
8
+ const keys = new Set()
9
+ const normalizedSource = source.replace(/^\uFEFF/, "")
10
+
11
+ let quote = null
12
+ let escaped = false
13
+
14
+ for (const rawLine of normalizedSource.split(/\r?\n/)) {
15
+ let value = rawLine
16
+
17
+ if (!quote) {
18
+ let line = rawLine.trim()
19
+ if (!line || line.startsWith("#")) continue
20
+ line = line.replace(/^export\s+/, "")
21
+
22
+ const equalsIndex = line.indexOf("=")
23
+ if (equalsIndex === -1) continue
24
+
25
+ const key = line.slice(0, equalsIndex).trim()
26
+ if (!ENV_KEY_PATTERN.test(key)) continue
27
+ keys.add(key)
28
+ value = line.slice(equalsIndex + 1).trimStart()
29
+ if (value[0] !== '"' && value[0] !== "'") continue
30
+ quote = value[0]
31
+ value = value.slice(1)
32
+ }
33
+
34
+ for (const character of value) {
35
+ if (escaped) {
36
+ escaped = false
37
+ } else if (character === "\\" && quote === '"') {
38
+ escaped = true
39
+ } else if (character === quote) {
40
+ quote = null
41
+ break
42
+ }
43
+ }
44
+ escaped = false
45
+ }
46
+
47
+ return [...keys]
48
+ }
49
+
50
+ export function rebuildEnvExample(envSource) {
51
+ const keys = parseEnvKeys(envSource)
52
+ return keys.length ? `${keys.map((key) => `${key}=`).join("\n")}\n` : ""
53
+ }
54
+
55
+ export function compareEnv(exampleSource, envSource) {
56
+ const expectedKeys = parseEnvKeys(exampleSource)
57
+ const actualKeys = parseEnvKeys(envSource)
58
+ const actualSet = new Set(actualKeys)
59
+ const expectedSet = new Set(expectedKeys)
60
+
61
+ return {
62
+ missing: expectedKeys.filter((key) => !actualSet.has(key)),
63
+ extra: actualKeys.filter((key) => !expectedSet.has(key)),
64
+ shared: expectedKeys.filter((key) => actualSet.has(key)),
65
+ }
66
+ }