@maverickcer/env-cap 0.4.0 → 0.5.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.
Files changed (46) hide show
  1. package/README.md +12 -12
  2. package/dist/.dts/build/index.d.ts +2 -2
  3. package/dist/.dts/build/index.d.ts.map +1 -1
  4. package/dist/.dts/build/lifecycle-model.d.ts +110 -2
  5. package/dist/.dts/build/lifecycle-model.d.ts.map +1 -1
  6. package/dist/.dts/build/link.d.ts +8 -0
  7. package/dist/.dts/build/link.d.ts.map +1 -1
  8. package/dist/.dts/build/parse.d.ts +8 -0
  9. package/dist/.dts/build/parse.d.ts.map +1 -1
  10. package/dist/.dts/runtime/document.d.ts +40 -0
  11. package/dist/.dts/runtime/document.d.ts.map +1 -1
  12. package/dist/build-4SFAWO5Y.js +5148 -0
  13. package/dist/build-4SFAWO5Y.js.map +1 -0
  14. package/dist/build.cjs +5021 -6
  15. package/dist/build.cjs.map +1 -1
  16. package/dist/build.js +5020 -7
  17. package/dist/build.js.map +1 -1
  18. package/dist/chunk-BV5OERR3.js +11 -0
  19. package/dist/{chunk-QUSAQJ52.js.map → chunk-BV5OERR3.js.map} +1 -1
  20. package/dist/cli/index.js +580 -38
  21. package/dist/cli/index.js.map +1 -1
  22. package/dist/eslint-plugin/index.cjs +701 -1
  23. package/dist/eslint-plugin/index.cjs.map +1 -1
  24. package/dist/eslint-plugin/index.js +701 -1
  25. package/dist/eslint-plugin/index.js.map +1 -1
  26. package/dist/evidence.cjs +59 -1
  27. package/dist/evidence.cjs.map +1 -1
  28. package/dist/evidence.js +59 -1
  29. package/dist/evidence.js.map +1 -1
  30. package/dist/helpers.cjs +379 -1
  31. package/dist/helpers.cjs.map +1 -1
  32. package/dist/helpers.js +379 -1
  33. package/dist/helpers.js.map +1 -1
  34. package/dist/index.cjs +249 -2
  35. package/dist/index.cjs.map +1 -1
  36. package/dist/index.js +249 -2
  37. package/dist/index.js.map +1 -1
  38. package/dist/node.cjs +27 -1
  39. package/dist/node.cjs.map +1 -1
  40. package/dist/node.js +27 -1
  41. package/dist/node.js.map +1 -1
  42. package/package.json +5 -3
  43. package/schemas/env-cap-report.schema.json +37 -3
  44. package/dist/build-ICYKXFRE.js +0 -12
  45. package/dist/build-ICYKXFRE.js.map +0 -1
  46. package/dist/chunk-QUSAQJ52.js +0 -3
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cli/index.ts","../../src/cli/filesystem.ts","../../src/cli/init.ts","../../src/cli/json.ts"],"sourcesContent":["import { realpathSync } from \"node:fs\"\nimport { pathToFileURL } from \"node:url\"\nimport type {\n generateEnvArtifacts,\n CheckEnvArtifactsResult,\n ContractModelContract,\n EnvExampleOnExisting,\n ManifestChangeReport,\n} from \"../build/index.js\"\nimport { nodeBuildFileSystem } from \"./filesystem.js\"\nimport { runInitCommand } from \"./init.js\"\nimport type { JsonRequestedPasses } from \"./json.js\"\nimport { serializeFailure, serializeSuccess, writeJson } from \"./json.js\"\n\n/**\n * Thin, optional CLI wrapper around `generateEnvArtifacts()`. Nothing here is\n * required for library usage -- `generateEnvManifest`/`generateDocumentation`/\n * `generateUsageReport`/`generateEnvArtifacts` are fully usable as plain imports\n * from npm scripts, bundler plugins, or CI steps without this file.\n *\n * `../build/index.js` (and, transitively, `typescript`) is imported here as\n * TYPES ONLY at module scope, and loaded with a dynamic `import()` inside\n * `runCheckMode`/`runGenerateMode` instead of a static top-level import.\n * `typescript` is an optional peer dependency (README: \"TypeScript 5+ is\n * only required for build-time manifest generation\"), but a static import\n * is evaluated eagerly for every invocation of this file, including\n * `env-cap init` and `env-cap --help` -- neither of which touches\n * `../build/index.js` at all. Without this split, a fresh install with no\n * `typescript` present threw `ERR_MODULE_NOT_FOUND: Cannot find package\n * 'typescript'` on `env-cap init`, before `runInitCommand` (pure `node:fs`,\n * no TypeScript dependency -- see ADR 0042) ever ran.\n */\n\n/** Parsed CLI flags -- see `helpText()` below for what each one means. */\nexport interface ParsedArgs {\n root?: string\n location?: string\n include: string[]\n exclude: string[]\n packages: string[]\n tsconfig?: string | false\n docs?: string\n envExample?: string\n envExampleOnExisting?: EnvExampleOnExisting\n ownership?: string\n evidence?: string\n strict: boolean\n strictDocs: boolean\n strictOwnership: boolean\n expiringWithinDays?: number\n json: boolean\n check: boolean\n help: boolean\n}\n\n// Every VALUE_FLAGS/BOOL_FLAGS entry below is a named function declaration,\n// not an inline arrow inside the dispatch table object literals -- Stryker\n// marks a module-level object literal's own arrow-shorthand properties\n// `static: true` (evaluated once at module load), which can produce a false\n// \"Survived\" on a mutant that real tests genuinely reach and would fail\n// against, even though `ignoreStatic` only suppresses a static mutant with\n// *zero* coverage (this one has real coverage, just misattributed). Named\n// function declarations don't have this problem -- their bodies are ordinary\n// function-scope code, attributed normally. See the identical fix already\n// applied to `check-artifacts.ts`/`reference-projections.ts`'s `defineX({...})`\n// schema objects.\nfunction setRoot(a: ParsedArgs, v: string): void {\n a.root = v\n}\nfunction setLocation(a: ParsedArgs, v: string): void {\n a.location = v\n}\nfunction pushInclude(a: ParsedArgs, v: string): void {\n a.include.push(v)\n}\nfunction pushExclude(a: ParsedArgs, v: string): void {\n a.exclude.push(v)\n}\nfunction pushPackage(a: ParsedArgs, v: string): void {\n a.packages.push(v)\n}\nfunction setTsconfig(a: ParsedArgs, v: string): void {\n a.tsconfig = v\n}\nfunction setDocs(a: ParsedArgs, v: string): void {\n a.docs = v\n}\nfunction setEnvExample(a: ParsedArgs, v: string): void {\n a.envExample = v\n}\nfunction setOwnership(a: ParsedArgs, v: string): void {\n a.ownership = v\n}\nfunction setEvidence(a: ParsedArgs, v: string): void {\n a.evidence = v\n}\nfunction setEnvExampleOnExisting(a: ParsedArgs, v: string): void {\n const values: readonly EnvExampleOnExisting[] = [\"keep-sibling\", \"overwrite\", \"skip\"]\n if (!values.includes(v as EnvExampleOnExisting)) {\n throw new Error(\n `Unknown value for --env-example-on-existing: \"${v}\". Expected one of: ${values.join(\", \")}.`,\n )\n }\n a.envExampleOnExisting = v as EnvExampleOnExisting\n}\nfunction setExpiringWithinDays(a: ParsedArgs, v: string): void {\n const parsed = Number(v)\n if (!Number.isFinite(parsed)) {\n throw new Error(`--expiring-within-days expects a number, got \"${v}\".`)\n }\n a.expiringWithinDays = parsed\n}\n\n/** Flags that consume the following argv token. A table, not a `switch`, so `parseArgs` stays a flat dispatch loop -- one branch per *kind* of flag. */\nconst VALUE_FLAGS: Readonly<Partial<Record<string, (args: ParsedArgs, value: string) => void>>> = {\n \"--root\": setRoot,\n \"--location\": setLocation,\n \"--include\": pushInclude,\n \"--exclude\": pushExclude,\n \"--package\": pushPackage,\n \"--tsconfig\": setTsconfig,\n \"--docs\": setDocs,\n \"--env-example\": setEnvExample,\n \"--ownership\": setOwnership,\n \"--evidence\": setEvidence,\n \"--env-example-on-existing\": setEnvExampleOnExisting,\n \"--expiring-within-days\": setExpiringWithinDays,\n}\n\nfunction setNoTsconfig(a: ParsedArgs): void {\n a.tsconfig = false\n}\nfunction setStrict(a: ParsedArgs): void {\n a.strict = true\n}\nfunction setStrictDocs(a: ParsedArgs): void {\n a.strictDocs = true\n}\nfunction setStrictOwnership(a: ParsedArgs): void {\n a.strictOwnership = true\n}\nfunction setJson(a: ParsedArgs): void {\n a.json = true\n}\nfunction setCheck(a: ParsedArgs): void {\n a.check = true\n}\nfunction setHelp(a: ParsedArgs): void {\n a.help = true\n}\n\n/** Flags that set a boolean and consume nothing further. */\n// This object literal itself is `static: true` (built once at module load),\n// which Stryker can misattribute a false \"Survived\" to even though it's\n// genuinely, heavily test-covered -- NOT an equivalent mutant. Hand-verified:\n// replacing this whole literal with `{}` and running the real suite\n// (`vitest run`, whole package) fails 21 tests across 2 files (every test\n// exercising `--strict`/`--json`/`--check`/`--help`/etc.), each throwing\n// \"Unknown argument\" instead of setting the flag. Extracting each entry to\n// its own named function (see above) already fixed the same class of false\n// \"Survived\" for every individual entry's own body; this fixes the entries,\n// the wrapper object literal's own collapse-to-`{}` mutant is a second,\n// distinct static-attribution target that the same fix doesn't reach.\n// Stryker disable next-line ObjectLiteral\nconst BOOL_FLAGS: Readonly<Partial<Record<string, (args: ParsedArgs) => void>>> = {\n \"--no-tsconfig\": setNoTsconfig,\n \"--strict\": setStrict,\n \"--strict-docs\": setStrictDocs,\n \"--strict-ownership\": setStrictOwnership,\n \"--json\": setJson,\n \"--check\": setCheck,\n \"--help\": setHelp,\n \"-h\": setHelp,\n}\n\n/**\n * Parses `process.argv` (already sliced past the `node`/script path) into `ParsedArgs`.\n *\n * @throws {Error} On an unrecognized flag, a flag missing its required value, or an invalid `--env-example-on-existing`/`--expiring-within-days` value.\n */\nexport function parseArgs(argv: string[]): ParsedArgs {\n const args: ParsedArgs = {\n include: [],\n exclude: [],\n packages: [],\n strict: false,\n strictDocs: false,\n strictOwnership: false,\n json: false,\n check: false,\n help: false,\n }\n\n // A fast-failing pass-count guard, independent of `i` itself: on any real\n // input `i` strictly advances toward `argv.length` every pass (the loop's\n // own `i++`, plus an extra `++i` when a value flag consumes its argument),\n // so no correct input ever needs more passes than `argv.length`. A mutation\n // that reverses the loop's own advance (`i++` -> `i--`) makes `i` walk\n // *away* from `argv.length` instead -- an infinite loop that produces no\n // observably wrong result for an assertion-based test to catch, only a hang\n // until Stryker's own mutant timeout. This counter climbs every pass\n // regardless of `i`'s (possibly-mutated) motion, so it still reaches its\n // bound and throws an ordinary, fast error instead.\n let passes = 0\n // The guard's own arithmetic/direction/comparison below are just as\n // unreachable/inconsequential for any correct `argv` as the guard body\n // itself (see the disable comment on the `if` below): under correct code\n // `passes` never approaches `maxPasses`, so no real test input can observe\n // a change to any of them.\n // Stryker disable next-line ArithmeticOperator\n const maxPasses = argv.length * 2 + 4\n for (let i = 0; i < argv.length; i++) {\n // Stryker disable next-line UpdateOperator\n passes++\n // Unreachable by design for any correct `argv`, the same way the\n // `arg = argv[i] ?? \"\"` fallback just below is: this guard's whole\n // purpose is to fail fast when a *mutated* build's loop-advance is\n // broken, so no real test input (which only ever exercises correct\n // code) can reach it. A test that reached it would itself require an\n // already-broken build to construct.\n // Stryker disable next-line BlockStatement,ConditionalExpression,EqualityOperator\n if (passes > maxPasses) {\n // Stryker disable next-line CallExpression\n throw new Error(\n // Stryker disable next-line StringLiteral\n `parseArgs: exceeded ${String(maxPasses)} iterations parsing ${String(argv.length)} argument(s) -- this should never happen for any real argv and indicates an internal parsing bug.`,\n )\n }\n // Provably unreachable for any real `string[]` input: the loop condition\n // `i < argv.length` guarantees `argv[i]` is in-bounds (hence defined)\n // every time this line runs, whether `i` just advanced by the outer\n // `i++` or by a value flag's own `++i` above -- `noUncheckedIndexedAccess`\n // isn't enabled, so TypeScript doesn't force this fallback either; it's\n // pure runtime defense against an out-of-bounds access that can't\n // actually occur. Hand-verified: replacing the fallback string and\n // running the real suite (`vitest run` across all of test/cli/) passes\n // unchanged.\n // Stryker disable next-line StringLiteral\n const arg = argv[i] ?? \"\"\n const valueFlag = VALUE_FLAGS[arg]\n if (valueFlag) {\n valueFlag(args, nonEmpty(argv[++i], arg))\n continue\n }\n const boolFlag = BOOL_FLAGS[arg]\n if (boolFlag) {\n boolFlag(args)\n continue\n }\n throw new Error(`Unknown argument: ${arg}`)\n }\n\n return args\n}\n\n/** Requires `value` (the argument immediately following `flag`) to be a non-empty string; throws otherwise. */\nfunction nonEmpty(value: string | undefined, flag: string): string {\n if (!value) throw new Error(`${flag} requires a value.`)\n return value\n}\n\n// A function, not a module-level `const` -- Stryker marks a module-level\n// template-literal `static: true` (evaluated once at import time), which can\n// under-attribute a real, test-covered mutant to a false \"Survived\" the same\n// way the VALUE_FLAGS/BOOL_FLAGS dispatch tables above did. Returning it from\n// a function makes the template literal ordinary function-scope code,\n// evaluated (and attributed) fresh on each of `main()`'s two call sites.\nfunction helpText(): string {\n return `env-cap - generate a manifest, docs, and/or a dependency ownership report from discovered env.schema.ts contracts\n\nUsage:\n env-cap init\n env-cap [--location <path>] [--docs <path>] [--ownership <path>] [--evidence <path>] [options]\n\n init Scaffold a minimal starting point (one env.schema.ts + a generate script); run \\`env-cap init --help\\` for details\n\nAt least one of --location, --docs, --ownership, or --evidence is required (for a non-init invocation).\n\nOptions:\n --root <path> Directory to resolve globs from (default: cwd)\n --location <path> Output path for the generated manifest\n --include <glob> Schema-discovery glob (repeatable, default: **/env.schema.ts)\n --exclude <glob> Glob pattern to exclude (repeatable)\n --package <name> Installed package name to also discover a schema from, via its \"envCap.schema\" package.json field (repeatable)\n --tsconfig <path> Path to a tsconfig.json (relative to root) whose \"paths\"/\"baseUrl\" resolve aliased imports encountered during static analysis (default: auto-detected \"tsconfig.json\" at root)\n --no-tsconfig Disable tsconfig path-alias resolution entirely\n --docs <path> Also emit the rich Markdown docs artifact at this path\n --env-example <path> Also emit a .env.example file at this path (only meaningful alongside --docs)\n --env-example-on-existing <mode> What to do when --env-example's target already exists: keep-sibling (default, never overwrites -- writes a timestamped sibling instead), overwrite, or skip (write nothing). No effect with --check, which never writes anything regardless.\n --ownership <path> Also emit the Dependency & Ownership Report at this path\n --evidence <path> Also emit the persisted evidence artifact (the full EvidenceModel, plus a paired .fingerprint sidecar) at this path, e.g. docs/env.evidence.json (see ADR 0038). Independent of --location -- needs no other pass.\n --strict Escalate every pass's warning findings to hard errors -- compatibility (manifest pass -- ADR 0009's provable exclusive-group/compatibility errors), documentation, and ownership alike (ADR 0044). Nothing is written when it fires. Info-severity findings are never escalated. Equivalent to passing all three scoped flags below at once.\n --strict-docs Escalate every documentation-family warning (undocumented contract/variable, stale doc entry, expiring/expired entry, unresolvable documentEnv() link) to a hard error, independent of --strict. Nothing is written when it fires. Info-severity findings are never escalated.\n --strict-ownership Escalate every ownership-family warning (abandoned contract, unresolved consumer, unconsumed owned variable, indeterminate ownership, stale/missing dynamicAccess citation) to a hard error, independent of --strict. Nothing is written when it fires. Info-severity findings are never escalated.\n --expiring-within-days <n> Window (in days) for the \"expiring soon\" report (default: 30)\n --json Emit a machine-readable JSON report instead of formatted text (see ADR 0013)\n --check Verify generated artifacts are up to date without writing anything; exits 1 if any is stale or missing (see ADR 0016)\n --help Show this message\n`\n}\n\n/** @internal Exported for direct unit coverage -- reached through `main()`'s `--evidence` flow in production, but that path alone can't isolate this from `contractNameResolver()`/`writeEvidenceChanges()`'s own logic, nor cheaply exercise every field-change/added/updated/removed shape without a full real generation run per case. */\nexport function formatFieldChanges(\n changes: ManifestChangeReport[\"updatedContracts\"][number][\"changes\"],\n): string {\n return changes\n .map((c) => `${c.field} (${c.previous ?? \"unset\"} -> ${c.current ?? \"unset\"})`)\n .join(\", \")\n}\n\n/**\n * Mirrors `docs.ts`'s \"Changes since last report\" section: a fixed\n * Added/Updated/Removed order, each printed only when non-empty, \"No\n * changes.\" when all three are empty -- printed whenever `--evidence` was\n * requested, not only when something actually changed. See ADR 0038 (the\n * persisted evidence artifact -- not the manifest itself, which no longer\n * tracks its own change history; see ADR 0021's now-superseded design).\n */\n/**\n * Resolves a `${file}#${exportName}` reference to the contract's display\n * name, from `ContractModel` -- the one model that owns it. A change-report\n * ref carries identity only (see `ContractRef`), so this is the lookup any\n * renderer needing prose performs; a removed contract has no entry in the\n * *current* model at all, which is exactly why this falls back to the export\n * name rather than assuming one exists.\n */\n/** @internal Exported for direct unit coverage -- see {@link formatFieldChanges}'s own doc comment for why. */\nexport function contractNameResolver(\n contracts: readonly ContractModelContract[],\n): (ref: { file: string; exportName: string }) => string {\n const byIdentity = new Map(contracts.map((c) => [`${c.file}#${c.exportName}`, c.contractName]))\n return (ref) => byIdentity.get(`${ref.file}#${ref.exportName}`) ?? ref.exportName\n}\n\n/** @internal Exported for direct unit coverage -- see {@link formatFieldChanges}'s own doc comment for why. */\nexport function writeEvidenceChanges(\n changes: ManifestChangeReport,\n contracts: readonly ContractModelContract[],\n): void {\n const nameOf = contractNameResolver(contracts)\n const hasAdded = changes.addedContracts.length > 0 || changes.addedVariables.length > 0\n const hasUpdated = changes.updatedContracts.length > 0 || changes.updatedVariables.length > 0\n const hasRemoved = changes.removedContracts.length > 0 || changes.removedVariables.length > 0\n\n process.stdout.write(\"\\nEvidence changes since the last persisted snapshot:\\n\")\n if (!hasAdded && !hasUpdated && !hasRemoved) {\n process.stdout.write(\" No changes.\\n\")\n return\n }\n\n if (hasAdded) {\n process.stdout.write(\" Added:\\n\")\n for (const c of changes.addedContracts)\n process.stdout.write(` - contract \"${nameOf(c)}\" (${c.file})\\n`)\n for (const v of changes.addedVariables)\n process.stdout.write(` - ${v.key} in \"${nameOf(v)}\"\\n`)\n }\n if (hasUpdated) {\n process.stdout.write(\" Updated:\\n\")\n for (const c of changes.updatedContracts)\n process.stdout.write(` - contract \"${nameOf(c)}\": ${formatFieldChanges(c.changes)}\\n`)\n for (const v of changes.updatedVariables)\n process.stdout.write(` - ${v.key} in \"${nameOf(v)}\": ${formatFieldChanges(v.changes)}\\n`)\n }\n if (hasRemoved) {\n process.stdout.write(\" Removed:\\n\")\n for (const c of changes.removedContracts)\n process.stdout.write(` - contract \"${nameOf(c)}\" (${c.file})\\n`)\n for (const v of changes.removedVariables)\n process.stdout.write(` - ${v.key} in \"${nameOf(v)}\"\\n`)\n }\n}\n\n/**\n * Which passes this invocation asked for, straight off the parsed flags --\n * never inferred from which results came back populated, which is exactly the\n * ambiguity `requested` exists to remove. See `JsonRequestedPasses`.\n */\n/** @internal Exported for direct unit coverage -- see {@link formatFieldChanges}'s own doc comment for why. */\nexport function requestedPasses(args: ParsedArgs): JsonRequestedPasses {\n return {\n manifest: args.location !== undefined,\n docs: args.docs !== undefined,\n usage: args.ownership !== undefined,\n evidence: args.evidence !== undefined,\n }\n}\n\n/**\n * The CLI entry point: parses argv, runs `--check` or a real generate, and writes either\n * human-readable text or (`--json`) a machine-readable report to stdout, setting\n * `process.exitCode` accordingly (see ADR 0013 for the JSON report contract).\n */\n/**\n * The full `GenerateEnvArtifactsOptions` object, built once from parsed args --\n * `checkEnvArtifacts` and `generateEnvArtifacts` take the same type, so both\n * call sites use this directly. `evidence` is included: `--check --evidence`\n * verifies the persisted evidence artifact for drift too, exactly as `--check`\n * already does for the manifest/docs/env-example/ownership artifacts.\n */\n/**\n * Whether a findings group escalates to a hard error: when bare `--strict`\n * is on (ADR 0044 -- `--strict` alone means every group), or when the\n * group-specific `--strict-*` flag is. One place so every group's\n * escalation reads identically, matching `@maverickcer/data-cap`'s own\n * `groupEscalates` (`src/build/generate-data-artifacts.ts`).\n */\nfunction groupEscalates(strict: boolean, specificFlag: boolean): boolean {\n return strict || specificFlag\n}\n\n/** @internal Exported for direct unit coverage -- see {@link formatFieldChanges}'s own doc comment for why. */\nexport function artifactOptions(args: ParsedArgs) {\n const listOrUndefined = (list: string[]): string[] | undefined =>\n list.length > 0 ? list : undefined\n return {\n // The deliberate injection boundary: the CLI (an executable consumer)\n // hands `env-cap/build` (a library surface) its filesystem capability.\n // See src/cli/filesystem.ts and ADR 0040.\n fs: nodeBuildFileSystem,\n root: args.root,\n include: listOrUndefined(args.include),\n exclude: listOrUndefined(args.exclude),\n packages: listOrUndefined(args.packages),\n tsconfig: args.tsconfig,\n manifest: args.location\n ? {\n location: args.location,\n onIncompatibility: args.strict ? (\"throw\" as const) : (\"warn\" as const),\n }\n : (false as const),\n docs: args.docs\n ? {\n location: args.docs,\n expiringWithinDays: args.expiringWithinDays,\n envExample: args.envExample\n ? { location: args.envExample, onExisting: args.envExampleOnExisting }\n : undefined,\n }\n : (false as const),\n usage: args.ownership ? { report: { location: args.ownership } } : (false as const),\n evidence: args.evidence ? { location: args.evidence } : (false as const),\n onUndocumented: groupEscalates(args.strict, args.strictDocs)\n ? (\"throw\" as const)\n : (\"warn\" as const),\n onOwnershipIssue: groupEscalates(args.strict, args.strictOwnership)\n ? (\"throw\" as const)\n : (\"warn\" as const),\n }\n}\n\n/** `if (items.length) { write header; write \" - <render(item)>\" per item }` -- the summary-list shape `main`'s generate output repeats ~15 times. */\n/** @internal Exported for direct unit coverage -- see {@link formatFieldChanges}'s own doc comment for why. */\nexport function printList<T>(\n items: readonly T[],\n header: string,\n render: (item: T) => string,\n): void {\n if (items.length === 0) return\n process.stdout.write(`\\n${header}\\n`)\n for (const item of items) process.stdout.write(` - ${render(item)}\\n`)\n}\n\n/** `--check`: verify every requested artifact for drift, write nothing, exit non-zero on any stale/missing. */\nasync function runCheckMode(args: ParsedArgs): Promise<void> {\n let checkResult: CheckEnvArtifactsResult\n try {\n const { checkEnvArtifacts } = await import(\"../build/index.js\")\n checkResult = await checkEnvArtifacts(artifactOptions(args))\n } catch (error) {\n if (!args.json) throw error\n writeJson(serializeFailure(error))\n process.exitCode = 1\n return\n }\n\n const stale = checkResult.findings.filter((f) => f.status !== \"ok\").map((f) => f.artifact)\n if (args.json) {\n // Both the `{manifest,docs,usage: undefined}` object and the `false`\n // (`includeEvidence`) argument below are equivalent at this call site:\n // `serializeSuccess()` only ever spreads these into its return payload\n // (`...rest`, `...(includeEvidence ? {evidence} : {})`), and `writeJson`\n // serializes the result through `JSON.stringify`, which drops an\n // `undefined`-valued key exactly like a MISSING key -- so `{}` (every\n // field implicitly undefined) and `{manifest: undefined, ...}` (every\n // field explicitly undefined) serialize identically, and\n // `includeEvidence: true` would only add `evidence: undefined` (`result`\n // here has no `evidence` property to destructure), equally dropped.\n // `requested` is passed explicitly right below, so `serializeSuccess`'s\n // own `rest.manifest !== undefined`-based default (which WOULD\n // distinguish `{}` from explicit `undefined`s) is never reached from\n // this call site either. Hand-verified: mutating both together (`{}`,\n // `true`) and running the real whole-package suite (`vitest run`)\n // passes unchanged.\n // Stryker disable ObjectLiteral,BooleanLiteral\n writeJson(\n serializeSuccess(\n { manifest: undefined, docs: undefined, usage: undefined },\n { ok: checkResult.ok, stale },\n false,\n // `--check` writes nothing, so every result above is undefined by\n // construction -- `requested` is the only thing distinguishing \"this run\n // checked the docs artifact\" from \"it didn't.\"\n requestedPasses(args),\n ),\n )\n // Stryker restore ObjectLiteral,BooleanLiteral\n } else {\n process.stdout.write(\"Checking for drift (--check: nothing will be written)...\\n\\n\")\n for (const f of checkResult.findings) {\n process.stdout.write(\n ` ${f.artifact.padEnd(10)} ${f.path.padEnd(50)} ${f.status.toUpperCase()}${f.detail ? ` (${f.detail})` : \"\"}\\n`,\n )\n }\n process.stdout.write(\n checkResult.ok\n ? \"\\nAll generated artifacts are up to date.\\n\"\n : `\\n${stale.length} artifact(s) are stale or missing. Run without --check to regenerate.\\n`,\n )\n }\n process.exitCode = checkResult.ok ? 0 : 1\n}\n\ntype GenerateResult = Awaited<ReturnType<typeof generateEnvArtifacts>>\n\n/** The human-readable manifest section of a generate run's summary. */\n/** @internal Exported for direct unit coverage -- see {@link formatFieldChanges}'s own doc comment for why. */\nexport function printManifestSummary(manifest: NonNullable<GenerateResult[\"manifest\"]>): void {\n process.stdout.write(`Wrote manifest: ${manifest.outputPath}\\n`)\n process.stdout.write(`Discovered ${String(manifest.contracts.length)} contract(s).\\n`)\n printList(\n manifest.warnings,\n `${String(manifest.warnings.length)} compatibility warning(s):`,\n (w) => `${w.code ? `[${w.code}] ` : \"\"}${w.variable}: ${w.reason}`,\n )\n printList(\n manifest.parseWarnings,\n `${String(manifest.parseWarnings.length)} parse warning(s):`,\n (w) => `${w.file}: ${w.message}`,\n )\n}\n\n/** The human-readable docs (+ env-example) section of a generate run's summary. */\nfunction printDocsSummary(docs: NonNullable<GenerateResult[\"docs\"]>): void {\n process.stdout.write(`Wrote docs: ${docs.docsPath}\\n`)\n const ex = docs.envExample\n if (ex) {\n process.stdout.write(\n ex.skippedExistingPath\n ? `Left existing example untouched: ${ex.skippedExistingPath}\\nWrote a fresh copy to compare/merge: ${ex.writtenPath}\\n`\n : `Wrote example: ${ex.writtenPath}\\n`,\n )\n printList(\n ex.staleVariables,\n `${String(ex.staleVariables.length)} variable(s) in the existing example are no longer used by any contract:`,\n (name) => name,\n )\n printList(\n ex.variablesToComment,\n `${String(ex.variablesToComment.length)} variable(s) in the existing example should be commented out (feature no longer active):`,\n (name) => name,\n )\n printList(\n ex.variablesToAdd,\n `${String(ex.variablesToAdd.length)} variable(s) required by the current configuration are missing from the existing example:`,\n (name) => name,\n )\n }\n\n const doc = docs.documentation\n printList(\n doc.undocumentedContracts,\n `${String(doc.undocumentedContracts.length)} undocumented contract(s) (no documentEnv() linked):`,\n (c) => `${c.exportName} (${c.file})`,\n )\n printList(\n doc.undocumentedVariables,\n `${String(doc.undocumentedVariables.length)} undocumented variable(s):`,\n (v) => `${v.key} in ${v.exportName} (${v.file})`,\n )\n printList(\n doc.staleDocEntries,\n `${String(doc.staleDocEntries.length)} stale documentEnv() entry/entries (no matching schema variable):`,\n (s) => `${s.key} in ${s.exportName} (${s.file})`,\n )\n printList(\n doc.expiringSoon,\n `${String(doc.expiringSoon.length)} variable(s)/contract(s) expiring soon or already expired:`,\n (e) => {\n const label = e.key ? `${e.key} in ${e.exportName}` : e.exportName\n const status =\n e.daysRemaining < 0\n ? `expired ${String(Math.abs(e.daysRemaining))}d ago`\n : `${String(e.daysRemaining)}d remaining`\n return `${label}: ${e.expiresAt} (${status})`\n },\n )\n printList(\n doc.unresolvedLinks,\n `${String(doc.unresolvedLinks.length)} documentEnv() call(s) could not be statically linked:`,\n (u) => `${u.file}: ${u.reason}`,\n )\n}\n\n/** The human-readable dependency-ownership section of a generate run's summary. */\n/** @internal Exported for direct unit coverage -- see {@link formatFieldChanges}'s own doc comment for why. */\nexport function printUsageSummary(usage: NonNullable<GenerateResult[\"usage\"]>): void {\n if (usage.reportPath) {\n process.stdout.write(`Wrote dependency ownership report: ${usage.reportPath}\\n`)\n }\n printList(\n usage.abandonedContracts,\n `${String(usage.abandonedContracts.length)} abandoned contract(s) (never imported anywhere):`,\n (f) => `${f.contractName} (${f.file})`,\n )\n printList(\n usage.unresolvedConsumers,\n `${String(usage.unresolvedConsumers.length)} contract(s) with unresolved consumers (barrel re-exports):`,\n (f) => `${f.contractName}: ${f.reason}`,\n )\n printList(\n usage.unconsumedOwnedVariables,\n `${String(usage.unconsumedOwnedVariables.length)} unconsumed owned variable(s):`,\n (f) => `${f.key} in ${f.contractName}`,\n )\n printList(\n usage.indeterminate,\n `${String(usage.indeterminate.length)} indeterminate finding(s) (dynamic access, never guessed at):`,\n (f) => `${f.key} in ${f.contractName}: ${f.reason}`,\n )\n printList(\n usage.parseWarnings,\n `${String(usage.parseWarnings.length)} parse warning(s):`,\n (w) => `${w.file}: ${w.message}`,\n )\n}\n\n/** A real generate run: write every requested artifact, then print a summary (or `--json` envelope). */\nasync function runGenerateMode(args: ParsedArgs): Promise<void> {\n let result: GenerateResult\n try {\n const { generateEnvArtifacts } = await import(\"../build/index.js\")\n result = await generateEnvArtifacts(artifactOptions(args))\n } catch (error) {\n if (!args.json) throw error // propagates to main().catch() exactly as before\n writeJson(serializeFailure(error))\n process.exitCode = 1\n return\n }\n\n if (args.json) {\n writeJson(\n serializeSuccess(result, undefined, args.evidence !== undefined, requestedPasses(args)),\n )\n return\n }\n\n const totalWarnings =\n (result.manifest?.parseWarnings.length ?? 0) +\n (result.docs?.documentation.unresolvedLinks.length ?? 0) +\n (result.usage?.parseWarnings.length ?? 0)\n if (totalWarnings > 0) {\n process.stdout.write(\n `⚠ ${totalWarnings} unresolved/dropped-schema warning(s) found -- details below. Re-run with --json for a machine-readable report.\\n\\n`,\n )\n }\n\n if (result.manifest) printManifestSummary(result.manifest)\n if (result.docs) printDocsSummary(result.docs)\n if (result.usage) printUsageSummary(result.usage)\n\n if (args.evidence) {\n process.stdout.write(`Wrote evidence: ${args.evidence}\\n`)\n writeEvidenceChanges(result.evidence.change.manifest, result.evidence.contract.contracts)\n }\n}\n\nexport async function main(): Promise<void> {\n const argv = process.argv.slice(2)\n\n // Subcommand dispatch: `init` as the FIRST positional token routes to the\n // scaffolder. Every existing flag-based invocation is untouched -- no flag\n // is reinterpreted as a subcommand, `--help` alone still prints helpText().\n if (argv[0] === \"init\") {\n process.exitCode = runInitCommand(argv.slice(1))\n return\n }\n\n const args = parseArgs(argv)\n\n if (args.help) {\n process.stdout.write(helpText())\n process.exitCode = 0\n return\n }\n\n if (!args.location && !args.docs && !args.ownership && !args.evidence) {\n if (args.json) {\n writeJson(\n serializeFailure(\n new Error(\"At least one of --location, --docs, --ownership, or --evidence is required.\"),\n ),\n )\n } else {\n process.stdout.write(helpText())\n }\n process.exitCode = 1\n return\n }\n\n await (args.check ? runCheckMode(args) : runGenerateMode(args))\n}\n\n// Only auto-run when this file is the process entry point, not when a test\n// imports `parseArgs`/`main` directly -- importing this module must never\n// have the side effect of running the CLI.\n//\n// npm installs `bin` entries as symlinks (e.g. `node_modules/.bin/env-cap`\n// -> `../env-cap/dist/cli/index.js`). Node resolves\n// `import.meta.url` through that symlink to this file's real, on-disk path,\n// but leaves `process.argv[1]` as the symlink path it was actually invoked\n// with -- so comparing the two directly never matches for a real `npx`/`.bin`\n// invocation, and the CLI would silently no-op. Resolving `argv[1]` through\n// `realpathSync` first makes the comparison symlink-aware; the try/catch\n// falls back to the unresolved path so this can't itself throw for an\n// argv[1] that doesn't resolve to a real file.\nexport function directRunUrl(): string | undefined {\n const entry = process.argv[1]\n if (!entry) return undefined\n try {\n return pathToFileURL(realpathSync(entry)).href\n } catch {\n return pathToFileURL(entry).href\n }\n}\n\nconst isDirectRun = import.meta.url === directRunUrl()\n\nif (isDirectRun) {\n main().catch((error: unknown) => {\n const message = error instanceof Error ? error.message : String(error)\n process.stderr.write(`${message}\\n`)\n process.exitCode = 1\n })\n}\n","import fs from \"node:fs/promises\"\nimport type { BuildDirent, BuildFileSystem, BuildStats } from \"../build/types.js\"\n\n/**\n * The concrete `node:fs/promises`-backed {@link BuildFileSystem} the `env-cap`\n * CLI hands to `env-cap/build`. Also re-exported as the public\n * `env-cap/node` entry point (`src/node/index.ts`) for a\n * consumer running the generators from their own Node build script.\n *\n * This is the deliberate injection boundary -- mirrors `repo-contract`'s own\n * `repo-contract.config.ts` (`spawn: crossSpawn, env: process.env`): a\n * **library surface** (`./build`) must not acquire filesystem access\n * implicitly; an **executable-context** entry (this CLI, or `./node`)\n * constructs the adapter and passes it in. `src/cli/**` is the sanctioned\n * executable-source carve-out -- `node:fs` lives only here. See ADR 0040.\n *\n * A thin structural pass-through: each method delegates straight to\n * `node:fs/promises`, whose real `Dirent`/`Stats` already satisfy the\n * minimal {@link BuildFileSystem} `BuildDirent`/`BuildStats` shapes.\n *\n * Named `function` declarations, not an object of arrow properties, so each\n * delegation body is a per-call statement a mutation test can actually reach\n * -- an arrow assigned as a property is only evaluated once, at module load,\n * where Stryker's mutant switch can't flip it (the module-level-`Set` trap\n * `build/discover.ts` calls out, in another form).\n */\nfunction readFile(path: string, encoding: \"utf8\"): Promise<string> {\n return fs.readFile(path, encoding)\n}\n\nfunction writeFile(path: string, data: string, encoding: \"utf8\"): Promise<void> {\n return fs.writeFile(path, data, encoding)\n}\n\nasync function mkdir(path: string, options: { recursive: true }): Promise<void> {\n await fs.mkdir(path, options)\n}\n\nfunction readdir(path: string, options: { withFileTypes: true }): Promise<BuildDirent[]> {\n return fs.readdir(path, options)\n}\n\nfunction stat(path: string): Promise<BuildStats> {\n return fs.stat(path)\n}\n\nfunction realpath(path: string): Promise<string> {\n return fs.realpath(path)\n}\n\n// The `{}` mutant here is a module-load-time (static) mutant: once this\n// module is imported and the const is bound, Stryker's per-mutant switch\n// can't re-run the binding, so the mutant can never actually activate --\n// Stryker itself flags it `static: true`. It is plainly non-equivalent (an\n// empty adapter breaks every consumer), just unkillable by the tool. Each\n// delegating function above is individually mutation-covered.\n// Stryker disable next-line ObjectLiteral\nexport const nodeBuildFileSystem: BuildFileSystem = {\n readFile,\n writeFile,\n mkdir,\n readdir,\n stat,\n realpath,\n}\n","import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from \"node:fs\"\nimport path from \"node:path\"\n\n/**\n * `env-cap init` -- scaffolds a minimal, working env-cap starting point into\n * the current project: one discoverable capability contract and one\n * artifact-generation script. Nothing more.\n *\n * Deliberately filesystem-only and non-executing, matching this package's\n * own runtime discipline (ADR 0002, ADR 0040) and repo-contract's `init`:\n * it reads the consumer's `package.json` (to confirm it's a project and to\n * decide `src/` vs. root placement) and writes new files with\n * exclusive-create -- it never runs a subprocess, never invokes a package\n * manager, never mutates `package.json`, never regenerates an artifact, and\n * never reads the ambient environment. Anything the documented workflow\n * still needs afterwards is printed as a `Next:` step, not performed here.\n * See ADR 0042.\n *\n * `src/cli/**` is the sanctioned place for direct `node:fs` use (ADR 0040) --\n * this file is bundled into the `bin` target, exempt from the\n * `verify-no-ambient-fs` tarball guard exactly as `src/cli/index.ts` is.\n */\n\n// USAGE/SCHEMA_TEMPLATE/GENERATOR_TEMPLATE are functions, not module-level\n// `const`s: a module-level const is evaluated once at import time, not per\n// test, so Stryker's perTest coverage analysis can't attribute it to any\n// single test and reports mutants on it Survived/NoCoverage even when tests\n// do exercise the rendered content. A function called at each use site is\n// evaluated during the test itself, which Stryker can attribute correctly.\nfunction usage(): string {\n return `Usage: env-cap init\n\nScaffolds a minimal env-cap starting point into the current directory:\n\n <src>/env.schema.ts a starter capability contract (createEnv + documentEnv)\n scripts/generate-env.mjs a script that generates the manifest + docs artifacts\n\nNever overwrites an existing file, never runs anything, never edits\npackage.json. Everything else -- generating artifacts, wiring validateEnv()\ninto startup -- is printed as a next step. Run generation afterwards with\n\\`node scripts/generate-env.mjs\\` or \\`npx env-cap --location <path>\\`.`\n}\n\nfunction schemaTemplate(): string {\n return `// Starter env-cap capability contract -- expand it: add your real variables,\n// split into per-capability files (e.g. features/<name>/env.schema.ts), or\n// keep everything here. env-cap discovers every **/env.schema.ts by default.\n//\n// createEnv() reads only default/processor/validator/context -- the fields\n// validateEnv() uses at runtime. documentEnv() is a build-time-only marker\n// that feeds the generated docs and ownership report; it is inert at runtime.\n// Keep the object passed to both a static literal -- env-cap resolves it by\n// static analysis and never executes this file.\nimport { createEnv, documentEnv } from \"@maverickcer/env-cap\"\n\nconst schema = {\n EXAMPLE_API_URL: {\n processor: (value: unknown): string => String(value ?? \"\"),\n validator: (value: string) => value.startsWith(\"https://\") || \"Expected an https:// URL.\",\n },\n}\n\nexport const exampleEnv = createEnv(schema, { name: \"example\", source: import.meta.url })\n\ndocumentEnv(schema, {\n owner: \"your-team\",\n variables: {\n EXAMPLE_API_URL: {\n description: \"Base URL for the example upstream API. Replace with a real variable.\",\n required: true,\n },\n },\n})\n`\n}\n\nfunction generatorTemplate(): string {\n return `// Build-time only. Run with \\`node scripts/generate-env.mjs\\`, or wire it into\n// a package.json script (e.g. \"generate:env\"). Never imported by app code.\nimport { generateEnvArtifacts } from \"@maverickcer/env-cap/build\"\nimport { nodeBuildFileSystem } from \"@maverickcer/env-cap/node\"\nimport path from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\n\nconst root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), \"..\")\n\nconst result = await generateEnvArtifacts({\n fs: nodeBuildFileSystem,\n root,\n manifest: { location: \"src/generated/env.manifest.ts\" },\n docs: {\n location: \"docs/ENVIRONMENT.md\",\n envExample: { location: \".env.example\", onExisting: \"keep-sibling\" },\n },\n usage: { report: { location: \"docs/OWNERSHIP.md\" } },\n})\n\nconsole.log(\\`Discovered \\${result.manifest?.contracts.length ?? 0} contract(s).\\`)\nif (result.manifest?.outputPath) console.log(\\`Wrote manifest: \\${result.manifest.outputPath}\\`)\nif (result.docs?.docsPath) console.log(\\`Wrote docs: \\${result.docs.docsPath}\\`)\n`\n}\n\ntype WriteOutcome = \"created\" | \"skipped\"\n\ninterface ScaffoldTarget {\n readonly label: string\n readonly absolutePath: string\n readonly content: string\n}\n\ninterface ScaffoldResult {\n readonly target: ScaffoldTarget\n readonly outcome: WriteOutcome\n}\n\ninterface InitReport {\n readonly results: readonly ScaffoldResult[]\n readonly schemaRelPath: string\n}\n\n/**\n * Confirms `cwd` is a project (`package.json` present and a JSON object).\n * Throws a message suitable for printing directly on any failure -- every\n * such failure is a preflight failure and nothing is written.\n */\nfunction assertIsProject(cwd: string): void {\n const packageJsonPath = path.join(cwd, \"package.json\")\n if (!existsSync(packageJsonPath)) {\n throw new Error(`no package.json found at ${packageJsonPath} -- run \\`npm init\\` first.`)\n }\n let parsed: unknown\n try {\n // Stryker disable next-line StringLiteral: hand-verified equivalent --\n // `readFileSync(path, \"\")` (the mutant) falls back to returning a\n // `Buffer` (an empty string isn't a recognized encoding), but\n // `JSON.parse` calls `.toString()` on any non-string input, which\n // defaults to utf8 for a `Buffer` -- so both encodings produce an\n // identical `JSON.parse` result for any file content this function can\n // ever see. Confirmed directly: `JSON.parse(readFileSync(p, \"\"))` on a\n // real UTF-8 JSON file parses identically to `JSON.parse(readFileSync(p,\n // \"utf8\"))`.\n parsed = JSON.parse(readFileSync(packageJsonPath, \"utf8\"))\n } catch {\n // No binding: the SyntaxError carries only a char offset, nothing the\n // caller needs beyond \"the file at this path isn't valid JSON\".\n throw new Error(`package.json at ${packageJsonPath} is not valid JSON.`)\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new Error(`package.json at ${packageJsonPath} must contain a top-level object.`)\n }\n}\n\n/** `src/` if it already exists as a directory, otherwise the project root -- where the starter schema goes. */\nfunction schemaDirectory(cwd: string): string {\n const srcDir = path.join(cwd, \"src\")\n return existsSync(srcDir) && statSync(srcDir).isDirectory() ? srcDir : cwd\n}\n\n/**\n * Computes the two scaffold targets and rejects any whose path is already\n * blocked by a wrong-typed entry (a directory where a file must go, or a\n * non-directory where `scripts/` must go). A failure here means zero writes.\n */\n// Always exactly two: the schema file and the generator script. Typed as a\n// tuple (not ScaffoldTarget[]) so runInit()'s targets[0] doesn't need a\n// defensive check for a case the fixed literal return below can't produce.\nfunction planTargets(cwd: string): [ScaffoldTarget, ScaffoldTarget] {\n const schemaPath = path.join(schemaDirectory(cwd), \"env.schema.ts\")\n const scriptsDir = path.join(cwd, \"scripts\")\n const generatorPath = path.join(scriptsDir, \"generate-env.mjs\")\n\n for (const filePath of [schemaPath, generatorPath]) {\n if (existsSync(filePath) && statSync(filePath).isDirectory()) {\n throw new Error(`${filePath} already exists and is a directory.`)\n }\n }\n if (existsSync(scriptsDir) && !statSync(scriptsDir).isDirectory()) {\n throw new Error(`${scriptsDir} already exists and is not a directory.`)\n }\n\n return [\n {\n label: path.relative(cwd, schemaPath),\n absolutePath: schemaPath,\n content: schemaTemplate(),\n },\n {\n label: path.relative(cwd, generatorPath),\n absolutePath: generatorPath,\n content: generatorTemplate(),\n },\n ]\n}\n\n/**\n * Writes `content` to `filePath` only if it doesn't already exist, creating\n * parent directories first. Exclusive-create (`\"wx\"`) rather than an\n * existsSync-then-write pair -- the two-step form races between the check\n * and the write; `\"wx\"` makes \"don't overwrite\" atomic. An existing file is\n * never touched -- the conflict is resolved by skipping, never overwriting.\n */\nfunction writeIfAbsent(filePath: string, content: string): WriteOutcome {\n mkdirSync(path.dirname(filePath), { recursive: true })\n try {\n writeFileSync(filePath, content, { flag: \"wx\" })\n return \"created\"\n } catch (error) {\n if (isFileExistsError(error)) return \"skipped\"\n throw error\n }\n}\n\nexport function isFileExistsError(error: unknown): boolean {\n return (\n typeof error === \"object\" && error !== null && (error as { code?: unknown }).code === \"EEXIST\"\n )\n}\n\nfunction runInit(cwd: string): InitReport {\n assertIsProject(cwd)\n const targets = planTargets(cwd)\n const results = targets.map((target) => ({\n target,\n outcome: writeIfAbsent(target.absolutePath, target.content),\n }))\n return { results, schemaRelPath: targets[0].label }\n}\n\n/** The structured `Created:` / `Skipped:` / `Next:` report, as a string (one `console.log`, testable). */\nfunction renderReport(report: InitReport): string {\n const lines: string[] = [\"env-cap initialized\", \"\"]\n\n const created = report.results.filter((r) => r.outcome === \"created\")\n const skipped = report.results.filter((r) => r.outcome === \"skipped\")\n\n if (created.length > 0) {\n lines.push(\"Created:\")\n for (const r of created) lines.push(` + ${r.target.label}`)\n lines.push(\"\")\n }\n if (skipped.length > 0) {\n lines.push(\"Skipped (already exists):\")\n for (const r of skipped) lines.push(` - ${r.target.label}`)\n lines.push(\"\")\n }\n\n const manifestImport = report.schemaRelPath.startsWith(\"src\" + path.sep)\n ? \"./generated/env.manifest.js\"\n : \"./src/generated/env.manifest.js\"\n\n lines.push(\n \"Next:\",\n \" 1. Generate the manifest + docs: node scripts/generate-env.mjs\",\n ' Requires \"typescript\" (>=5) in your project -- it\\'s how env-cap parses',\n \" env.schema.ts by static analysis. Add it if you don't already have it:\",\n \" npm install --save-dev typescript\",\n \" 2. Validate once at app startup:\",\n \"\",\n ' import { validateEnv } from \"@maverickcer/env-cap\"',\n ` import { manifest } from \"${manifestImport}\"`,\n \" await validateEnv({ manifest, values: process.env })\",\n \"\",\n \" 3. Read validated values through the contract: exampleEnv.EXAMPLE_API_URL\",\n \"\",\n \"env-cap init edited no package.json script -- add one if you want, e.g.\",\n ' \"generate:env\": \"node scripts/generate-env.mjs\"',\n )\n\n return lines.join(\"\\n\")\n}\n\n/**\n * `env-cap init` entry. Returns the process exit code; never calls\n * `process.exit`. `rest` is argv already sliced past the `init` token.\n */\nexport function runInitCommand(rest: readonly string[]): number {\n if (rest.includes(\"--help\") || rest.includes(\"-h\")) {\n process.stdout.write(`${usage()}\\n`)\n return 0\n }\n if (rest.length > 0) {\n process.stderr.write(`env-cap init takes no arguments (got: ${rest.join(\" \")})\\n\\n${usage()}\\n`)\n return 1\n }\n\n try {\n process.stdout.write(`${renderReport(runInit(process.cwd()))}\\n`)\n return 0\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n process.stderr.write(`env-cap init failed: ${message}\\n`)\n return 1\n }\n}\n","import type { CompatibilityIssue, GenerateEnvArtifactsResult } from \"../build/index.js\"\n// Imported from the leaf module, not the `../build/index.js` barrel: pulling\n// in the barrel here would eagerly load its full build-time surface --\n// (indirectly) `typescript`, an optional peer dependency -- just to read a\n// version string, for EVERY CLI invocation this module is part of\n// (including `env-cap init` and `env-cap --help`, neither of which touches\n// build-time analysis at all). See the identical fix, and its regression\n// test, on src/cli/index.ts's own former static `../build/index.js` import.\nimport { readToolVersion } from \"../build/tool-version.js\"\n\n/**\n * `--json`'s machine-readable contract lives here, in one place, so it's\n * unit/snapshot-testable without going through `main()`'s stdout spying and\n * doesn't make the CLI's control-flow function the de facto owner of a\n * public contract. See ADR 0013.\n */\n\n/** Bump only when a consumer written for the previous version could\n * misinterpret the new payload (a field changes type/meaning, or is\n * removed) -- NOT for every additive field. See ADR 0013. */\nexport const JSON_SCHEMA_VERSION = 1\n\n// One version source, shared with the `./build` entry -- `readToolVersion()`\n// returns `tsup`'s build-time constant, so the CLI never reads its own\n// manifest at runtime. See ADR 0040.\nconst TOOL_VERSION: string = readToolVersion()\n\n/**\n * Which passes this invocation actually asked for -- recorded explicitly so a\n * consumer never has to infer intent from which top-level keys happen to be\n * present.\n *\n * @remarks\n * Without this, `\"manifest\": undefined` is genuinely ambiguous: it could mean\n * \"no `--location` was passed\" or \"the manifest pass ran and produced\n * nothing,\" and telling those apart required knowing which CLI flags the run\n * was invoked with -- information the envelope itself never carried. A CI step\n * gating on \"did the docs pass run?\" would otherwise have to reconstruct the\n * command line. `evidence` records the request specifically (the model itself\n * is always computed, per ADR 0038, but only *included* in this envelope on\n * request -- see `JsonSuccessPayload.evidence`).\n */\nexport interface JsonRequestedPasses {\n /** `--location` was passed. */\n readonly manifest: boolean\n /** `--docs` was passed. */\n readonly docs: boolean\n /** `--ownership` was passed. */\n readonly usage: boolean\n /** `--evidence` was passed. */\n readonly evidence: boolean\n}\n\n/** The `--json` envelope for a successful run (generation completed without throwing). */\nexport interface JsonSuccessPayload extends Omit<GenerateEnvArtifactsResult, \"evidence\"> {\n readonly schemaVersion: typeof JSON_SCHEMA_VERSION\n readonly kind: \"env-cap-report\"\n readonly toolVersion: string\n readonly ok: true\n /** Which passes this invocation requested -- always present, so \"not requested\" is never confused with \"computed empty.\" See {@link JsonRequestedPasses}. */\n readonly requested: JsonRequestedPasses\n /** Present only when the caller actually requested `--evidence` --\n * `GenerateEnvArtifactsResult.evidence` itself is always populated (ADR\n * 0038, \"free to compute, always real\"), but the `--json` envelope omits\n * it by default so an ordinary `--location`/`--docs`/`--ownership` report\n * doesn't silently grow by the full evidence model every time. */\n readonly evidence?: GenerateEnvArtifactsResult[\"evidence\"]\n /** Present only when invoked with --check. Governs --check's own pass/fail\n * exit code, independent of this envelope's top-level `ok` (which keeps\n * its existing, unrelated meaning: \"did generation complete without\n * throwing\"). See ADR 0016. */\n readonly checkResult?: { readonly ok: boolean; readonly stale: readonly string[] }\n}\n\n/** A thrown error's shape in the `--json` envelope. */\nexport interface JsonErrorInfo {\n readonly name: string\n readonly message: string\n /** Populated only when the thrown error carries a `CompatibilityIssue[]` (the generator errors in `build/errors.ts` all do). */\n readonly issues?: readonly CompatibilityIssue[]\n}\n\n/** The `--json` envelope for a failed run (generation threw). */\nexport interface JsonErrorPayload {\n readonly schemaVersion: typeof JSON_SCHEMA_VERSION\n readonly kind: \"env-cap-report\"\n readonly toolVersion: string\n readonly ok: false\n readonly error: JsonErrorInfo\n}\n\nfunction hasIssues(error: unknown): error is { issues: readonly CompatibilityIssue[] } {\n return (\n typeof error === \"object\" &&\n error !== null &&\n Array.isArray((error as { issues?: unknown }).issues)\n )\n}\n\n/**\n * Wraps a completed {@link generateEnvArtifacts} result in the `--json`\n * success envelope. `includeEvidence` (default `false`) controls whether\n * `result.evidence` -- always populated on `result` itself, per ADR 0038 --\n * is actually included in the envelope; the CLI passes `true` only when the\n * caller requested `--evidence`.\n *\n * `requested` is supplied by the caller rather than inferred from `result`'s\n * own populated keys -- inferring it would reproduce exactly the ambiguity\n * this field exists to remove (see {@link JsonRequestedPasses}). It defaults\n * to deriving each pass from whether its result is present, which is correct\n * for a normal generate run and keeps this callable from a test without\n * threading flags through; the CLI always passes the real flags.\n */\nexport function serializeSuccess(\n result: Omit<GenerateEnvArtifactsResult, \"evidence\"> &\n Partial<Pick<GenerateEnvArtifactsResult, \"evidence\">>,\n checkResult?: { readonly ok: boolean; readonly stale: readonly string[] },\n includeEvidence = false,\n requested?: JsonRequestedPasses,\n): JsonSuccessPayload {\n const { evidence, ...rest } = result\n return {\n schemaVersion: JSON_SCHEMA_VERSION,\n kind: \"env-cap-report\",\n toolVersion: TOOL_VERSION,\n ok: true,\n requested: requested ?? {\n manifest: rest.manifest !== undefined,\n docs: rest.docs !== undefined,\n usage: rest.usage !== undefined,\n evidence: includeEvidence,\n },\n ...rest,\n ...(includeEvidence ? { evidence } : {}),\n ...(checkResult ? { checkResult } : {}),\n }\n}\n\n/** Wraps a thrown error in the `--json` failure envelope. */\nexport function serializeFailure(error: unknown): JsonErrorPayload {\n return {\n schemaVersion: JSON_SCHEMA_VERSION,\n kind: \"env-cap-report\",\n toolVersion: TOOL_VERSION,\n ok: false,\n error: {\n name: error instanceof Error ? error.name : \"Error\",\n message: error instanceof Error ? error.message : String(error),\n // exactOptionalPropertyTypes: omit the key rather than set it to\n // `undefined` when the thrown error carries no issues of its own.\n ...(hasIssues(error) ? { issues: error.issues } : {}),\n },\n }\n}\n\n/**\n * The complete `--json` envelope shape, success or failure -- the target\n * type the published JSON Schema (`schemas/env-cap-report.schema.json`,\n * `npm run schema`) is generated from. See ADR 0019.\n */\nexport type JsonReportPayload = JsonSuccessPayload | JsonErrorPayload\n\n/** Writes a `--json` envelope to stdout, pretty-printed with a trailing newline. */\nexport function writeJson(payload: JsonReportPayload): void {\n process.stdout.write(`${JSON.stringify(payload, null, 2)}\\n`)\n}\n"],"mappings":";kDAAA,OAAS,iBAAoB,KAC7B,OAAS,kBAAqB,MCD9B,OAAO,OAAQ,cA0Bf,SAAS,SAASA,MAAc,SAAmC,CACjE,OAAO,GAAG,SAASA,MAAM,QAAQ,CACnC,CAEA,SAAS,UAAUA,MAAc,KAAc,SAAiC,CAC9E,OAAO,GAAG,UAAUA,MAAM,KAAM,QAAQ,CAC1C,CAEA,eAAe,MAAMA,MAAc,QAA6C,CAC9E,MAAM,GAAG,MAAMA,MAAM,OAAO,CAC9B,CAEA,SAAS,QAAQA,MAAc,QAA0D,CACvF,OAAO,GAAG,QAAQA,MAAM,OAAO,CACjC,CAEA,SAAS,KAAKA,MAAmC,CAC/C,OAAO,GAAG,KAAKA,KAAI,CACrB,CAEA,SAAS,SAASA,MAA+B,CAC/C,OAAO,GAAG,SAASA,KAAI,CACzB,CASO,IAAM,oBAAuC,CACl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AAQ,SAAW,EACnB,MACF,CAEA,MAAO,KAAK,MAAQ,aAAa,IAAI,EAAI,gBAAgB,IAAI,EAC/D,CAeO,SAAS,cAAmC,CACjD,MAAM,MAAQ,QAAQ,KAAK,CAAC,EAC5B,GAAI,CAAC,MAAO,OAAO,OACnB,GAAI,CACF,OAAO,cAAc,aAAa,KAAK,CAAC,EAAE,IAC5C,MAAQ,CACN,OAAO,cAAc,KAAK,EAAE,IAC9B,CACF,CAEA,IAAM,YAAc,YAAY,MAAQ,aAAa,EAErD,GAAI,YAAa,CACf,KAAK,EAAE,MAAO,OAAmB,CAC/B,MAAM,QAAU,iBAAiB,MAAQ,MAAM,QAAU,OAAO,KAAK,EACrE,QAAQ,OAAO,MAAM,GAAG,OAAO;AAAA,CAAI,EACnC,QAAQ,SAAW,CACrB,CAAC,CACH","names":["path","usage"]}
1
+ {"version":3,"sources":["../../src/cli/index.ts","../../src/cli/filesystem.ts","../../src/cli/init.ts","../../src/cli/json.ts"],"sourcesContent":["import { realpathSync } from \"node:fs\"\nimport { pathToFileURL } from \"node:url\"\nimport type {\n generateEnvArtifacts,\n CheckEnvArtifactsResult,\n ContractModelContract,\n ManifestChangeReport,\n} from \"../build/index.js\"\nimport { nodeBuildFileSystem } from \"./filesystem.js\"\nimport { runInitCommand } from \"./init.js\"\nimport type { JsonRequestedPasses } from \"./json.js\"\nimport { serializeFailure, serializeSuccess, writeJson } from \"./json.js\"\n\n/**\n * Thin, optional CLI wrapper around `generateEnvArtifacts()`. Nothing here is\n * required for library usage -- `generateEnvManifest`/`generateDocumentation`/\n * `generateUsageReport`/`generateEnvArtifacts` are fully usable as plain imports\n * from npm scripts, bundler plugins, or CI steps without this file.\n *\n * `../build/index.js` (and, transitively, `typescript`) is imported here as\n * TYPES ONLY at module scope, and loaded with a dynamic `import()` inside\n * `runCheckMode`/`runGenerateMode` instead of a static top-level import.\n * `typescript` is an optional peer dependency (README: \"TypeScript 5+ is\n * only required for build-time manifest generation\"), but a static import\n * is evaluated eagerly for every invocation of this file, including\n * `env-cap init` and `env-cap --help` -- neither of which touches\n * `../build/index.js` at all. Without this split, a fresh install with no\n * `typescript` present threw `ERR_MODULE_NOT_FOUND: Cannot find package\n * 'typescript'` on `env-cap init`, before `runInitCommand` (pure `node:fs`,\n * no TypeScript dependency -- see ADR 0042) ever ran.\n */\n\n/** Parsed CLI flags -- see `helpText()` below for what each one means. */\nexport interface ParsedArgs {\n root?: string\n location?: string\n include: string[]\n exclude: string[]\n packages: string[]\n tsconfig?: string | false\n evidence?: string\n strict: boolean\n strictDocs: boolean\n strictOwnership: boolean\n json: boolean\n check: boolean\n help: boolean\n}\n\n// Every VALUE_FLAGS/BOOL_FLAGS entry below is a named function declaration,\n// not an inline arrow inside the dispatch table object literals -- Stryker\n// marks a module-level object literal's own arrow-shorthand properties\n// `static: true` (evaluated once at module load), which can produce a false\n// \"Survived\" on a mutant that real tests genuinely reach and would fail\n// against, even though `ignoreStatic` only suppresses a static mutant with\n// *zero* coverage (this one has real coverage, just misattributed). Named\n// function declarations don't have this problem -- their bodies are ordinary\n// function-scope code, attributed normally. See the identical fix already\n// applied to `check-artifacts.ts`/`reference-projections.ts`'s `defineX({...})`\n// schema objects.\nfunction setRoot(a: ParsedArgs, v: string): void {\n a.root = v\n}\nfunction setLocation(a: ParsedArgs, v: string): void {\n a.location = v\n}\nfunction pushInclude(a: ParsedArgs, v: string): void {\n a.include.push(v)\n}\nfunction pushExclude(a: ParsedArgs, v: string): void {\n a.exclude.push(v)\n}\nfunction pushPackage(a: ParsedArgs, v: string): void {\n a.packages.push(v)\n}\nfunction setTsconfig(a: ParsedArgs, v: string): void {\n a.tsconfig = v\n}\nfunction setEvidence(a: ParsedArgs, v: string): void {\n a.evidence = v\n}\n\n/** Flags that consume the following argv token. A table, not a `switch`, so `parseArgs` stays a flat dispatch loop -- one branch per *kind* of flag. */\nconst VALUE_FLAGS: Readonly<Partial<Record<string, (args: ParsedArgs, value: string) => void>>> = {\n \"--root\": setRoot,\n \"--location\": setLocation,\n \"--include\": pushInclude,\n \"--exclude\": pushExclude,\n \"--package\": pushPackage,\n \"--tsconfig\": setTsconfig,\n \"--evidence\": setEvidence,\n}\n\nfunction setNoTsconfig(a: ParsedArgs): void {\n a.tsconfig = false\n}\nfunction setStrict(a: ParsedArgs): void {\n a.strict = true\n}\nfunction setStrictDocs(a: ParsedArgs): void {\n a.strictDocs = true\n}\nfunction setStrictOwnership(a: ParsedArgs): void {\n a.strictOwnership = true\n}\nfunction setJson(a: ParsedArgs): void {\n a.json = true\n}\nfunction setCheck(a: ParsedArgs): void {\n a.check = true\n}\nfunction setHelp(a: ParsedArgs): void {\n a.help = true\n}\n\n/** Flags that set a boolean and consume nothing further. */\n// This object literal itself is `static: true` (built once at module load),\n// which Stryker can misattribute a false \"Survived\" to even though it's\n// genuinely, heavily test-covered -- NOT an equivalent mutant. Hand-verified:\n// replacing this whole literal with `{}` and running the real suite\n// (`vitest run`, whole package) fails 21 tests across 2 files (every test\n// exercising `--strict`/`--json`/`--check`/`--help`/etc.), each throwing\n// \"Unknown argument\" instead of setting the flag. Extracting each entry to\n// its own named function (see above) already fixed the same class of false\n// \"Survived\" for every individual entry's own body; this fixes the entries,\n// the wrapper object literal's own collapse-to-`{}` mutant is a second,\n// distinct static-attribution target that the same fix doesn't reach.\n// Stryker disable next-line ObjectLiteral\nconst BOOL_FLAGS: Readonly<Partial<Record<string, (args: ParsedArgs) => void>>> = {\n \"--no-tsconfig\": setNoTsconfig,\n \"--strict\": setStrict,\n \"--strict-docs\": setStrictDocs,\n \"--strict-ownership\": setStrictOwnership,\n \"--json\": setJson,\n \"--check\": setCheck,\n \"--help\": setHelp,\n \"-h\": setHelp,\n}\n\n/**\n * Parses `process.argv` (already sliced past the `node`/script path) into `ParsedArgs`.\n *\n * @throws {Error} On an unrecognized flag, or a flag missing its required value.\n */\nexport function parseArgs(argv: string[]): ParsedArgs {\n const args: ParsedArgs = {\n include: [],\n exclude: [],\n packages: [],\n strict: false,\n strictDocs: false,\n strictOwnership: false,\n json: false,\n check: false,\n help: false,\n }\n\n // A fast-failing pass-count guard, independent of `i` itself: on any real\n // input `i` strictly advances toward `argv.length` every pass (the loop's\n // own `i++`, plus an extra `++i` when a value flag consumes its argument),\n // so no correct input ever needs more passes than `argv.length`. A mutation\n // that reverses the loop's own advance (`i++` -> `i--`) makes `i` walk\n // *away* from `argv.length` instead -- an infinite loop that produces no\n // observably wrong result for an assertion-based test to catch, only a hang\n // until Stryker's own mutant timeout. This counter climbs every pass\n // regardless of `i`'s (possibly-mutated) motion, so it still reaches its\n // bound and throws an ordinary, fast error instead.\n let passes = 0\n // The guard's own arithmetic/direction/comparison below are just as\n // unreachable/inconsequential for any correct `argv` as the guard body\n // itself (see the disable comment on the `if` below): under correct code\n // `passes` never approaches `maxPasses`, so no real test input can observe\n // a change to any of them.\n // Stryker disable next-line ArithmeticOperator\n const maxPasses = argv.length * 2 + 4\n for (let i = 0; i < argv.length; i++) {\n // Stryker disable next-line UpdateOperator\n passes++\n // Unreachable by design for any correct `argv`, the same way the\n // `arg = argv[i] ?? \"\"` fallback just below is: this guard's whole\n // purpose is to fail fast when a *mutated* build's loop-advance is\n // broken, so no real test input (which only ever exercises correct\n // code) can reach it. A test that reached it would itself require an\n // already-broken build to construct.\n // Stryker disable next-line BlockStatement,ConditionalExpression,EqualityOperator\n if (passes > maxPasses) {\n // Stryker disable next-line CallExpression\n throw new Error(\n // Stryker disable next-line StringLiteral\n `parseArgs: exceeded ${String(maxPasses)} iterations parsing ${String(argv.length)} argument(s) -- this should never happen for any real argv and indicates an internal parsing bug.`,\n )\n }\n // Provably unreachable for any real `string[]` input: the loop condition\n // `i < argv.length` guarantees `argv[i]` is in-bounds (hence defined)\n // every time this line runs, whether `i` just advanced by the outer\n // `i++` or by a value flag's own `++i` above -- `noUncheckedIndexedAccess`\n // isn't enabled, so TypeScript doesn't force this fallback either; it's\n // pure runtime defense against an out-of-bounds access that can't\n // actually occur. Hand-verified: replacing the fallback string and\n // running the real suite (`vitest run` across all of test/cli/) passes\n // unchanged.\n // Stryker disable next-line StringLiteral\n const arg = argv[i] ?? \"\"\n const valueFlag = VALUE_FLAGS[arg]\n if (valueFlag) {\n valueFlag(args, nonEmpty(argv[++i], arg))\n continue\n }\n const boolFlag = BOOL_FLAGS[arg]\n if (boolFlag) {\n boolFlag(args)\n continue\n }\n throw new Error(`Unknown argument: ${arg}`)\n }\n\n return args\n}\n\n/** Requires `value` (the argument immediately following `flag`) to be a non-empty string; throws otherwise. */\nfunction nonEmpty(value: string | undefined, flag: string): string {\n if (!value) throw new Error(`${flag} requires a value.`)\n return value\n}\n\n// A function, not a module-level `const` -- Stryker marks a module-level\n// template-literal `static: true` (evaluated once at import time), which can\n// under-attribute a real, test-covered mutant to a false \"Survived\" the same\n// way the VALUE_FLAGS/BOOL_FLAGS dispatch tables above did. Returning it from\n// a function makes the template literal ordinary function-scope code,\n// evaluated (and attributed) fresh on each of `main()`'s two call sites.\nfunction helpText(): string {\n return `env-cap - generate a manifest and/or a persisted evidence artifact from discovered env.schema.ts contracts\n\nUsage:\n env-cap init\n env-cap [--location <path>] [--evidence <path>] [options]\n\n init Scaffold a minimal starting point (one env.schema.ts + a generate script); run \\`env-cap init --help\\` for details\n\nAt least one of --location or --evidence is required (for a non-init invocation).\n\nOptions:\n --root <path> Directory to resolve globs from (default: cwd)\n --location <path> Output path for the generated manifest\n --include <glob> Schema-discovery glob (repeatable, default: **/env.schema.ts)\n --exclude <glob> Glob pattern to exclude (repeatable)\n --package <name> Installed package name to also discover a schema from, via its \"envCap.schema\" package.json field (repeatable)\n --tsconfig <path> Path to a tsconfig.json (relative to root) whose \"paths\"/\"baseUrl\" resolve aliased imports encountered during static analysis (default: auto-detected \"tsconfig.json\" at root)\n --no-tsconfig Disable tsconfig path-alias resolution entirely\n --evidence <path> Also emit the persisted evidence artifact (the full EvidenceModel, plus a paired .fingerprint sidecar) at this path, e.g. docs/env.evidence.json (see ADR 0038). Independent of --location -- needs no other pass.\n --strict Escalate every pass's warning findings to hard errors -- compatibility (manifest pass -- ADR 0009's provable exclusive-group/compatibility errors), documentation, and ownership alike (ADR 0044). Nothing is written when it fires. Info-severity findings are never escalated. Equivalent to passing all three scoped flags below at once.\n --strict-docs Escalate every documentation-family warning (undocumented contract/variable, stale doc entry, expiring/expired entry, unresolvable documentEnv() link) to a hard error, independent of --strict. Nothing is written when it fires. Info-severity findings are never escalated.\n --strict-ownership Escalate every ownership-family warning (abandoned contract, unresolved consumer, unconsumed owned variable, indeterminate ownership, stale/missing dynamicAccess citation) to a hard error, independent of --strict. Nothing is written when it fires. Info-severity findings are never escalated.\n --json Emit a machine-readable JSON report instead of formatted text (see ADR 0013)\n --check Verify generated artifacts are up to date without writing anything; exits 1 if any is stale or missing (see ADR 0016)\n --help Show this message\n\nDocumentation (a rich Markdown catalog), a dependency & ownership report, and\na reconciled .env.example are no longer generated by this CLI -- they have no\nruntime consumer, so generating them is application-level code now, not a CLI\nconcern. Call \\`computeDocumentation\\`/\\`writeDocumentation\\`/\\`computeUsage\\`/\n\\`writeUsageReport\\` (or the higher-level \\`generateDocumentation\\`/\n\\`generateUsageReport\\` orchestrators) directly from \\`env-cap/build\\` in your\nown build script -- see \\`examples/nextjs-app/scripts/generate-docs\\` for a\nworked example, and specs/decisions/0046-cli-restricted-to-runtime-and-evidence-output.md\nfor why.\n`\n}\n\n/** @internal Exported for direct unit coverage -- reached through `main()`'s `--evidence` flow in production, but that path alone can't isolate this from `contractNameResolver()`/`writeEvidenceChanges()`'s own logic, nor cheaply exercise every field-change/added/updated/removed shape without a full real generation run per case. */\nexport function formatFieldChanges(\n changes: ManifestChangeReport[\"updatedContracts\"][number][\"changes\"],\n): string {\n return changes\n .map((c) => `${c.field} (${c.previous ?? \"unset\"} -> ${c.current ?? \"unset\"})`)\n .join(\", \")\n}\n\n/**\n * Mirrors `docs.ts`'s \"Changes since last report\" section: a fixed\n * Added/Updated/Removed order, each printed only when non-empty, \"No\n * changes.\" when all three are empty -- printed whenever `--evidence` was\n * requested, not only when something actually changed. See ADR 0038 (the\n * persisted evidence artifact -- not the manifest itself, which no longer\n * tracks its own change history; see ADR 0021's now-superseded design).\n */\n/**\n * Resolves a `${file}#${exportName}` reference to the contract's display\n * name, from `ContractModel` -- the one model that owns it. A change-report\n * ref carries identity only (see `ContractRef`), so this is the lookup any\n * renderer needing prose performs; a removed contract has no entry in the\n * *current* model at all, which is exactly why this falls back to the export\n * name rather than assuming one exists.\n */\n/** @internal Exported for direct unit coverage -- see {@link formatFieldChanges}'s own doc comment for why. */\nexport function contractNameResolver(\n contracts: readonly ContractModelContract[],\n): (ref: { file: string; exportName: string }) => string {\n const byIdentity = new Map(contracts.map((c) => [`${c.file}#${c.exportName}`, c.contractName]))\n return (ref) => byIdentity.get(`${ref.file}#${ref.exportName}`) ?? ref.exportName\n}\n\n/** @internal Exported for direct unit coverage -- see {@link formatFieldChanges}'s own doc comment for why. */\nexport function writeEvidenceChanges(\n changes: ManifestChangeReport,\n contracts: readonly ContractModelContract[],\n): void {\n const nameOf = contractNameResolver(contracts)\n const hasAdded = changes.addedContracts.length > 0 || changes.addedVariables.length > 0\n const hasUpdated = changes.updatedContracts.length > 0 || changes.updatedVariables.length > 0\n const hasRemoved = changes.removedContracts.length > 0 || changes.removedVariables.length > 0\n\n process.stdout.write(\"\\nEvidence changes since the last persisted snapshot:\\n\")\n if (!hasAdded && !hasUpdated && !hasRemoved) {\n process.stdout.write(\" No changes.\\n\")\n return\n }\n\n if (hasAdded) {\n process.stdout.write(\" Added:\\n\")\n for (const c of changes.addedContracts)\n process.stdout.write(` - contract \"${nameOf(c)}\" (${c.file})\\n`)\n for (const v of changes.addedVariables)\n process.stdout.write(` - ${v.key} in \"${nameOf(v)}\"\\n`)\n }\n if (hasUpdated) {\n process.stdout.write(\" Updated:\\n\")\n for (const c of changes.updatedContracts)\n process.stdout.write(` - contract \"${nameOf(c)}\": ${formatFieldChanges(c.changes)}\\n`)\n for (const v of changes.updatedVariables)\n process.stdout.write(` - ${v.key} in \"${nameOf(v)}\": ${formatFieldChanges(v.changes)}\\n`)\n }\n if (hasRemoved) {\n process.stdout.write(\" Removed:\\n\")\n for (const c of changes.removedContracts)\n process.stdout.write(` - contract \"${nameOf(c)}\" (${c.file})\\n`)\n for (const v of changes.removedVariables)\n process.stdout.write(` - ${v.key} in \"${nameOf(v)}\"\\n`)\n }\n}\n\n/**\n * Which passes this invocation asked for, straight off the parsed flags --\n * never inferred from which results came back populated, which is exactly the\n * ambiguity `requested` exists to remove. See `JsonRequestedPasses`.\n */\n/** @internal Exported for direct unit coverage -- see {@link formatFieldChanges}'s own doc comment for why. */\nexport function requestedPasses(args: ParsedArgs): JsonRequestedPasses {\n return {\n manifest: args.location !== undefined,\n // The CLI can no longer request either pass -- `--docs`/`--ownership`\n // were removed (see specs/decisions/0046-cli-restricted-to-runtime-and-evidence-output.md);\n // `JsonRequestedPasses` keeps both fields, unchanged in shape, for\n // `--json` schema compatibility (see JSON_SCHEMA_VERSION's own doc\n // comment -- an unused-but-still-`false` field is additive, not a\n // meaning change), always reporting them as not requested.\n docs: false,\n usage: false,\n evidence: args.evidence !== undefined,\n }\n}\n\n/**\n * The CLI entry point: parses argv, runs `--check` or a real generate, and writes either\n * human-readable text or (`--json`) a machine-readable report to stdout, setting\n * `process.exitCode` accordingly (see ADR 0013 for the JSON report contract).\n */\n/**\n * The full `GenerateEnvArtifactsOptions` object, built once from parsed args --\n * `checkEnvArtifacts` and `generateEnvArtifacts` take the same type, so both\n * call sites use this directly. `evidence` is included: `--check --evidence`\n * verifies the persisted evidence artifact for drift too, exactly as `--check`\n * already does for the manifest artifact.\n */\n/**\n * Whether a findings group escalates to a hard error: when bare `--strict`\n * is on (ADR 0044 -- `--strict` alone means every group), or when the\n * group-specific `--strict-*` flag is. One place so every group's\n * escalation reads identically, matching `@maverickcer/data-cap`'s own\n * `groupEscalates` (`src/build/generate-data-artifacts.ts`).\n */\nfunction groupEscalates(strict: boolean, specificFlag: boolean): boolean {\n return strict || specificFlag\n}\n\n/** @internal Exported for direct unit coverage -- see {@link formatFieldChanges}'s own doc comment for why. */\nexport function artifactOptions(args: ParsedArgs) {\n const listOrUndefined = (list: string[]): string[] | undefined =>\n list.length > 0 ? list : undefined\n return {\n // The deliberate injection boundary: the CLI (an executable consumer)\n // hands `env-cap/build` (a library surface) its filesystem capability.\n // See src/cli/filesystem.ts and ADR 0040.\n fs: nodeBuildFileSystem,\n root: args.root,\n include: listOrUndefined(args.include),\n exclude: listOrUndefined(args.exclude),\n packages: listOrUndefined(args.packages),\n tsconfig: args.tsconfig,\n manifest: args.location\n ? {\n location: args.location,\n onIncompatibility: args.strict ? (\"throw\" as const) : (\"warn\" as const),\n }\n : (false as const),\n // `docs`/`usage` are deliberately omitted (not set to `false`): the CLI\n // no longer has `--docs`/`--ownership` flags to derive them from, and\n // omitting an optional `GenerateEnvArtifactsOptions` field is already\n // equivalent to passing `false` (`computeArtifacts()`'s `options.docs\n // === false ? undefined : options.docs` treats a missing key and an\n // explicit `false` identically). `computeDocumentation`/`computeUsage`\n // themselves still run unconditionally inside `generateEnvArtifacts()`\n // -- Finding Model needs both regardless (ADR 0038) -- only the CLI's\n // ability to ALSO write a docs/ownership artifact is gone. See\n // specs/decisions/0046-cli-restricted-to-runtime-and-evidence-output.md.\n evidence: args.evidence ? { location: args.evidence } : (false as const),\n onUndocumented: groupEscalates(args.strict, args.strictDocs)\n ? (\"throw\" as const)\n : (\"warn\" as const),\n onOwnershipIssue: groupEscalates(args.strict, args.strictOwnership)\n ? (\"throw\" as const)\n : (\"warn\" as const),\n }\n}\n\n/** `if (items.length) { write header; write \" - <render(item)>\" per item }` -- the summary-list shape `main`'s generate output repeats ~15 times. */\n/** @internal Exported for direct unit coverage -- see {@link formatFieldChanges}'s own doc comment for why. */\nexport function printList<T>(\n items: readonly T[],\n header: string,\n render: (item: T) => string,\n): void {\n if (items.length === 0) return\n process.stdout.write(`\\n${header}\\n`)\n for (const item of items) process.stdout.write(` - ${render(item)}\\n`)\n}\n\n/** `--check`: verify every requested artifact for drift, write nothing, exit non-zero on any stale/missing. */\nasync function runCheckMode(args: ParsedArgs): Promise<void> {\n let checkResult: CheckEnvArtifactsResult\n try {\n const { checkEnvArtifacts } = await import(\"../build/index.js\")\n checkResult = await checkEnvArtifacts(artifactOptions(args))\n } catch (error) {\n if (!args.json) throw error\n writeJson(serializeFailure(error))\n process.exitCode = 1\n return\n }\n\n const stale = checkResult.findings.filter((f) => f.status !== \"ok\").map((f) => f.artifact)\n if (args.json) {\n // Both the `{manifest,docs,usage: undefined}` object and the `false`\n // (`includeEvidence`) argument below are equivalent at this call site:\n // `serializeSuccess()` only ever spreads these into its return payload\n // (`...rest`, `...(includeEvidence ? {evidence} : {})`), and `writeJson`\n // serializes the result through `JSON.stringify`, which drops an\n // `undefined`-valued key exactly like a MISSING key -- so `{}` (every\n // field implicitly undefined) and `{manifest: undefined, ...}` (every\n // field explicitly undefined) serialize identically, and\n // `includeEvidence: true` would only add `evidence: undefined` (`result`\n // here has no `evidence` property to destructure), equally dropped.\n // `requested` is passed explicitly right below, so `serializeSuccess`'s\n // own `rest.manifest !== undefined`-based default (which WOULD\n // distinguish `{}` from explicit `undefined`s) is never reached from\n // this call site either. Hand-verified: mutating both together (`{}`,\n // `true`) and running the real whole-package suite (`vitest run`)\n // passes unchanged.\n // Stryker disable ObjectLiteral,BooleanLiteral\n writeJson(\n serializeSuccess(\n { manifest: undefined, docs: undefined, usage: undefined },\n { ok: checkResult.ok, stale },\n false,\n // `--check` writes nothing, so every result above is undefined by\n // construction -- `requested` is the only thing distinguishing \"this run\n // checked the docs artifact\" from \"it didn't.\"\n requestedPasses(args),\n ),\n )\n // Stryker restore ObjectLiteral,BooleanLiteral\n } else {\n process.stdout.write(\"Checking for drift (--check: nothing will be written)...\\n\\n\")\n for (const f of checkResult.findings) {\n process.stdout.write(\n ` ${f.artifact.padEnd(10)} ${f.path.padEnd(50)} ${f.status.toUpperCase()}${f.detail ? ` (${f.detail})` : \"\"}\\n`,\n )\n }\n process.stdout.write(\n checkResult.ok\n ? \"\\nAll generated artifacts are up to date.\\n\"\n : `\\n${stale.length} artifact(s) are stale or missing. Run without --check to regenerate.\\n`,\n )\n }\n process.exitCode = checkResult.ok ? 0 : 1\n}\n\ntype GenerateResult = Awaited<ReturnType<typeof generateEnvArtifacts>>\n\n/** The human-readable manifest section of a generate run's summary. */\n/** @internal Exported for direct unit coverage -- see {@link formatFieldChanges}'s own doc comment for why. */\nexport function printManifestSummary(manifest: NonNullable<GenerateResult[\"manifest\"]>): void {\n process.stdout.write(`Wrote manifest: ${manifest.outputPath}\\n`)\n process.stdout.write(`Discovered ${String(manifest.contracts.length)} contract(s).\\n`)\n printList(\n manifest.warnings,\n `${String(manifest.warnings.length)} compatibility warning(s):`,\n (w) => `${w.code ? `[${w.code}] ` : \"\"}${w.variable}: ${w.reason}`,\n )\n printList(\n manifest.parseWarnings,\n `${String(manifest.parseWarnings.length)} parse warning(s):`,\n (w) => `${w.file}: ${w.message}`,\n )\n}\n\n// `printDocsSummary()`/`printUsageSummary()` (the docs/env-example and\n// dependency-ownership sections of the human-readable summary) were removed\n// along with `--docs`/`--ownership` themselves: `artifactOptions()` no\n// longer ever populates `GenerateEnvArtifactsOptions.docs`/`.usage`, so\n// `result.docs`/`result.usage` below are now unconditionally `undefined`\n// on every real CLI run -- keeping either function (or its now-permanently-\n// false `if (result.docs)`/`if (result.usage)` call site) would be dead code\n// no CLI-level test could ever legitimately cover. See\n// specs/decisions/0046-cli-restricted-to-runtime-and-evidence-output.md.\n// `computeDocumentation`/`writeDocumentation`/`computeUsage`/\n// `writeUsageReport` themselves are unaffected -- see\n// `examples/nextjs-app/scripts/generate-docs` for the same rendering,\n// now invoked directly as application code instead of through this CLI.\n\n/** A real generate run: write every requested artifact, then print a summary (or `--json` envelope). */\nasync function runGenerateMode(args: ParsedArgs): Promise<void> {\n let result: GenerateResult\n try {\n const { generateEnvArtifacts } = await import(\"../build/index.js\")\n result = await generateEnvArtifacts(artifactOptions(args))\n } catch (error) {\n if (!args.json) throw error // propagates to main().catch() exactly as before\n writeJson(serializeFailure(error))\n process.exitCode = 1\n return\n }\n\n if (args.json) {\n writeJson(\n serializeSuccess(result, undefined, args.evidence !== undefined, requestedPasses(args)),\n )\n return\n }\n\n // Only the manifest pass's own parse warnings feed this banner now --\n // `result.docs`/`result.usage` are always `undefined` from the CLI (see\n // the comment above `runGenerateMode`), so their `parseWarnings`/\n // `unresolvedLinks` terms were removed rather than kept as permanently-0\n // addends.\n const totalWarnings = result.manifest?.parseWarnings.length ?? 0\n if (totalWarnings > 0) {\n process.stdout.write(\n `⚠ ${totalWarnings} unresolved/dropped-schema warning(s) found -- details below. Re-run with --json for a machine-readable report.\\n\\n`,\n )\n }\n\n if (result.manifest) printManifestSummary(result.manifest)\n\n if (args.evidence) {\n process.stdout.write(`Wrote evidence: ${args.evidence}\\n`)\n writeEvidenceChanges(result.evidence.change.manifest, result.evidence.contract.contracts)\n }\n}\n\nexport async function main(): Promise<void> {\n const argv = process.argv.slice(2)\n\n // Subcommand dispatch: `init` as the FIRST positional token routes to the\n // scaffolder. Every existing flag-based invocation is untouched -- no flag\n // is reinterpreted as a subcommand, `--help` alone still prints helpText().\n if (argv[0] === \"init\") {\n process.exitCode = runInitCommand(argv.slice(1))\n return\n }\n\n const args = parseArgs(argv)\n\n if (args.help) {\n process.stdout.write(helpText())\n process.exitCode = 0\n return\n }\n\n if (!args.location && !args.evidence) {\n if (args.json) {\n writeJson(\n serializeFailure(new Error(\"At least one of --location or --evidence is required.\")),\n )\n } else {\n process.stdout.write(helpText())\n }\n process.exitCode = 1\n return\n }\n\n await (args.check ? runCheckMode(args) : runGenerateMode(args))\n}\n\n// Only auto-run when this file is the process entry point, not when a test\n// imports `parseArgs`/`main` directly -- importing this module must never\n// have the side effect of running the CLI.\n//\n// npm installs `bin` entries as symlinks (e.g. `node_modules/.bin/env-cap`\n// -> `../env-cap/dist/cli/index.js`). Node resolves\n// `import.meta.url` through that symlink to this file's real, on-disk path,\n// but leaves `process.argv[1]` as the symlink path it was actually invoked\n// with -- so comparing the two directly never matches for a real `npx`/`.bin`\n// invocation, and the CLI would silently no-op. Resolving `argv[1]` through\n// `realpathSync` first makes the comparison symlink-aware; the try/catch\n// falls back to the unresolved path so this can't itself throw for an\n// argv[1] that doesn't resolve to a real file.\nexport function directRunUrl(): string | undefined {\n const entry = process.argv[1]\n if (!entry) return undefined\n try {\n return pathToFileURL(realpathSync(entry)).href\n } catch {\n return pathToFileURL(entry).href\n }\n}\n\nconst isDirectRun = import.meta.url === directRunUrl()\n\nif (isDirectRun) {\n main().catch((error: unknown) => {\n const message = error instanceof Error ? error.message : String(error)\n process.stderr.write(`${message}\\n`)\n process.exitCode = 1\n })\n}\n","import fs from \"node:fs/promises\"\nimport type { BuildDirent, BuildFileSystem, BuildStats } from \"../build/types.js\"\n\n/**\n * The concrete `node:fs/promises`-backed {@link BuildFileSystem} the `env-cap`\n * CLI hands to `env-cap/build`. Also re-exported as the public\n * `env-cap/node` entry point (`src/node/index.ts`) for a\n * consumer running the generators from their own Node build script.\n *\n * This is the deliberate injection boundary -- mirrors `repo-contract`'s own\n * `repo-contract.config.ts` (`spawn: crossSpawn, env: process.env`): a\n * **library surface** (`./build`) must not acquire filesystem access\n * implicitly; an **executable-context** entry (this CLI, or `./node`)\n * constructs the adapter and passes it in. `src/cli/**` is the sanctioned\n * executable-source carve-out -- `node:fs` lives only here. See ADR 0040.\n *\n * A thin structural pass-through: each method delegates straight to\n * `node:fs/promises`, whose real `Dirent`/`Stats` already satisfy the\n * minimal {@link BuildFileSystem} `BuildDirent`/`BuildStats` shapes.\n *\n * Named `function` declarations, not an object of arrow properties, so each\n * delegation body is a per-call statement a mutation test can actually reach\n * -- an arrow assigned as a property is only evaluated once, at module load,\n * where Stryker's mutant switch can't flip it (the module-level-`Set` trap\n * `build/discover.ts` calls out, in another form).\n */\nfunction readFile(path: string, encoding: \"utf8\"): Promise<string> {\n return fs.readFile(path, encoding)\n}\n\nfunction writeFile(path: string, data: string, encoding: \"utf8\"): Promise<void> {\n return fs.writeFile(path, data, encoding)\n}\n\nasync function mkdir(path: string, options: { recursive: true }): Promise<void> {\n await fs.mkdir(path, options)\n}\n\nfunction readdir(path: string, options: { withFileTypes: true }): Promise<BuildDirent[]> {\n return fs.readdir(path, options)\n}\n\nfunction stat(path: string): Promise<BuildStats> {\n return fs.stat(path)\n}\n\nfunction realpath(path: string): Promise<string> {\n return fs.realpath(path)\n}\n\n// The `{}` mutant here is a module-load-time (static) mutant: once this\n// module is imported and the const is bound, Stryker's per-mutant switch\n// can't re-run the binding, so the mutant can never actually activate --\n// Stryker itself flags it `static: true`. It is plainly non-equivalent (an\n// empty adapter breaks every consumer), just unkillable by the tool. Each\n// delegating function above is individually mutation-covered.\n// Stryker disable next-line ObjectLiteral\nexport const nodeBuildFileSystem: BuildFileSystem = {\n readFile,\n writeFile,\n mkdir,\n readdir,\n stat,\n realpath,\n}\n","import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from \"node:fs\"\nimport path from \"node:path\"\n\n/**\n * `env-cap init` -- scaffolds a minimal, working env-cap starting point into\n * the current project: one discoverable capability contract and one\n * artifact-generation script. Nothing more.\n *\n * Deliberately filesystem-only and non-executing, matching this package's\n * own runtime discipline (ADR 0002, ADR 0040) and repo-contract's `init`:\n * it reads the consumer's `package.json` (to confirm it's a project and to\n * decide `src/` vs. root placement) and writes new files with\n * exclusive-create -- it never runs a subprocess, never invokes a package\n * manager, never mutates `package.json`, never regenerates an artifact, and\n * never reads the ambient environment. Anything the documented workflow\n * still needs afterwards is printed as a `Next:` step, not performed here.\n * See ADR 0042.\n *\n * `src/cli/**` is the sanctioned place for direct `node:fs` use (ADR 0040) --\n * this file is bundled into the `bin` target, exempt from the\n * `verify-no-ambient-fs` tarball guard exactly as `src/cli/index.ts` is.\n */\n\n// USAGE/SCHEMA_TEMPLATE/GENERATOR_TEMPLATE are functions, not module-level\n// `const`s: a module-level const is evaluated once at import time, not per\n// test, so Stryker's perTest coverage analysis can't attribute it to any\n// single test and reports mutants on it Survived/NoCoverage even when tests\n// do exercise the rendered content. A function called at each use site is\n// evaluated during the test itself, which Stryker can attribute correctly.\nfunction usage(): string {\n return `Usage: env-cap init\n\nScaffolds a minimal env-cap starting point into the current directory:\n\n <src>/env.schema.ts a starter capability contract (createEnv + documentEnv)\n scripts/generate-env.mjs a script that generates the manifest + docs artifacts\n\nNever overwrites an existing file, never runs anything, never edits\npackage.json. Everything else -- generating artifacts, wiring validateEnv()\ninto startup -- is printed as a next step. Run generation afterwards with\n\\`node scripts/generate-env.mjs\\` or \\`npx env-cap --location <path>\\`.`\n}\n\nfunction schemaTemplate(): string {\n return `// Starter env-cap capability contract -- expand it: add your real variables,\n// split into per-capability files (e.g. features/<name>/env.schema.ts), or\n// keep everything here. env-cap discovers every **/env.schema.ts by default.\n//\n// createEnv() reads only default/processor/validator/context -- the fields\n// validateEnv() uses at runtime. documentEnv() is a build-time-only marker\n// that feeds the generated docs and ownership report; it is inert at runtime.\n// Keep the object passed to both a static literal -- env-cap resolves it by\n// static analysis and never executes this file.\nimport { createEnv, documentEnv } from \"@maverickcer/env-cap\"\n\nconst schema = {\n EXAMPLE_API_URL: {\n processor: (value: unknown): string => String(value ?? \"\"),\n validator: (value: string) => value.startsWith(\"https://\") || \"Expected an https:// URL.\",\n },\n}\n\nexport const exampleEnv = createEnv(schema, { name: \"example\", source: import.meta.url })\n\ndocumentEnv(schema, {\n owner: \"your-team\",\n variables: {\n EXAMPLE_API_URL: {\n description: \"Base URL for the example upstream API. Replace with a real variable.\",\n required: true,\n },\n },\n})\n`\n}\n\nfunction generatorTemplate(): string {\n return `// Build-time only. Run with \\`node scripts/generate-env.mjs\\`, or wire it into\n// a package.json script (e.g. \"generate:env\"). Never imported by app code.\nimport { generateEnvArtifacts } from \"@maverickcer/env-cap/build\"\nimport { nodeBuildFileSystem } from \"@maverickcer/env-cap/node\"\nimport path from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\n\nconst root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), \"..\")\n\nconst result = await generateEnvArtifacts({\n fs: nodeBuildFileSystem,\n root,\n manifest: { location: \"src/generated/env.manifest.ts\" },\n docs: {\n location: \"docs/ENVIRONMENT.md\",\n envExample: { location: \".env.example\", onExisting: \"keep-sibling\" },\n },\n usage: { report: { location: \"docs/OWNERSHIP.md\" } },\n})\n\nconsole.log(\\`Discovered \\${result.manifest?.contracts.length ?? 0} contract(s).\\`)\nif (result.manifest?.outputPath) console.log(\\`Wrote manifest: \\${result.manifest.outputPath}\\`)\nif (result.docs?.docsPath) console.log(\\`Wrote docs: \\${result.docs.docsPath}\\`)\n`\n}\n\ntype WriteOutcome = \"created\" | \"skipped\"\n\ninterface ScaffoldTarget {\n readonly label: string\n readonly absolutePath: string\n readonly content: string\n}\n\ninterface ScaffoldResult {\n readonly target: ScaffoldTarget\n readonly outcome: WriteOutcome\n}\n\ninterface InitReport {\n readonly results: readonly ScaffoldResult[]\n readonly schemaRelPath: string\n}\n\n/**\n * Confirms `cwd` is a project (`package.json` present and a JSON object).\n * Throws a message suitable for printing directly on any failure -- every\n * such failure is a preflight failure and nothing is written.\n */\nfunction assertIsProject(cwd: string): void {\n const packageJsonPath = path.join(cwd, \"package.json\")\n if (!existsSync(packageJsonPath)) {\n throw new Error(`no package.json found at ${packageJsonPath} -- run \\`npm init\\` first.`)\n }\n let parsed: unknown\n try {\n // Stryker disable next-line StringLiteral: hand-verified equivalent --\n // `readFileSync(path, \"\")` (the mutant) falls back to returning a\n // `Buffer` (an empty string isn't a recognized encoding), but\n // `JSON.parse` calls `.toString()` on any non-string input, which\n // defaults to utf8 for a `Buffer` -- so both encodings produce an\n // identical `JSON.parse` result for any file content this function can\n // ever see. Confirmed directly: `JSON.parse(readFileSync(p, \"\"))` on a\n // real UTF-8 JSON file parses identically to `JSON.parse(readFileSync(p,\n // \"utf8\"))`.\n parsed = JSON.parse(readFileSync(packageJsonPath, \"utf8\"))\n } catch {\n // No binding: the SyntaxError carries only a char offset, nothing the\n // caller needs beyond \"the file at this path isn't valid JSON\".\n throw new Error(`package.json at ${packageJsonPath} is not valid JSON.`)\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new Error(`package.json at ${packageJsonPath} must contain a top-level object.`)\n }\n}\n\n/** `src/` if it already exists as a directory, otherwise the project root -- where the starter schema goes. */\nfunction schemaDirectory(cwd: string): string {\n const srcDir = path.join(cwd, \"src\")\n return existsSync(srcDir) && statSync(srcDir).isDirectory() ? srcDir : cwd\n}\n\n/**\n * Computes the two scaffold targets and rejects any whose path is already\n * blocked by a wrong-typed entry (a directory where a file must go, or a\n * non-directory where `scripts/` must go). A failure here means zero writes.\n */\n// Always exactly two: the schema file and the generator script. Typed as a\n// tuple (not ScaffoldTarget[]) so runInit()'s targets[0] doesn't need a\n// defensive check for a case the fixed literal return below can't produce.\nfunction planTargets(cwd: string): [ScaffoldTarget, ScaffoldTarget] {\n const schemaPath = path.join(schemaDirectory(cwd), \"env.schema.ts\")\n const scriptsDir = path.join(cwd, \"scripts\")\n const generatorPath = path.join(scriptsDir, \"generate-env.mjs\")\n\n for (const filePath of [schemaPath, generatorPath]) {\n if (existsSync(filePath) && statSync(filePath).isDirectory()) {\n throw new Error(`${filePath} already exists and is a directory.`)\n }\n }\n if (existsSync(scriptsDir) && !statSync(scriptsDir).isDirectory()) {\n throw new Error(`${scriptsDir} already exists and is not a directory.`)\n }\n\n return [\n {\n label: path.relative(cwd, schemaPath),\n absolutePath: schemaPath,\n content: schemaTemplate(),\n },\n {\n label: path.relative(cwd, generatorPath),\n absolutePath: generatorPath,\n content: generatorTemplate(),\n },\n ]\n}\n\n/**\n * Writes `content` to `filePath` only if it doesn't already exist, creating\n * parent directories first. Exclusive-create (`\"wx\"`) rather than an\n * existsSync-then-write pair -- the two-step form races between the check\n * and the write; `\"wx\"` makes \"don't overwrite\" atomic. An existing file is\n * never touched -- the conflict is resolved by skipping, never overwriting.\n */\nfunction writeIfAbsent(filePath: string, content: string): WriteOutcome {\n mkdirSync(path.dirname(filePath), { recursive: true })\n try {\n writeFileSync(filePath, content, { flag: \"wx\" })\n return \"created\"\n } catch (error) {\n if (isFileExistsError(error)) return \"skipped\"\n throw error\n }\n}\n\nexport function isFileExistsError(error: unknown): boolean {\n return (\n typeof error === \"object\" && error !== null && (error as { code?: unknown }).code === \"EEXIST\"\n )\n}\n\nfunction runInit(cwd: string): InitReport {\n assertIsProject(cwd)\n const targets = planTargets(cwd)\n const results = targets.map((target) => ({\n target,\n outcome: writeIfAbsent(target.absolutePath, target.content),\n }))\n return { results, schemaRelPath: targets[0].label }\n}\n\n/** The structured `Created:` / `Skipped:` / `Next:` report, as a string (one `console.log`, testable). */\nfunction renderReport(report: InitReport): string {\n const lines: string[] = [\"env-cap initialized\", \"\"]\n\n const created = report.results.filter((r) => r.outcome === \"created\")\n const skipped = report.results.filter((r) => r.outcome === \"skipped\")\n\n if (created.length > 0) {\n lines.push(\"Created:\")\n for (const r of created) lines.push(` + ${r.target.label}`)\n lines.push(\"\")\n }\n if (skipped.length > 0) {\n lines.push(\"Skipped (already exists):\")\n for (const r of skipped) lines.push(` - ${r.target.label}`)\n lines.push(\"\")\n }\n\n const manifestImport = report.schemaRelPath.startsWith(\"src\" + path.sep)\n ? \"./generated/env.manifest.js\"\n : \"./src/generated/env.manifest.js\"\n\n lines.push(\n \"Next:\",\n \" 1. Generate the manifest + docs: node scripts/generate-env.mjs\",\n ' Requires \"typescript\" (>=5) in your project -- it\\'s how env-cap parses',\n \" env.schema.ts by static analysis. Add it if you don't already have it:\",\n \" npm install --save-dev typescript\",\n \" 2. Validate once at app startup:\",\n \"\",\n ' import { validateEnv } from \"@maverickcer/env-cap\"',\n ` import { manifest } from \"${manifestImport}\"`,\n \" await validateEnv({ manifest, values: process.env })\",\n \"\",\n \" 3. Read validated values through the contract: exampleEnv.EXAMPLE_API_URL\",\n \"\",\n \"env-cap init edited no package.json script -- add one if you want, e.g.\",\n ' \"generate:env\": \"node scripts/generate-env.mjs\"',\n )\n\n return lines.join(\"\\n\")\n}\n\n/**\n * `env-cap init` entry. Returns the process exit code; never calls\n * `process.exit`. `rest` is argv already sliced past the `init` token.\n */\nexport function runInitCommand(rest: readonly string[]): number {\n if (rest.includes(\"--help\") || rest.includes(\"-h\")) {\n process.stdout.write(`${usage()}\\n`)\n return 0\n }\n if (rest.length > 0) {\n process.stderr.write(`env-cap init takes no arguments (got: ${rest.join(\" \")})\\n\\n${usage()}\\n`)\n return 1\n }\n\n try {\n process.stdout.write(`${renderReport(runInit(process.cwd()))}\\n`)\n return 0\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n process.stderr.write(`env-cap init failed: ${message}\\n`)\n return 1\n }\n}\n","import type { CompatibilityIssue, GenerateEnvArtifactsResult } from \"../build/index.js\"\n// Imported from the leaf module, not the `../build/index.js` barrel: pulling\n// in the barrel here would eagerly load its full build-time surface --\n// (indirectly) `typescript`, an optional peer dependency -- just to read a\n// version string, for EVERY CLI invocation this module is part of\n// (including `env-cap init` and `env-cap --help`, neither of which touches\n// build-time analysis at all). See the identical fix, and its regression\n// test, on src/cli/index.ts's own former static `../build/index.js` import.\nimport { readToolVersion } from \"../build/tool-version.js\"\n\n/**\n * `--json`'s machine-readable contract lives here, in one place, so it's\n * unit/snapshot-testable without going through `main()`'s stdout spying and\n * doesn't make the CLI's control-flow function the de facto owner of a\n * public contract. See ADR 0013.\n */\n\n/** Bump only when a consumer written for the previous version could\n * misinterpret the new payload (a field changes type/meaning, or is\n * removed) -- NOT for every additive field. See ADR 0013. */\nexport const JSON_SCHEMA_VERSION = 1\n\n// One version source, shared with the `./build` entry -- `readToolVersion()`\n// returns `tsup`'s build-time constant, so the CLI never reads its own\n// manifest at runtime. See ADR 0040.\nconst TOOL_VERSION: string = readToolVersion()\n\n/**\n * Which passes this invocation actually asked for -- recorded explicitly so a\n * consumer never has to infer intent from which top-level keys happen to be\n * present.\n *\n * @remarks\n * Without this, `\"manifest\": undefined` is genuinely ambiguous: it could mean\n * \"no `--location` was passed\" or \"the manifest pass ran and produced\n * nothing,\" and telling those apart required knowing which CLI flags the run\n * was invoked with -- information the envelope itself never carried. A CI step\n * gating on \"did the docs pass run?\" would otherwise have to reconstruct the\n * command line. `evidence` records the request specifically (the model itself\n * is always computed, per ADR 0038, but only *included* in this envelope on\n * request -- see `JsonSuccessPayload.evidence`).\n */\nexport interface JsonRequestedPasses {\n /** `--location` was passed. */\n readonly manifest: boolean\n /** `--docs` was passed. */\n readonly docs: boolean\n /** `--ownership` was passed. */\n readonly usage: boolean\n /** `--evidence` was passed. */\n readonly evidence: boolean\n}\n\n/** The `--json` envelope for a successful run (generation completed without throwing). */\nexport interface JsonSuccessPayload extends Omit<GenerateEnvArtifactsResult, \"evidence\"> {\n readonly schemaVersion: typeof JSON_SCHEMA_VERSION\n readonly kind: \"env-cap-report\"\n readonly toolVersion: string\n readonly ok: true\n /** Which passes this invocation requested -- always present, so \"not requested\" is never confused with \"computed empty.\" See {@link JsonRequestedPasses}. */\n readonly requested: JsonRequestedPasses\n /** Present only when the caller actually requested `--evidence` --\n * `GenerateEnvArtifactsResult.evidence` itself is always populated (ADR\n * 0038, \"free to compute, always real\"), but the `--json` envelope omits\n * it by default so an ordinary `--location`/`--docs`/`--ownership` report\n * doesn't silently grow by the full evidence model every time. */\n readonly evidence?: GenerateEnvArtifactsResult[\"evidence\"]\n /** Present only when invoked with --check. Governs --check's own pass/fail\n * exit code, independent of this envelope's top-level `ok` (which keeps\n * its existing, unrelated meaning: \"did generation complete without\n * throwing\"). See ADR 0016. */\n readonly checkResult?: { readonly ok: boolean; readonly stale: readonly string[] }\n}\n\n/** A thrown error's shape in the `--json` envelope. */\nexport interface JsonErrorInfo {\n readonly name: string\n readonly message: string\n /** Populated only when the thrown error carries a `CompatibilityIssue[]` (the generator errors in `build/errors.ts` all do). */\n readonly issues?: readonly CompatibilityIssue[]\n}\n\n/** The `--json` envelope for a failed run (generation threw). */\nexport interface JsonErrorPayload {\n readonly schemaVersion: typeof JSON_SCHEMA_VERSION\n readonly kind: \"env-cap-report\"\n readonly toolVersion: string\n readonly ok: false\n readonly error: JsonErrorInfo\n}\n\nfunction hasIssues(error: unknown): error is { issues: readonly CompatibilityIssue[] } {\n return (\n typeof error === \"object\" &&\n error !== null &&\n Array.isArray((error as { issues?: unknown }).issues)\n )\n}\n\n/**\n * Wraps a completed {@link generateEnvArtifacts} result in the `--json`\n * success envelope. `includeEvidence` (default `false`) controls whether\n * `result.evidence` -- always populated on `result` itself, per ADR 0038 --\n * is actually included in the envelope; the CLI passes `true` only when the\n * caller requested `--evidence`.\n *\n * `requested` is supplied by the caller rather than inferred from `result`'s\n * own populated keys -- inferring it would reproduce exactly the ambiguity\n * this field exists to remove (see {@link JsonRequestedPasses}). It defaults\n * to deriving each pass from whether its result is present, which is correct\n * for a normal generate run and keeps this callable from a test without\n * threading flags through; the CLI always passes the real flags.\n */\nexport function serializeSuccess(\n result: Omit<GenerateEnvArtifactsResult, \"evidence\"> &\n Partial<Pick<GenerateEnvArtifactsResult, \"evidence\">>,\n checkResult?: { readonly ok: boolean; readonly stale: readonly string[] },\n includeEvidence = false,\n requested?: JsonRequestedPasses,\n): JsonSuccessPayload {\n const { evidence, ...rest } = result\n return {\n schemaVersion: JSON_SCHEMA_VERSION,\n kind: \"env-cap-report\",\n toolVersion: TOOL_VERSION,\n ok: true,\n requested: requested ?? {\n manifest: rest.manifest !== undefined,\n docs: rest.docs !== undefined,\n usage: rest.usage !== undefined,\n evidence: includeEvidence,\n },\n ...rest,\n ...(includeEvidence ? { evidence } : {}),\n ...(checkResult ? { checkResult } : {}),\n }\n}\n\n/** Wraps a thrown error in the `--json` failure envelope. */\nexport function serializeFailure(error: unknown): JsonErrorPayload {\n return {\n schemaVersion: JSON_SCHEMA_VERSION,\n kind: \"env-cap-report\",\n toolVersion: TOOL_VERSION,\n ok: false,\n error: {\n name: error instanceof Error ? error.name : \"Error\",\n message: error instanceof Error ? error.message : String(error),\n // exactOptionalPropertyTypes: omit the key rather than set it to\n // `undefined` when the thrown error carries no issues of its own.\n ...(hasIssues(error) ? { issues: error.issues } : {}),\n },\n }\n}\n\n/**\n * The complete `--json` envelope shape, success or failure -- the target\n * type the published JSON Schema (`schemas/env-cap-report.schema.json`,\n * `npm run schema`) is generated from. See ADR 0019.\n */\nexport type JsonReportPayload = JsonSuccessPayload | JsonErrorPayload\n\n/** Writes a `--json` envelope to stdout, pretty-printed with a trailing newline. */\nexport function writeJson(payload: JsonReportPayload): void {\n process.stdout.write(`${JSON.stringify(payload, null, 2)}\\n`)\n}\n"],"mappings":";;;;;;AAAA,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;;;ACD9B,OAAO,QAAQ;AA0Bf,SAAS,SAASA,OAAc,UAAmC;AACjE,SAAO,GAAG,SAASA,OAAM,QAAQ;AACnC;AAEA,SAAS,UAAUA,OAAc,MAAc,UAAiC;AAC9E,SAAO,GAAG,UAAUA,OAAM,MAAM,QAAQ;AAC1C;AAEA,eAAe,MAAMA,OAAc,SAA6C;AAC9E,QAAM,GAAG,MAAMA,OAAM,OAAO;AAC9B;AAEA,SAAS,QAAQA,OAAc,SAA0D;AACvF,SAAO,GAAG,QAAQA,OAAM,OAAO;AACjC;AAEA,SAAS,KAAKA,OAAmC;AAC/C,SAAO,GAAG,KAAKA,KAAI;AACrB;AAEA,SAAS,SAASA,OAA+B;AAC/C,SAAO,GAAG,SAASA,KAAI;AACzB;AASO,IAAM,sBAAuC;AAAA,EAClD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;;;AChEA,SAAS,YAAY,WAAW,cAAc,UAAU,qBAAqB;AAC7E,OAAO,UAAU;AA4BjB,SAAS,QAAgB;AACvB,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWT;AAEA,SAAS,iBAAyB;AAChC,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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