@super-repo/envx 0.2.3-b.3 → 0.2.3-b.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -54,6 +54,21 @@ The CLI shape, the `encrypted:<base64>` ciphertext format, the `ENVX_PUBLIC_KEY*
54
54
  | **Programmatic API** | `dotenvx.config()` / library functions | `envx()` (single call), `import "@super-repo/envx/auto"` side-effect entry |
55
55
  | **Auto-environment detection** | Limited | Reads `VERCEL_ENV`, Netlify `CONTEXT`, `NODE_ENV` to pick `.env.<env>` when `--env` is omitted |
56
56
  | **Distribution** | npm package | npm package + workspace-private helpers (`envx-libs`, `envx-common`) bundled via Vite |
57
+ | **Health check** | Not built in | `envx doctor` — workspace, config, keys file, decryptability, required, expand cycles |
58
+ | **`.env.example` sync** | Not built in | `envx template` (and `--check` for CI drift detection) |
59
+ | **Diff between env files** | Not built in | `envx diff` — keys-only-in-a/b + value mismatches (decrypts via `.env.keys`) |
60
+ | **Shell injection** | Not built in | `envx hook bash|zsh|fish|powershell` — eval-able exports for the parent shell |
61
+ | **Typed `process.env`** | Not built in | `envx types` — emits `env.d.ts` from loaded keys (Zod-shape-aware) |
62
+ | **Watch mode** | Not built in | `envx watch -- node app.js` — restart on `.env*` change |
63
+ | **Repo-wide secret audit** | Not built in | `envx audit` — AKIA, ghp_, sk_live_, JWT, OpenAI/Anthropic keys, PEM blocks, … |
64
+ | **Selective encryption** | Per-key flag (`-k`) | Per-key, glob patterns (`--pattern`), and `--secrets` preset |
65
+ | **Schema validation (Zod)** | Not built in | `schema:` field in config — duck-typed `safeParse()` with fail-fast exit |
66
+ | **Named profiles** | Not built in | `profiles: { staging: { ... } }` + `--profile staging` (per-field override) |
67
+ | **External secret refs** | Not built in | `${aws-secrets:my-id}` resolved by user-registered `resolvers:` callbacks |
68
+ | **Secret-provider plugins** | Not built in | `@super-repo/envx-plugins` ships AWS, GCP, Azure, Vault, 1Password, Doppler, Infisical |
69
+ | **Public-variable mirroring** | Not built in | `PUBLIC_*` vars auto-mirror under `VITE_`, `NEXT_PUBLIC_`, `REACT_APP_`, etc. |
70
+ | **Build-time secret bake** | Not built in | `envx bake` resolves all refs into `.env.resolved` for bundlers (Vite/Next/esbuild) |
71
+ | **Runtime / edge secrets** | Not built in | `createSecretRuntime()` — async, TTL-cached, V8-isolate-safe (CF Workers, Vercel Edge) |
57
72
  | **License** | BSD-3-Clause | MIT |
58
73
 
59
74
  In short: same crypto, same file formats, same CLI vocabulary — different path-resolution layer underneath.
@@ -81,6 +96,52 @@ The string form (`envx("prod")`) is shorthand for "scope this load to the named
81
96
 
82
97
  `envx()` discovers `envx.config.{ts,js,json}` and `package.json#envx.config` automatically; explicit args override matching fields from the config.
83
98
 
99
+ #### Programmatic options — full surface
100
+
101
+ `envx()` accepts everything from `LoadEnvOptions` plus an optional `profile` string. The full shape (`EnvxProgrammaticOptions`):
102
+
103
+ ```ts
104
+ import envx, { type EnvxProgrammaticOptions } from "@super-repo/envx";
105
+
106
+ const opts: EnvxProgrammaticOptions = {
107
+ // env-file selection
108
+ envFiles: ["vault/.env.prod"],
109
+ envPath: "vault",
110
+ cascade: "prod", // string for explicit, true for auto-detected, false to disable
111
+ vault: false, // shortcut for envPath: "vault"
112
+
113
+ // load behavior
114
+ override: false,
115
+ quiet: true,
116
+ variables: ["DEBUG=1"], // post-load mutation; always wins
117
+
118
+ // auto-detection
119
+ autoDetect: true,
120
+ nodeEnvMap: { qa: "qa-prod" },
121
+
122
+ // post-load behavior
123
+ required: ["DATABASE_URL"], // exit 1 if any is unset after load
124
+ expand: true, // resolve ${VAR} references
125
+ defaults: { LOG_LEVEL: "info" }, // fill holes; never overwrite
126
+
127
+ // validation + plug-ins
128
+ schema: zodSchema, // any { safeParse(input) → { success, error?, data? } }
129
+ resolvers: { // ${provider:id} → resolver(id)
130
+ "aws-secrets": (id) => fetchSecret(id),
131
+ },
132
+
133
+ // profile selection (programmatic equivalent of --profile)
134
+ profile: "staging", // throws if config.profiles[name] is missing
135
+
136
+ // advanced
137
+ workspaceRoot: "/abs/path", // skip findWorkspaceRoot() walk-up
138
+ };
139
+
140
+ envx(opts);
141
+ ```
142
+
143
+ Caller-supplied fields override matching fields from the discovered config **per-field** — anything you omit falls through to config, then to defaults.
144
+
84
145
  ### Side-effect import
