Repository navigation
Description
What happens
parseAndApply in packages/cli/src/lib/dev/load-env.ts reads each KEY=value line of a .env file into process.env, and returns how many variables it set, which load-app-env.ts prints as Loaded N variable(s) from .env. Two edge cases go wrong:
- A one-character quoted value loses its only character. The quote check is
value.startsWith('"') && value.endsWith('"')(and the same for'). For the value", the one character is both the "opening" and the "closing" quote, sovalue.slice(1, -1)yields the empty string.LONE_DQ="setsLONE_DQto"", not", and the same holds for'. - A key-less line is counted as loaded. For
=orphan, the key is"".process.env[""] === undefinedholds, so the assignment runs andloadedis incremented, but Node ignores an empty-named variable: nothing is set. TheLoaded N variable(s)line overstates by one for each such line.
Expected
- A value is unquoted only when it is at least two characters long and starts and ends with the same quote character.
LONE_DQ="sets"andLONE_SQ='sets'.A=""still sets the empty string, andA="x"still setsx. - A line whose key is empty after trimming (
=orphan,= x) is skipped like a line without=: nothing is set and it does not count toward the returned total.
LONE_DQ=" -> LONE_DQ is " (now: empty)
LONE_SQ=' -> LONE_SQ is ' (now: empty)
=orphan -> skipped, not counted (now: counted, nothing set)
A="" -> A is empty (unchanged)
A="x" -> A is x (unchanged)
Where
packages/cli/src/lib/dev/load-env.ts, parseAndApply, lines 22–34: the key taken at line 22 is never checked for emptiness, and the quote check at lines 24–29 has no length guard.
Reproduction
From packages/cli, save this as repro.ts and run npx tsx repro.ts:
import { mkdtempSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { loadEnvFiles } from "./src/lib/dev/load-env.ts"
const file = join(mkdtempSync(join(tmpdir(), "load-env-repro-")), ".env")
writeFileSync(file, ['LONE_DQ="', "LONE_SQ='", "=orphan", ""].join("\n"))
delete process.env.LONE_DQ
delete process.env.LONE_SQ
delete process.env.LANGSMITH_API_KEY
console.log("loaded:", loadEnvFiles([file]))
console.log("LONE_DQ:", JSON.stringify(process.env.LONE_DQ))
console.log("LONE_SQ:", JSON.stringify(process.env.LONE_SQ))
console.log('"" in process.env:', "" in process.env)Output at main (1a4e4551b):
loaded: 3
LONE_DQ: ""
LONE_SQ: ""
"" in process.env: false
Expected: loaded: 2, LONE_DQ: "\"", LONE_SQ: "'", "" in process.env: false.
Scope
Only packages/cli/src/lib/dev/load-env.ts needs to change. No change to loadEnvFiles's or loadEnvFile's signatures, to the shell-and-earlier-files-win precedence, to # comment handling, or to applyLangsmithTracing.
Activity