85
146
 
86
147
  ```ts
@@ -102,9 +163,19 @@ envx --dir vault -- pnpm test # load every .env* in vault/
102
163
  envx print DATABASE_URL # print one variable
103
164
  envx debug --cascade prod # show resolved paths
104
165
  envx encrypt -e .env.prod # encrypt values in .env.prod (writes ./.env.keys)
166
+ envx encrypt --secrets # encrypt only conventional secret keys (*_SECRET, *_TOKEN, …)
105
167
  envx decrypt -e .env.prod -k FOO # decrypt only FOO
106
168
  envx rotate --dir vault # rotate keypair for every vault/.env* file
107
169
  envx expand -e vault/.env.prod # decrypt + expand to stdout
170
+ envx doctor # health check (workspace, keys, decryptability, required, cycles)
171
+ envx template # write .env.example with values stripped
172
+ envx template --check # CI gate — exit 1 on .env.example drift
173
+ envx diff .env.dev .env.prod # show keys-only-in-a/b + value mismatches
174
+ eval "$(envx hook bash)" # inject loaded env into the parent shell
175
+ envx types # emit env.d.ts for typed process.env access
176
+ envx watch -- node app.js # restart on .env* change
177
+ envx audit # scan repo for plaintext secrets
178
+ envx --profile staging -- node app.js # apply named profile from envx.config.*
108
179
  envx -c ./envx.config.json run -- node app.js
109
180
  ```
110
181
 
@@ -117,17 +188,32 @@ envx -c ./envx.config.json run -- node app.js
117
188
 
118
189
  ### Subcommands
119
190
 
191
+ #### Core
192
+
120
193
  | command | what it does |
121
194
  | --------- | -------------------------------------------------------------------------------------- |
122
195
  | `run` | (default) load env files into `process.env` and execute a command |
123
196
  | `print` | load env files and print a single variable's value |
124
197
  | `debug` | show which files would be loaded without loading them |
125
- | `encrypt` | encrypt values in one or more `.env*` files (writes `.env.keys` on first run) |
198
+ | `encrypt` | encrypt values in one or more `.env*` files (writes `.env.keys` on first run). Selective: `--key`, `--pattern '*_SECRET,*_TOKEN'`, `--secrets` preset |
126
199
  | `decrypt` | decrypt values back in place |
127
200
  | `rotate` | generate a fresh keypair and re-encrypt every encrypted value in place |
128
201
  | `info` | print resolved configuration, auto-detection details, NODE_ENV mappings, and the env files that would load |
129
202
  | `expand` | decrypt (if needed) and expand `${VAR}` / `$VAR` / `${VAR:-default}` / `${VAR:?msg}` |
130
203
 
204
+ #### Workflow + DX
205
+
206
+ | command | what it does |
207
+ | ------------- | ---------------------------------------------------------------------------------------------------------------- |
208
+ | `doctor` | run health checks: workspace + config visible, env files exist, keys file present, every encrypted value decrypts, `required` keys filled after a dry load, expansion has no cycles. Exits non-zero on hard failures. CI-friendly. |
209
+ | `template` | emit a value-stripped `.env.example` from your real env files. `--check` mode exits 1 on drift; `--stdout` prints to stdout; `--annotate` (default on) tags each key with the source file. |
210
+ | `diff <a> <b>` | compare two env files key-by-key. Reports keys-only-in-a, keys-only-in-b, and value mismatches. Decrypts via `.env.keys` so the comparison reflects logical values; values are masked unless `--show-values`. |
211
+ | `hook <shell>` | print eval-able shell exports for the loaded env. Supports `bash`, `zsh`, `fish`, `powershell`/`pwsh` with proper escaping. Use `eval "$(envx hook bash)"` to inject env into the parent shell. |
212
+ | `types` | emit an `env.d.ts` declaring every loaded key on `NodeJS.ProcessEnv`. Keys listed in `required` (or non-optional in a Zod schema) narrow to `string`; everything else is `string \| undefined`. |
213
+ | `watch` | spawn a command and restart it whenever any of the resolved env files change. Debounce + SIGTERM-then-SIGKILL grace for clean restarts. |
214
+ | `audit` | walk the repo looking for plaintext secrets — AWS keys, GitHub PATs, Stripe live/test keys, JWTs, OpenAI / Anthropic keys, Google API keys, Slack tokens, PEM private-key blocks. Findings are redacted; exit 1 on any hit. `--json` for downstream tools. |
215
+ | `bake` | resolve every `${{provider:id}}` ref + decrypt every encrypted value + run defaults / expand / schema / public-mirror, then write a sealed `.env.resolved` for build tools to consume. Output is plaintext — refuses to write under `.git/`; use `--public-only` for client bundles. `--json` for structured tools, `--out=-` for stdout. |
216
+
131
217
  ### Global options
132
218
 
133
219
  | option | alias | default | description |
@@ -141,6 +227,7 @@ envx -c ./envx.config.json run -- node app.js
141
227
  | `--cascade` | | _(off)_ | Cascade name; expands `.env`, `.env.<c>`, `.env.local`, `.env.<c>.local`. |
142
228
  | `--override` | `-o` | `false` | Override existing `process.env` values. Conflicts with `--cascade`. |
143
229
  | `--quiet` | `-q` | `true` | Suppress dotenv's own output. |
230
+ | `--profile` | `-P` | _(none)_ | Named profile from `profiles` in `envx.config.*` — fields override the base config per-field. |
144
231
 
145
232
  ### Defaults
146
233
 
@@ -430,7 +517,9 @@ Final value of process.env.SOME_KEY is the FIRST hit, top-down:
430
517
 
431
518
  ```ts
432
519
  // envx.config.ts
433
- export default {
520
+ import { defineConfig } from "@super-repo/envx";
521
+
522
+ export default defineConfig({
434
523
  // ── env-file selection ─────────────────────────────────
435
524
  envFiles: [".env", ".env.local"], // bypass auto-detect; explicit list
436
525
  envPath: "vault", // workspace-relative subdir (cwd-first, ws-root fallback)
@@ -464,12 +553,44 @@ export default {
464
553
  PORT: "3000",
465
554
  },
466
555
 
556
+ // ── validation ─────────────────────────────────────────
557
+ schema: z.object({ // any object exposing `safeParse(input) → { success, error?, data? }`
558
+ DATABASE_URL: z.string().url(), // Zod is the obvious choice but envx duck-types — bring your own
559
+ PORT: z.coerce.number(), // coerced values are written back to process.env
560
+ }),
561
+
562
+ // ── named profiles ─────────────────────────────────────
563
+ profiles: { // `--profile staging` (or programmatic `envx({ profile: "staging" })`)
564
+ staging: { // merges this object onto the base config per-field, profile wins
565
+ envFiles: [".env.staging"],
566
+ required: ["DB_URL"],
567
+ },
568
+ prod: {
569
+ envFiles: [".env.prod"],
570
+ cascade: true,
571
+ required: ["DB_URL", "API_KEY"],
572
+ },
573
+ },
574
+
575
+ // ── external secret refs ───────────────────────────────
576
+ resolvers: { // values like `${aws-secrets:my-id}` get passed to the resolver
577
+ "aws-secrets": (id: string) => { // and replaced by its return. Sync — wrap async SDK calls externally.
578
+ return cachedAwsSecret(id); // (e.g. pre-warm a cache before envx() runs in your bootstrap)
579
+ },
580
+ },
581
+
582
+ // ── public-variable mirroring (SSR / client-side bundlers) ─
583
+ publicPrefixes: ["VITE_", "NEXT_PUBLIC_"], // duplicate every PUBLIC_* under each prefix
584
+ publicSource: "PUBLIC_", // (default) the prefix that marks a var as public
585
+
467
586
  // ── advanced ───────────────────────────────────────────
468
587
  workspaceRoot: "/abs/path/to/repo", // escape hatch — skip findWorkspaceRoot() walk-up
469
- }
588
+ })
470
589
  ```
471
590
 
472
- All fields are optional. Anything you omit falls through to the built-in default for that field.
591
+ All fields are optional. Anything you omit falls through to the built-in default for that field. `defineConfig` is an identity helper — at runtime it just returns the object, but it gives editors full autocomplete and type-checking for `DotenvxConfig`. A plain `export default { … }` works too.
592
+
593
+ > **Note:** `schema`, `profiles`, and `resolvers` are TS/JS-only — JSON configs can't carry callable functions. A `package.json#envx.config` reference must point at a `.ts` / `.mts` / `.js` / `.mjs` / `.cjs` file to use them.
473
594
 
474
595
  ### Discovery order
475
596
 
@@ -509,6 +630,371 @@ Expanded explanations, worked examples, and recipes ship with the package in [`.
509
630
  - **[Configuration](./docs/configuration.md)** — full schema, the per-field merge rules, where each field gets read from, and the discovery walk.
510
631
  - **[Monorepo recipes](./docs/recipes.md)** — common layouts (single workspace `.env.keys`, vault subdir, per-app overrides, CI patterns) with the exact files and commands.
511
632
 
633
+ ## Library API
634
+
635
+ Beyond `envx()`, the package re-exports the building blocks the CLI uses internally — useful when you need to script the same behavior from your own tool, plugin, or test harness. Everything below is importable from the default entry:
636
+
637
+ ```ts
638
+ import {
639
+ // Programmatic loader
640
+ envx,
641
+ type EnvxProgrammaticOptions,
642
+ type LoadEnvOptions,
643
+
644
+ // Audit (plaintext-secret scanner)
645
+ auditFiles,
646
+ BUILT_IN_PATTERNS,
647
+ type AuditFinding,
648
+ type AuditOptions,
649
+ type SecretPattern,
650
+
651
+ // Crypto primitives
652
+ ENCRYPTED_PREFIX,
653
+ generateKeyPair,
654
+ encryptValueAsymmetric,
655
+ decryptValueAsymmetric,
656
+ isEncrypted,
657
+
658
+ // Higher-level operations
659
+ encryptFiles,
660
+ decryptFiles,
661
+ rotateFiles,
662
+
663
+ // Env-file parser (line-preserving)
664
+ parseEnv,
665
+ serializeEnv,
666
+ toRecord,
667
+
668
+ // Variable expansion (cycle-safe)
669
+ expandRecord,
670
+ expandEnvSrc,
671
+
672
+ // Config + path resolution
673
+ defineConfig,
674
+ loadDotenvxConfig,
675
+ findWorkspaceRoot,
676
+ resolveCwdOrWorkspace,
677
+ resolveEnvPaths,
678
+ detectEnvironment,
679
+
680
+ // Keys-file management
681
+ readKeysFile,
682
+ writeKeysFile,
683
+ defaultKeysPath,
684
+ } from "@super-repo/envx";
685
+ ```
686
+
687
+ ### Audit programmatically
688
+
689
+ `envx audit` is a thin wrapper around `auditFiles()`. Use it directly to plug envx's secret detection into a pre-commit hook, a CI script, or your own dashboard:
690
+
691
+ ```ts
692
+ import { auditFiles, type SecretPattern } from "@super-repo/envx";
693
+
694
+ // Add custom patterns alongside the built-ins.
695
+ const orgPatterns: SecretPattern[] = [
696
+ { id: "internal-token", label: "ACME internal token", regex: /\bacme_[A-Za-z0-9]{32}\b/ },
697
+ ];
698
+
699
+ const { findings, filesScanned } = auditFiles({
700
+ roots: ["packages/", "apps/"],
701
+ ignore: ["fixtures", "snapshots"],
702
+ extra: orgPatterns,
703
+ max: 100, // 0 = unlimited
704
+ });
705
+
706
+ if (findings.length > 0) {
707
+ console.error(`audit: ${findings.length} finding(s) across ${filesScanned} files`);
708
+ process.exit(1);
709
+ }
710
+ ```
711
+
712
+ Findings are redacted (`AKIA…MPLE [redacted 20 chars]`) so the report itself never leaks the secret payload.
713
+
714
+ ### Custom profiles + resolvers in code
715
+
716
+ When you need conditional behavior in a programmatic call (without a config file):
717
+
718
+ ```ts
719
+ import envx from "@super-repo/envx";
720
+ import { z } from "zod";
721
+
722
+ const Schema = z.object({
723
+ DATABASE_URL: z.string().url(),
724
+ PORT: z.coerce.number().int().min(1).max(65535),
725
+ });
726
+
727
+ await preloadAwsSecretsCache(); // resolvers are sync — warm caches up front
728
+
729
+ envx({
730
+ schema: Schema,
731
+ resolvers: {
732
+ "aws-secrets": (id) => awsSecretsCache.get(id),
733
+ "1password": (ref) => onePasswordCache.get(ref),
734
+ },
735
+ required: ["DATABASE_URL", "PORT"],
736
+ expand: true, // ${HOST}/api works after resolvers run
737
+ });
738
+ ```
739
+
740
+ Order of operations inside `envx()` once a profile / resolvers / schema are in play:
741
+
742
+ ```
743
+ 1. resolve workspaceRoot
744
+ 2. resolve env file paths
745
+ 3. load each env file → mutates process.env (subject to `override`)
746
+ 4. apply `variables` → unconditional overwrite
747
+ 5. run `resolvers` on ${provider:id} refs
748
+ 6. apply `defaults` → only for keys still unset
749
+ 7. expand `${VAR}` references (when `expand: true`)
750
+ 8. validate against `schema` (when configured) — exits 1 on failure
751
+ 9. enforce `required` (any unset → log + exit 1)
752
+ ```
753
+
754
+ ## Public variables (SSR + client bundlers)
755
+
756
+ Modern frameworks each demand their own prefix for variables that should reach client-side code:
757
+
758
+ | framework | prefix |
759
+ | ----------------- | --------------- |
760
+ | Vite | `VITE_` |
761
+ | Next.js | `NEXT_PUBLIC_` |
762
+ | Create React App | `REACT_APP_` |
763
+ | Nuxt 3 (public) | `NUXT_PUBLIC_` |
764
+ | SvelteKit (public)| `PUBLIC_` |
765
+ | Remix (loader) | _(none)_ |
766
+
767
+ Maintaining the same value under three different keys (`VITE_API_URL`, `NEXT_PUBLIC_API_URL`, `REACT_APP_API_URL`) is the kind of busywork envx exists to delete. Mark a variable "public" once with `PUBLIC_` (or any prefix you configure as `publicSource`), and envx mirrors it under every framework prefix at load time.
768
+
769
+ ```ts
770
+ // envx.config.ts
771
+ export default {
772
+ publicPrefixes: ["VITE_", "NEXT_PUBLIC_"],
773
+ // publicSource: "PUBLIC_" // (default)
774
+ }
775
+ ```
776
+
777
+ ```env
778
+ # .env
779
+ PUBLIC_API_URL=https://api.example.com
780
+ PUBLIC_FEATURE_FLAG=true
781
+ DATABASE_URL=secret-stuff # not mirrored — no PUBLIC_ prefix
782
+ ```
783
+
784
+ After `envx -- node app.js`, `process.env` looks like:
785
+
786
+ | key | value | source |
787
+ | ---------------------------- | --------------------------- | --------------- |
788
+ | `PUBLIC_API_URL` | `https://api.example.com` | original |
789
+ | `VITE_API_URL` | `https://api.example.com` | mirror |
790
+ | `NEXT_PUBLIC_API_URL` | `https://api.example.com` | mirror |
791
+ | `PUBLIC_FEATURE_FLAG` | `true` | original |
792
+ | `VITE_FEATURE_FLAG` | `true` | mirror |
793
+ | `NEXT_PUBLIC_FEATURE_FLAG` | `true` | mirror |
794
+ | `DATABASE_URL` | `secret-stuff` | original (kept private — no mirror) |
795
+
796
+ CLI flag for one-off use:
797
+
798
+ ```sh
799
+ envx --public-prefix VITE_ --public-prefix NEXT_PUBLIC_ -- pnpm build
800
+ ```
801
+
802
+ Mirroring runs **after** `expand`, so `${VAR}` references inside `PUBLIC_*` values resolve before being mirrored. Existing target keys are never overwritten — a `VITE_API_URL` already set in the parent shell wins over the auto-mirror.
803
+
804
+ ## Security models — when secrets are fetched
805
+
806
+ Pick one based on where you want plaintext to live:
807
+
808
+ | model | when secrets are fetched | plaintext on disk? | best for |
809
+ | ------------------------------ | --------------------------------------- | ------------------------------- | ---------------------------------------- |
810
+ | **Encrypted-at-rest** (default)| process startup — `envx run --` decrypts via `.env.keys` | ciphertext only, in committed `.env*` | most apps — single binary, fast cold start |
811
+ | **Load-time fetch** (resolvers)| process startup — plugins fetch via `resolvers:` | none — plaintext stays in process memory | server processes, long-running workers |
812
+ | **Build-time bake** | once, in CI — `envx bake` writes `.env.resolved` | yes (in the build artifact) ⚠️ | static SPA bundles, public-only vars |
813
+ | **Runtime fetch** (edge) | per cold start, lazily — `secrets.get()` on first read | none — secrets stay in the source-of-truth | edge functions, serverless, zero-trust |
814
+
815
+ The four models stack — most apps end up using two or more (e.g. encrypted-at-rest for non-secret config, runtime fetch for actual secrets).
816
+
817
+ ### Build-time bake (`envx bake`)
818
+
819
+ ```sh
820
+ # CI step — resolves every encrypted value + ${provider:id} ref + ${VAR}
821
+ # expansion + schema validation, then writes a sealed file the bundler picks up.
822
+ envx bake --out dist/.env.resolved
823
+
824
+ # Public-only mode for client bundles — only PUBLIC_* keys + their framework mirrors.
825
+ envx bake --public-only --out dist/.env.public
826
+ ```
827
+
828
+ ⚠️ The output file is **plaintext**. envx writes a `# DO NOT COMMIT` banner and refuses to write under `.git/`, but you must add the path to `.gitignore` yourself. Use `--public-only` whenever the artifact will ship to clients.
829
+
830
+ Build-tool integration:
831
+
832
+ ```ts
833
+ // vite.config.ts
834
+ import { defineConfig, loadEnv } from "vite";
835
+
836
+ export default defineConfig(({ mode }) => {
837
+ // Vite's loadEnv reads .env.resolved like any other .env file.
838
+ const env = loadEnv(mode, process.cwd(), ".env.resolved");
839
+ return {
840
+ define: {
841
+ "import.meta.env.VITE_API_URL": JSON.stringify(env.VITE_API_URL),
842
+ },
843
+ };
844
+ });
845
+ ```
846
+
847
+ ```sh
848
+ # CI script
849
+ envx bake --public-only --out .env.resolved && pnpm vite build
850
+ ```
851
+
852
+ ### Runtime fetch — edge / serverless
853
+
854
+ For the "secrets never leave the source-of-truth" model, use `createSecretRuntime` from `@super-repo/envx-plugins/runtime`. Async-first, TTL caching, no `fs` / `child_process` dependencies — works in Cloudflare Workers, Vercel Edge, Deno Deploy, AWS Lambda, Bun, Node.
855
+
856
+ ```ts
857
+ // src/secrets.ts — module-level singleton, one per worker
858
+ import { createSecretRuntime } from "@super-repo/envx-plugins/runtime";
859
+ import { hcVault } from "@super-repo/envx-plugins/vault";
860
+
861
+ export const secrets = createSecretRuntime({
862
+ providers: [
863
+ hcVault({
864
+ endpoint: env.VAULT_ADDR,
865
+ token: env.VAULT_TOKEN,
866
+ }),
867
+ ],
868
+ ttl: 300, // refresh every 5 min
869
+ onFailure: "cache-stale", // serve stale on transient backend failures
870
+ });
871
+ ```
872
+
873
+ ```ts
874
+ // src/handler.ts (Cloudflare Worker / Vercel Edge / Lambda — same shape)
875
+ import { secrets } from "./secrets";
876
+
877
+ export default async function handler(req: Request): Promise<Response> {
878
+ const dbUrl = await secrets.get("vault:prod/db");
879
+ const apiKey = await secrets.get("vault:prod/api");
880
+ // … handler logic …
881
+ }
882
+ ```
883
+
884
+ What you get:
885
+ - **Lazy fetch** — first read triggers the network call. Subsequent reads within the TTL window hit memory.
886
+ - **Single-flight** — N concurrent reads of the same ref coalesce into one fetch. Edge functions handling a burst of requests don't fan out N parallel calls to your secret store.
887
+ - **TTL refresh** — values older than `ttl` seconds are refetched on next read. Set `ttl: Infinity` to cache forever; `ttl: 0` to fetch every read.
888
+ - **Failure modes** — `"throw"` (default), `"cache-stale"` (serve previous value, log warning), or `"cache-error"` (cache the failure for `errorTtl` seconds so you don't hammer a failing backend).
889
+ - **No fs / child_process imports** — the runtime entry point is V8-isolate-safe.
890
+
891
+ ### Compatibility note
892
+
893
+ Plugin compatibility for the runtime entry depends on what each provider's transport needs:
894
+
895
+ | provider | edge runtime? | reason |
896
+ | ------------------ | --------------------------- | ----------------------------------- |
897
+ | HashiCorp Vault | ✓ | native `fetch` |
898
+ | Doppler | ✓ | native `fetch` |
899
+ | Infisical | ✓ | native `fetch` |
900
+ | AWS Secrets Manager| ⚠ Node-compat only | `@aws-sdk/client-secrets-manager` uses Node streams |
901
+ | GCP Secret Manager | ⚠ Node-compat only | `@google-cloud/secret-manager` uses gRPC |
902
+ | Azure Key Vault | ⚠ Node-compat only | `@azure/identity` token chain |
903
+ | 1Password (CLI) | ✗ | spawns the `op` binary |
904
+ | 1Password (SDK) | depends on `@1password/sdk` | check the SDK's runtime support |
905
+
906
+ For Cloudflare Workers / Vercel Edge / Deno: prefer Vault, Doppler, Infisical, or a custom HTTP `buildProvider`. AWS / GCP / Azure SDKs run fine in Lambda / Cloud Run / Cloud Functions but won't work in V8-only edges.
907
+
908
+ ## Secret-provider plugins
909
+
910
+ Ship as a sibling package: [`@super-repo/envx-plugins`](https://www.npmjs.com/package/@super-repo/envx-plugins). Plugins return a `SecretProvider` you wire into envx's `resolvers:` config so values like `${aws-secrets:my-db}` and `${vault:prod/api}` fetch from the matching backend at load time.
911
+
912
+ ```ts
913
+ import envx from "@super-repo/envx";
914
+ import { awsSecrets, autoPreload, asResolvers } from "@super-repo/envx-plugins";
915
+
916
+ const aws = awsSecrets({ region: "us-east-1" });
917
+
918
+ await autoPreload([aws], { envFiles: [".env", "vault/.env.prod"] });
919
+
920
+ envx({ resolvers: asResolvers([aws]) });
921
+ ```
922
+
923
+ ```env
924
+ DATABASE_URL=${aws-secrets:prod/db}
925
+ ```
926
+
927
+ Built-in providers: AWS Secrets Manager, GCP Secret Manager, Azure Key Vault, HashiCorp Vault, 1Password (CLI + SDK), Doppler, Infisical. Each plugin lazy-loads its SDK — install only what you use. See the [`@super-repo/envx-plugins` README](../plugins/README.md) for per-provider setup.
928
+
929
+ ## Pre-commit hooks
930
+
931
+ Three of the new commands (`audit`, `doctor`, `template --check`) are designed to compose into a single git pre-commit gate so secrets, broken configs, and stale `.env.example` files never reach the remote.
932
+
933
+ The repo ships a reference `.hooks/pre-commit` you can adopt verbatim or copy into your own setup:
934
+
935
+ ```sh
936
+ # Activate the in-repo .hooks/ directory (one-time per clone)
937
+ git config core.hooksPath .hooks
938
+ ```
939
+
940
+ That single config line tells git to look for hooks under `<repo>/.hooks/` instead of `.git/hooks/`. The directory is committed (everyone gets the same hooks), no third-party tool is required.
941
+
942
+ The hook itself:
943
+
944
+ ```bash
945
+ #!/usr/bin/env bash
946
+ # .hooks/pre-commit
947
+ set -euo pipefail
948
+ [[ "${ENVX_SKIP_HOOK:-}" == "1" ]] && exit 0
949
+
950
+ # Use the workspace binary if available, else a global envx
951
+ if command -v pnpm >/dev/null && [[ -f package.json ]]; then
952
+ ENVX="pnpm exec envx"
953
+ else
954
+ ENVX="envx"
955
+ fi
956
+
957
+ failed=0
958
+
959
+ # 1. Audit staged files for plaintext secrets (AKIA, ghp_, sk_live_, JWTs, …)
960
+ staged=$(git diff --cached --name-only --diff-filter=ACMR | tr '\n' ' ')
961
+ [[ -n "$staged" ]] && ! $ENVX audit $staged && failed=1
962
+
963
+ # 2. Workspace health (skip required-key gate so dev machines don't fail)
964
+ $ENVX doctor --ignore-required || failed=1
965
+
966
+ # 3. .env.example drift gate
967
+ [[ -f .env ]] && ! $ENVX template --check && failed=1
968
+
969
+ exit $failed
970
+ ```
971
+
972
+ Bypass options:
973
+ - `ENVX_SKIP_HOOK=1 git commit ...` — skip just the envx hook
974
+ - `git commit --no-verify` — skip every git hook (use sparingly)
975
+
976
+ The full annotated script lives at `.hooks/pre-commit` in this repo. CI should run the same three commands without the `--ignore-required` flag so missing required keys fail builds (not just commits).
977
+
978
+ ### Pre-push variant
979
+
980
+ For a stricter gate that runs only on push (so commits stay fast but pushes are guarded):
981
+
982
+ ```bash
983
+ #!/usr/bin/env bash
984
+ # .hooks/pre-push — same checks, run against the whole repo, no skip.
985
+ set -euo pipefail
986
+ envx audit && envx doctor && envx template --check
987
+ ```
988
+
989
+ ### CI-friendly invocations
990
+
991
+ ```yaml
992
+ # .github/workflows/secrets.yml
993
+ - run: pnpm exec envx audit --json > audit.json
994
+ - run: pnpm exec envx doctor # fails the build on missing required keys
995
+ - run: pnpm exec envx template --check # fails on .env.example drift
996
+ ```
997
+
512
998
  ## Embedding the CLI
513
999
 
514
1000
  The yargs factory is exported under the `./commands` subpath if you want to register envx's commands inside your own tool:
@@ -542,13 +1028,21 @@ packages/envx/core/
542
1028
  │ │ └── dotenvx.ts # `dotenvx-proxy` direct passthrough to upstream
543
1029
  │ └── commands/
544
1030
  │ ├── index.ts # createCli — registers subcommands + global options
545
- │ ├── run.ts # `run [command..]`
546
- │ ├── print.ts # `print <variable>`
547
- │ ├── debug.ts # `debug`
548
- │ ├── encrypt.ts # `encrypt`
1031
+ │ ├── run.ts # `run [command..]` — load env + spawn
1032
+ │ ├── print.ts # `print <variable>` — print one value
1033
+ │ ├── debug.ts # `debug` — show resolved paths
1034
+ │ ├── encrypt.ts # `encrypt` — incl. --pattern / --secrets
549
1035
  │ ├── decrypt.ts # `decrypt`
550
- │ ├── rotate.ts # `rotate`
551
- └── expand.ts # `expand`
1036
+ │ ├── rotate.ts # `rotate` — refresh keypair across files
1037
+ ├── expand.ts # `expand` — resolve ${VAR} on stdout
1038
+ │ ├── info.ts # `info` — print resolved config
1039
+ │ ├── doctor.ts # `doctor` — health checks (CI gate)
1040
+ │ ├── template.ts # `template` — emit/check .env.example
1041
+ │ ├── diff.ts # `diff <a> <b>` — keys + value mismatches
1042
+ │ ├── hook.ts # `hook <shell>` — eval-able shell exports
1043
+ │ ├── types.ts # `types` — emit env.d.ts
1044
+ │ ├── watch.ts # `watch -- <cmd>` — restart on env change
1045
+ │ └── audit.ts # `audit` — plaintext-secret scanner
552
1046
  ├── tests/
553
1047
  │ ├── *.test.ts # unit suites
554
1048
  │ └── integration/
package/dist/auto.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"auto.js","names":[],"sources":["../src/auto.ts"],"sourcesContent":["// #region -- Side-effect entry point ----------------------\n\n// `import \"@honeycluster/envx/auto\"` (or \"/config\") loads .env into\n// process.env on import — same ergonomics as `import \"dotenv/config\"`.\n// Picks up envx.config.* and the package.json `envx.config` discovery\n// chain automatically. Use the named/default export from the package\n// root when you want an explicit handle.\n\nimport envx from \"./index.js\";\n\nenvx();\n\n// #endregion -----------------------------------------------\n"],"mappings":";;AAUA,MAAM"}
1
+ {"version":3,"file":"auto.js","names":[],"sources":["../src/auto.ts"],"sourcesContent":["// #region -- Side-effect entry point ----------------------\n\n// `import \"@super-repo/envx/auto\"` (or \"/config\") loads .env into\n// process.env on import — same ergonomics as `import \"dotenv/config\"`.\n// Picks up envx.config.* and the package.json `envx.config` discovery\n// chain automatically. Use the named/default export from the package\n// root when you want an explicit handle.\n\nimport envx from \"./index.js\";\n\nenvx();\n\n// #endregion -----------------------------------------------\n"],"mappings":";;AAUA,MAAM"}